context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Linq; using System.Reflection; using NUnit.Framework; using System.Management.Automation; using System.Collections.ObjectModel; using System.Collections.Generic; using TestParameterizedProperties; using TestPSSnapIn; namespace ReferenceTests.API { // prevents the compiler from complaining about unused fields, etc #pragma warning disable 169, 414, 0649 interface IDummyBase { int DummyBaseProperty { get; } } interface IDummy : IDummyBase { } class DummyAncestor : IDummyBase { private int AncFieldPrivated; protected int AncFieldProtected; static public int AncFieldPublic; public string AncProperty { get; set; } public int DummyBaseProperty { get { return 0; } } private void AncMethodPrivate() { } protected void AncMethodProtected() { } public void AncMethodPublic() { } public virtual void VirtualMethod() { } } class DummyDescendant : DummyAncestor { private int DescFieldPrivated; protected int DescFieldProtected; internal int DescFieldInternal; public int DescFieldPublic; public string DescProperty { get; set; } private void DescMethodPrivate() { } protected void DescMethodProtected() { } static public void DescMethodPublic() { } public override void VirtualMethod() { } } #pragma warning restore 169, 414, 0649 [TestFixture] public class PSObjectTests : ReferenceTestBase { private Collection<string> _dummyDescendantTypeNames = new Collection<string>() { typeof(DummyDescendant).FullName, typeof(DummyAncestor).FullName, typeof(Object).FullName }; private IEnumerable<string> GetPublicInstanceMembers(Type type) { var members = (from member in type.GetMembers(BindingFlags.Instance | BindingFlags.Public) where (member.MemberType & (MemberTypes.Field | MemberTypes.Property)) != 0 select member.Name).ToList(); type.GetInterfaces().ToList().ForEach( i => members.AddRange( from prop in i.GetProperties(BindingFlags.Instance | BindingFlags.Public) select prop.Name ) ); return members.Distinct(); } private IEnumerable<string> GetPublicInstanceMethods(Type type) { return from method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public) select method.Name; } [Test] public void PSObjectWrapsInstance() { var instace = new DummyDescendant(); var psobj = PSObject.AsPSObject(instace); Assert.AreSame(instace, psobj.BaseObject); Assert.AreSame(instace, psobj.ImmediateBaseObject); } [Test] public void PSObjectReflectsTypeNames() { var psobj = PSObject.AsPSObject(new DummyDescendant()); var names = psobj.TypeNames; Assert.AreEqual(_dummyDescendantTypeNames, names); } [Test] public void PSObjectReflectsProperties() { var psobj = PSObject.AsPSObject(new DummyDescendant()); var propertyNames = from prop in psobj.Properties select prop.Name; var realProperyNames = GetPublicInstanceMembers(typeof(DummyDescendant)); Assert.That(propertyNames, Is.EquivalentTo(realProperyNames)); } [Test] public void PSObjectReflectsMethods() { var psobj = PSObject.AsPSObject(new DummyDescendant()); var methodNames = from method in psobj.Methods select method.Name; var realMethodNames = GetPublicInstanceMethods(typeof(DummyDescendant)); Assert.That(methodNames, Is.EquivalentTo(realMethodNames)); } [Test] public void PSObjectReflectsMembers() { var psobj = PSObject.AsPSObject(new DummyDescendant()); var memberNames = from member in psobj.Members select member.Name; var type = typeof(DummyDescendant); var realMemberNames = GetPublicInstanceMembers(type).Concat(GetPublicInstanceMethods(type)); Assert.That(memberNames, Is.EquivalentTo(realMemberNames)); } [Test] public void AsPSObjectCannotWrapNull() { // TODO: check for exception type Assert.Throws(Is.InstanceOf(typeof(Exception)), delegate { PSObject.AsPSObject(null); }); } [Test] public void PSObjectCannotConstructNull() { // TODO: check for exception type Assert.Throws(Is.InstanceOf(typeof(Exception)), delegate { new PSObject(null); }); } [Test] [TestCase(new int[] { 1, 2 }, "1 2")] [TestCase(new object[] { 1, "foo" }, "1 foo")] [TestCase(new object[] { 1, new object[] { 1, 2 } }, "1 System.Object[]")] public void PSObjectToStringConvertsArrayCorrectly(object input, string expected) { Assert.AreEqual(expected, new PSObject(input).ToString()); } [Test, SetCulture("de-DE")] public void PSObjectToStringUsesCurrentCulture() { Assert.AreEqual("1 2,5", new PSObject(new object[] { 1, 2.5 }).ToString()); } [Test] public void ObjectWithReadOnlyParameterizedProperty() { var obj = new TestReadOnlyParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty; Assert.IsTrue(propertyInfo.IsGettable); Assert.IsFalse(propertyInfo.IsSettable); Assert.IsTrue(propertyInfo.IsInstance); Assert.AreEqual(PSMemberTypes.ParameterizedProperty, propertyInfo.MemberType); Assert.AreEqual("FileNames", propertyInfo.Name); Assert.AreEqual("System.String", propertyInfo.TypeNameOfValue); Assert.AreEqual(propertyInfo, propertyInfo.Value); Assert.AreEqual(1, propertyInfo.OverloadDefinitions.Count); Assert.AreEqual("string FileNames(int index) {get;}", propertyInfo.OverloadDefinitions[0]); } [Test] public void ObjectWithWriteOnlyParameterizedProperty() { var obj = new TestWriteOnlyParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty; Assert.IsFalse(propertyInfo.IsGettable); Assert.IsTrue(propertyInfo.IsSettable); Assert.AreEqual("void FileNames(int index) {set;}", propertyInfo.OverloadDefinitions[0]); } [Test] public void ObjectWithReadWriteOnlyParameterizedProperty() { var obj = new TestParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty; Assert.IsTrue(propertyInfo.IsGettable); Assert.IsTrue(propertyInfo.IsSettable); Assert.AreEqual("string FileNames(int index) {get;set;}", propertyInfo.OverloadDefinitions[0]); } [Test] public void ParameterizedPropertyCopy() { var obj = new TestReadOnlyParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty; propertyInfo = propertyInfo.Copy() as PSParameterizedProperty; Assert.IsTrue(propertyInfo.IsGettable); Assert.IsFalse(propertyInfo.IsSettable); Assert.IsTrue(propertyInfo.IsInstance); Assert.AreEqual(PSMemberTypes.ParameterizedProperty, propertyInfo.MemberType); Assert.AreEqual("FileNames", propertyInfo.Name); Assert.AreEqual("System.String", propertyInfo.TypeNameOfValue); Assert.AreEqual(propertyInfo, propertyInfo.Value); Assert.AreEqual(1, propertyInfo.OverloadDefinitions.Count); Assert.AreEqual("string FileNames(int index) {get;}", propertyInfo.OverloadDefinitions[0]); } [Test] public void InvokeParameterizedPropertyGetter() { var obj = new TestParameterizedProperty(new string[] {"a.txt"}); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty; object result = propertyInfo.Invoke(0); Assert.AreEqual("a.txt", result); } [Test] public void InvokeParameterizedPropertySetter() { var obj = new TestParameterizedProperty(new string[] { "a.txt" }); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty; propertyInfo.InvokeSet("b.txt", 0); Assert.AreEqual("b.txt", obj[0]); } [Test] public void CannotInvokeParameterizedPropertySetterWithInvokeMethod() { var obj = new TestParameterizedProperty(new string[] { "a.txt" }); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty; GetValueInvocationException ex = Assert.Throws<GetValueInvocationException>(() => propertyInfo.Invoke(0, "b.txt")); var innerEx = ex.InnerException as MethodException; StringAssert.StartsWith("Exception getting \"FileNames\": ", ex.Message); Assert.AreEqual("Cannot find an overload for \"FileNames\" and the argument count: \"2\".", innerEx.Message); StringAssert.StartsWith("Exception getting \"FileNames\": ", ex.ErrorRecord.Exception.Message); Assert.AreEqual("CatchFromBaseParameterizedPropertyAdapterGetValue", ex.ErrorRecord.FullyQualifiedErrorId); Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.Activity); Assert.AreEqual(ErrorCategory.NotSpecified, ex.ErrorRecord.CategoryInfo.Category); Assert.AreEqual("ParentContainsErrorRecordException", ex.ErrorRecord.CategoryInfo.Reason); Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetName); Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetType); Assert.IsNull(ex.ErrorRecord.TargetObject); Assert.IsInstanceOf(typeof(ParentContainsErrorRecordException), ex.ErrorRecord.Exception); StringAssert.StartsWith("Cannot find an overload for \"FileNames\"", innerEx.ErrorRecord.Exception.Message); Assert.AreEqual("MethodCountCouldNotFindBest", innerEx.ErrorRecord.FullyQualifiedErrorId); Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.Activity); Assert.AreEqual(ErrorCategory.NotSpecified, innerEx.ErrorRecord.CategoryInfo.Category); Assert.AreEqual("ParentContainsErrorRecordException", innerEx.ErrorRecord.CategoryInfo.Reason); Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.TargetName); Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.TargetType); Assert.IsNull(innerEx.ErrorRecord.TargetObject); Assert.IsInstanceOf(typeof(ParentContainsErrorRecordException), innerEx.ErrorRecord.Exception); } [Test] public void CannotInvokeParameterizedPropertyGetterWithInvokeSet() { var obj = new TestParameterizedProperty(new string[] { "a.txt" }); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty; SetValueInvocationException ex = Assert.Throws<SetValueInvocationException>(() => propertyInfo.InvokeSet(0)); var innerEx = ex.InnerException as MethodException; StringAssert.StartsWith("Exception setting \"FileNames\": ", ex.Message); Assert.AreEqual("Cannot find an overload for \"FileNames\" and the argument count: \"0\".", innerEx.Message); StringAssert.StartsWith("Exception setting \"FileNames\": ", ex.ErrorRecord.Exception.Message); Assert.AreEqual("CatchFromBaseAdapterParameterizedPropertySetValue", ex.ErrorRecord.FullyQualifiedErrorId); Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.Activity); Assert.AreEqual(ErrorCategory.NotSpecified, ex.ErrorRecord.CategoryInfo.Category); Assert.AreEqual("ParentContainsErrorRecordException", ex.ErrorRecord.CategoryInfo.Reason); Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetName); Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetType); Assert.IsNull(ex.ErrorRecord.TargetObject); Assert.IsInstanceOf(typeof(ParentContainsErrorRecordException), ex.ErrorRecord.Exception); StringAssert.StartsWith("Cannot find an overload for \"FileNames\"", innerEx.ErrorRecord.Exception.Message); Assert.AreEqual("MethodCountCouldNotFindBest", innerEx.ErrorRecord.FullyQualifiedErrorId); Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.Activity); Assert.AreEqual(ErrorCategory.NotSpecified, innerEx.ErrorRecord.CategoryInfo.Category); Assert.AreEqual("ParentContainsErrorRecordException", innerEx.ErrorRecord.CategoryInfo.Reason); Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.TargetName); Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.TargetType); Assert.IsNull(innerEx.ErrorRecord.TargetObject); Assert.IsInstanceOf(typeof(ParentContainsErrorRecordException), innerEx.ErrorRecord.Exception); } [Test] public void TooManyArgumentsForParameterizedPropertyInvokeSet() { var obj = new TestParameterizedProperty(new string[] { "a.txt" }); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty; SetValueInvocationException ex = Assert.Throws<SetValueInvocationException>(() => propertyInfo.InvokeSet(0, 1, 2, 3)); var innerEx = ex.InnerException as MethodException; StringAssert.StartsWith("Exception setting \"FileNames\": ", ex.Message); Assert.AreEqual("Cannot find an overload for \"FileNames\" and the argument count: \"3\".", innerEx.Message); } [Test] public void TooManyArgumentsForPSMethodInvoke() { var obj = new Object(); var psObject = new PSObject(obj); PSMethodInfo method = psObject.Methods.First(m => m.Name == "ToString"); MethodException ex = Assert.Throws<MethodException>(() => method.Invoke(1, 2, 3, 4, 5)); Assert.AreEqual("Cannot find an overload for \"ToString\" and the argument count: \"5\".", ex.Message); } [Test] public void ObjectWithOverloadedByTypeParameterizedProperty() { var obj = new TestOverloadedByTypeParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.Single(m => m.Name == "FileNames") as PSParameterizedProperty; Assert.IsTrue(propertyInfo.IsGettable); Assert.IsTrue(propertyInfo.IsSettable); Assert.AreEqual("FileNames", propertyInfo.Name); Assert.AreEqual("System.String", propertyInfo.TypeNameOfValue); Assert.AreEqual(propertyInfo, propertyInfo.Value); Assert.AreEqual(2, propertyInfo.OverloadDefinitions.Count); Assert.AreEqual("string FileNames(int index) {get;set;}", propertyInfo.OverloadDefinitions[0]); Assert.AreEqual("string FileNames(string fileName) {get;set;}", propertyInfo.OverloadDefinitions[1]); } [Test] public void ObjectWithOverloadedByArgumentNumberParameterizedProperty() { var obj = new TestOverloadedByArgumentNumbersParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.Single(m => m.Name == "Grid") as PSParameterizedProperty; Assert.IsTrue(propertyInfo.IsGettable); Assert.IsTrue(propertyInfo.IsSettable); Assert.AreEqual("Grid", propertyInfo.Name); Assert.AreEqual("System.String", propertyInfo.TypeNameOfValue); Assert.AreEqual(propertyInfo, propertyInfo.Value); Assert.AreEqual(2, propertyInfo.OverloadDefinitions.Count); Assert.AreEqual("string Grid(int x) {get;set;}", propertyInfo.OverloadDefinitions[0]); Assert.AreEqual("string Grid(int x, int y) {get;set;}", propertyInfo.OverloadDefinitions[1]); } [Test] public void InvokeOverloadedByTypeParameterizedPropertySetter() { var obj = new TestOverloadedByTypeParameterizedProperty(new [] {"a.txt"}); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.Single(m => m.Name == "FileNames") as PSParameterizedProperty; propertyInfo.InvokeSet("b.txt", "a.txt"); Assert.AreEqual("b.txt", obj[1]); } [Test] public void InvokeOverloadedByArgumentNumberParameterizedPropertyGetter() { var obj = new TestOverloadedByArgumentNumbersParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.Single(m => m.Name == "Grid") as PSParameterizedProperty; object result = propertyInfo.Invoke(1, 2); Assert.AreEqual("1, 2", result); } [Test] public void InvokeOverloadedByArgumentNumbersParameterizedPropertySetter() { var obj = new TestOverloadedByArgumentNumbersParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.Single(m => m.Name == "Grid") as PSParameterizedProperty; propertyInfo.InvokeSet("b.txt", 1, 2); Assert.AreEqual("b.txt", obj.get_Grid(1, 2)); } [Test] public void ObjectWithTwoInterfacesOneWithParameterizedProperty() { var obj = new TestInterfaceParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.Single(m => m.Name == "FileNames") as PSParameterizedProperty; Assert.IsTrue(propertyInfo.IsGettable); Assert.IsTrue(propertyInfo.IsSettable); Assert.AreEqual("FileNames", propertyInfo.Name); Assert.AreEqual("System.String", propertyInfo.TypeNameOfValue); Assert.AreEqual(1, propertyInfo.OverloadDefinitions.Count); Assert.AreEqual("string ITestParameterizedProperty.FileNames(int index) {get;set;}", propertyInfo.OverloadDefinitions[0]); } [Test] public void ObjectWithOverloadedParameterizedPropertiesWithDifferentReturnTypes() { var obj = new TestDifferentReturnTypesParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.Single(m => m.Name == "FileNames") as PSParameterizedProperty; Assert.IsTrue(propertyInfo.IsGettable); Assert.IsTrue(propertyInfo.IsSettable); Assert.AreEqual("FileNames", propertyInfo.Name); Assert.AreEqual("System.Object", propertyInfo.TypeNameOfValue); Assert.AreEqual(propertyInfo, propertyInfo.Value); Assert.AreEqual(2, propertyInfo.OverloadDefinitions.Count); Assert.AreEqual("string FileNames(int index) {get;set;}", propertyInfo.OverloadDefinitions[0]); Assert.AreEqual("int FileNames(string fileName) {get;set;}", propertyInfo.OverloadDefinitions[1]); } [Test] public void DictionaryObjectInterfaceHasItemParameterizedProperty() { var obj = new Dictionary<string, int>(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.Single(m => m.Name == "Item") as PSParameterizedProperty; Assert.IsTrue(propertyInfo.IsGettable); Assert.IsTrue(propertyInfo.IsSettable); Assert.AreEqual("Item", propertyInfo.Name); Assert.AreEqual("System.Object", propertyInfo.TypeNameOfValue); Assert.AreEqual(propertyInfo, propertyInfo.Value); Assert.AreEqual(2, propertyInfo.OverloadDefinitions.Count); Assert.AreEqual("int Item(string key) {get;set;}", propertyInfo.OverloadDefinitions[0]); Assert.AreEqual("System.Object IDictionary.Item(System.Object key) {get;set;}", propertyInfo.OverloadDefinitions[1]); } [Test] public void SetParameterizedPropertyValue() { const string expectedErrorMessage = "Cannot set the Value property for PSMemberInfo object of type \"System.Management.Automation.PSParameterizedProperty\"."; var obj = new TestParameterizedProperty(); var psObject = new PSObject(obj); var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty; var ex = Assert.Throws<ExtendedTypeSystemException>(() => propertyInfo.Value = "a"); var errorRecordException = ex.ErrorRecord.Exception as ParentContainsErrorRecordException; Assert.AreEqual(expectedErrorMessage, ex.Message); Assert.IsNull(ex.InnerException); Assert.AreEqual("CannotChangePSMethodInfoValue", ex.ErrorRecord.FullyQualifiedErrorId); Assert.AreEqual(expectedErrorMessage, errorRecordException.Message); Assert.IsNull(errorRecordException.InnerException); Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.Activity); Assert.AreEqual(ErrorCategory.NotSpecified, ex.ErrorRecord.CategoryInfo.Category); Assert.AreEqual("ParentContainsErrorRecordException", ex.ErrorRecord.CategoryInfo.Reason); Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetName); Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetType); Assert.IsNull(ex.ErrorRecord.TargetObject); } [Test] public void EnumPropertyCanBeSetWithString() { var variable = new PSVariable("foo"); variable.Options = ScopedItemOptions.None; var obj = new PSObject(variable); var optionsProperty = obj.Properties.OfType<PSProperty>().First(p => p.Name == "Options"); optionsProperty.Value = "AllScope"; Assert.AreEqual(ScopedItemOptions.AllScope, variable.Options); } class EnumFieldTestClass { public SessionStateEntryVisibility Visibility = SessionStateEntryVisibility.Public; } [Test] public void EnumFieldCanBeSetWithString() { var testClass = new EnumFieldTestClass(); testClass.Visibility = SessionStateEntryVisibility.Public; var obj = new PSObject(testClass); var property = obj.Properties.OfType<PSProperty>().First(p => p.Name == "Visibility"); property.Value = "Private"; Assert.AreEqual(SessionStateEntryVisibility.Private, testClass.Visibility); } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion namespace OpenTK.Input { /// <summary> /// The available keyboard keys. /// </summary> public enum Key : int { /// <summary>A key outside the known keys.</summary> Unknown = 0, // Modifiers /// <summary>The left shift key.</summary> ShiftLeft, /// <summary>The left shift key (equivalent to ShiftLeft).</summary> LShift = ShiftLeft, /// <summary>The right shift key.</summary> ShiftRight, /// <summary>The right shift key (equivalent to ShiftRight).</summary> RShift = ShiftRight, /// <summary>The left control key.</summary> ControlLeft, /// <summary>The left control key (equivalent to ControlLeft).</summary> LControl = ControlLeft, /// <summary>The right control key.</summary> ControlRight, /// <summary>The right control key (equivalent to ControlRight).</summary> RControl = ControlRight, /// <summary>The left alt key.</summary> AltLeft, /// <summary>The left alt key (equivalent to AltLeft.</summary> LAlt = AltLeft, /// <summary>The right alt key.</summary> AltRight, /// <summary>The right alt key (equivalent to AltRight).</summary> RAlt = AltRight, /// <summary>The left win key.</summary> WinLeft, /// <summary>The left win key (equivalent to WinLeft).</summary> LWin = WinLeft, /// <summary>The right win key.</summary> WinRight, /// <summary>The right win key (equivalent to WinRight).</summary> RWin = WinRight, /// <summary>The menu key.</summary> Menu, // Function keys (hopefully enough for most keyboards - mine has 26) // <keysymdef.h> on X11 reports up to 35 function keys. /// <summary>The F1 key.</summary> F1, /// <summary>The F2 key.</summary> F2, /// <summary>The F3 key.</summary> F3, /// <summary>The F4 key.</summary> F4, /// <summary>The F5 key.</summary> F5, /// <summary>The F6 key.</summary> F6, /// <summary>The F7 key.</summary> F7, /// <summary>The F8 key.</summary> F8, /// <summary>The F9 key.</summary> F9, /// <summary>The F10 key.</summary> F10, /// <summary>The F11 key.</summary> F11, /// <summary>The F12 key.</summary> F12, /// <summary>The F13 key.</summary> F13, /// <summary>The F14 key.</summary> F14, /// <summary>The F15 key.</summary> F15, /// <summary>The F16 key.</summary> F16, /// <summary>The F17 key.</summary> F17, /// <summary>The F18 key.</summary> F18, /// <summary>The F19 key.</summary> F19, /// <summary>The F20 key.</summary> F20, /// <summary>The F21 key.</summary> F21, /// <summary>The F22 key.</summary> F22, /// <summary>The F23 key.</summary> F23, /// <summary>The F24 key.</summary> F24, /// <summary>The F25 key.</summary> F25, /// <summary>The F26 key.</summary> F26, /// <summary>The F27 key.</summary> F27, /// <summary>The F28 key.</summary> F28, /// <summary>The F29 key.</summary> F29, /// <summary>The F30 key.</summary> F30, /// <summary>The F31 key.</summary> F31, /// <summary>The F32 key.</summary> F32, /// <summary>The F33 key.</summary> F33, /// <summary>The F34 key.</summary> F34, /// <summary>The F35 key.</summary> F35, // Direction arrows /// <summary>The up arrow key.</summary> Up, /// <summary>The down arrow key.</summary> Down, /// <summary>The left arrow key.</summary> Left, /// <summary>The right arrow key.</summary> Right, /// <summary>The enter key.</summary> Enter, /// <summary>The escape key.</summary> Escape, /// <summary>The space key.</summary> Space, /// <summary>The tab key.</summary> Tab, /// <summary>The backspace key.</summary> BackSpace, /// <summary>The backspace key (equivalent to BackSpace).</summary> Back = BackSpace, /// <summary>The insert key.</summary> Insert, /// <summary>The delete key.</summary> Delete, /// <summary>The page up key.</summary> PageUp, /// <summary>The page down key.</summary> PageDown, /// <summary>The home key.</summary> Home, /// <summary>The end key.</summary> End, /// <summary>The caps lock key.</summary> CapsLock, /// <summary>The scroll lock key.</summary> ScrollLock, /// <summary>The print screen key.</summary> PrintScreen, /// <summary>The pause key.</summary> Pause, /// <summary>The num lock key.</summary> NumLock, // Special keys /// <summary>The clear key (Keypad5 with NumLock disabled, on typical keyboards).</summary> Clear, /// <summary>The sleep key.</summary> Sleep, /*LogOff, Help, Undo, Redo, New, Open, Close, Reply, Forward, Send, Spell, Save, Calculator, // Folders and applications Documents, Pictures, Music, MediaPlayer, Mail, Browser, Messenger, // Multimedia keys Mute, PlayPause, Stop, VolumeUp, VolumeDown, TrackPrevious, TrackNext,*/ // Keypad keys /// <summary>The keypad 0 key.</summary> Keypad0, /// <summary>The keypad 1 key.</summary> Keypad1, /// <summary>The keypad 2 key.</summary> Keypad2, /// <summary>The keypad 3 key.</summary> Keypad3, /// <summary>The keypad 4 key.</summary> Keypad4, /// <summary>The keypad 5 key.</summary> Keypad5, /// <summary>The keypad 6 key.</summary> Keypad6, /// <summary>The keypad 7 key.</summary> Keypad7, /// <summary>The keypad 8 key.</summary> Keypad8, /// <summary>The keypad 9 key.</summary> Keypad9, /// <summary>The keypad divide key.</summary> KeypadDivide, /// <summary>The keypad multiply key.</summary> KeypadMultiply, /// <summary>The keypad subtract key.</summary> KeypadSubtract, /// <summary>The keypad minus key (equivalent to KeypadSubtract).</summary> KeypadMinus = KeypadSubtract, /// <summary>The keypad add key.</summary> KeypadAdd, /// <summary>The keypad plus key (equivalent to KeypadAdd).</summary> KeypadPlus = KeypadAdd, /// <summary>The keypad decimal key.</summary> KeypadDecimal, /// <summary>The keypad enter key.</summary> KeypadEnter, // Letters /// <summary>The A key.</summary> A, /// <summary>The B key.</summary> B, /// <summary>The C key.</summary> C, /// <summary>The D key.</summary> D, /// <summary>The E key.</summary> E, /// <summary>The F key.</summary> F, /// <summary>The G key.</summary> G, /// <summary>The H key.</summary> H, /// <summary>The I key.</summary> I, /// <summary>The J key.</summary> J, /// <summary>The K key.</summary> K, /// <summary>The L key.</summary> L, /// <summary>The M key.</summary> M, /// <summary>The N key.</summary> N, /// <summary>The O key.</summary> O, /// <summary>The P key.</summary> P, /// <summary>The Q key.</summary> Q, /// <summary>The R key.</summary> R, /// <summary>The S key.</summary> S, /// <summary>The T key.</summary> T, /// <summary>The U key.</summary> U, /// <summary>The V key.</summary> V, /// <summary>The W key.</summary> W, /// <summary>The X key.</summary> X, /// <summary>The Y key.</summary> Y, /// <summary>The Z key.</summary> Z, // Numbers /// <summary>The number 0 key.</summary> Number0, /// <summary>The number 1 key.</summary> Number1, /// <summary>The number 2 key.</summary> Number2, /// <summary>The number 3 key.</summary> Number3, /// <summary>The number 4 key.</summary> Number4, /// <summary>The number 5 key.</summary> Number5, /// <summary>The number 6 key.</summary> Number6, /// <summary>The number 7 key.</summary> Number7, /// <summary>The number 8 key.</summary> Number8, /// <summary>The number 9 key.</summary> Number9, // Symbols /// <summary>The tilde key.</summary> Tilde, /// <summary>The minus key.</summary> Minus, //Equal, /// <summary>The plus key.</summary> Plus, /// <summary>The left bracket key.</summary> BracketLeft, /// <summary>The left bracket key (equivalent to BracketLeft).</summary> LBracket = BracketLeft, /// <summary>The right bracket key.</summary> BracketRight, /// <summary>The right bracket key (equivalent to BracketRight).</summary> RBracket = BracketRight, /// <summary>The semicolon key.</summary> Semicolon, /// <summary>The quote key.</summary> Quote, /// <summary>The comma key.</summary> Comma, /// <summary>The period key.</summary> Period, /// <summary>The slash key.</summary> Slash, /// <summary>The backslash key.</summary> BackSlash, /// <summary>Indicates the last available keyboard key.</summary> LastKey } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using System; namespace SDKTemplate { public sealed partial class Scenario1_Define : Page { private MainPage rootPage = MainPage.Current; public Scenario1_Define() { this.InitializeComponent(); } /// <summary> /// Creates an Appointment based on the input fields and validates it. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Create_Click(object sender, RoutedEventArgs e) { string errorMessage = null; var appointment = new Windows.ApplicationModel.Appointments.Appointment(); // StartTime var date = StartTimeDatePicker.Date; var time = StartTimeTimePicker.Time; var timeZoneOffset = TimeZoneInfo.Local.GetUtcOffset(DateTime.Now); var startTime = new DateTimeOffset(date.Year, date.Month, date.Day, time.Hours, time.Minutes, 0, timeZoneOffset); appointment.StartTime = startTime; // Subject appointment.Subject = SubjectTextBox.Text; if (appointment.Subject.Length > 255) { errorMessage = "The subject cannot be greater than 255 characters."; } // Location appointment.Location = LocationTextBox.Text; if (appointment.Location.Length > 32768) { errorMessage = "The location cannot be greater than 32,768 characters."; } // Details appointment.Details = DetailsTextBox.Text; if (appointment.Details.Length > 1073741823) { errorMessage = "The details cannot be greater than 1,073,741,823 characters."; } // Duration if (DurationComboBox.SelectedIndex == 0) { // 30 minute duration is selected appointment.Duration = TimeSpan.FromMinutes(30); } else { // 1 hour duration is selected appointment.Duration = TimeSpan.FromHours(1); } // All Day appointment.AllDay = AllDayCheckBox.IsChecked.Value; // Reminder if (ReminderCheckBox.IsChecked.Value) { switch (ReminderComboBox.SelectedIndex) { case 0: appointment.Reminder = TimeSpan.FromMinutes(15); break; case 1: appointment.Reminder = TimeSpan.FromHours(1); break; case 2: appointment.Reminder = TimeSpan.FromDays(1); break; } } //Busy Status switch (BusyStatusComboBox.SelectedIndex) { case 0: appointment.BusyStatus = Windows.ApplicationModel.Appointments.AppointmentBusyStatus.Busy; break; case 1: appointment.BusyStatus = Windows.ApplicationModel.Appointments.AppointmentBusyStatus.Tentative; break; case 2: appointment.BusyStatus = Windows.ApplicationModel.Appointments.AppointmentBusyStatus.Free; break; case 3: appointment.BusyStatus = Windows.ApplicationModel.Appointments.AppointmentBusyStatus.OutOfOffice; break; case 4: appointment.BusyStatus = Windows.ApplicationModel.Appointments.AppointmentBusyStatus.WorkingElsewhere; break; } // Sensitivity switch (SensitivityComboBox.SelectedIndex) { case 0: appointment.Sensitivity = Windows.ApplicationModel.Appointments.AppointmentSensitivity.Public; break; case 1: appointment.Sensitivity = Windows.ApplicationModel.Appointments.AppointmentSensitivity.Private; break; } // Uri if (UriTextBox.Text.Length > 0) { try { appointment.Uri = new System.Uri(UriTextBox.Text); } catch (Exception) { errorMessage = "The Uri provided is invalid."; } } // Organizer // Note: Organizer can only be set if there are no invitees added to this appointment. if (OrganizerRadioButton.IsChecked.Value) { var organizer = new Windows.ApplicationModel.Appointments.AppointmentOrganizer(); // Organizer Display Name organizer.DisplayName = OrganizerDisplayNameTextBox.Text; if (organizer.DisplayName.Length > 256) { errorMessage = "The organizer display name cannot be greater than 256 characters."; } else { // Organizer Address (e.g. Email Address) organizer.Address = OrganizerAddressTextBox.Text; if (organizer.Address.Length > 321) { errorMessage = "The organizer address cannot be greater than 321 characters."; } else if (organizer.Address.Length == 0) { errorMessage = "The organizer address must be greater than 0 characters."; } else { appointment.Organizer = organizer; } } } // Invitees // Note: If the size of the Invitees list is not zero, then an Organizer cannot be set. if (InviteeRadioButton.IsChecked.Value) { var invitee = new Windows.ApplicationModel.Appointments.AppointmentInvitee(); // Invitee Display Name invitee.DisplayName = InviteeDisplayNameTextBox.Text; if (invitee.DisplayName.Length > 256) { errorMessage = "The invitee display name cannot be greater than 256 characters."; } else { // Invitee Address (e.g. Email Address) invitee.Address = InviteeAddressTextBox.Text; if (invitee.Address.Length > 321) { errorMessage = "The invitee address cannot be greater than 321 characters."; } else if (invitee.Address.Length == 0) { errorMessage = "The invitee address must be greater than 0 characters."; } else { // Invitee Role switch (RoleComboBox.SelectedIndex) { case 0: invitee.Role = Windows.ApplicationModel.Appointments.AppointmentParticipantRole.RequiredAttendee; break; case 1: invitee.Role = Windows.ApplicationModel.Appointments.AppointmentParticipantRole.OptionalAttendee; break; case 2: invitee.Role = Windows.ApplicationModel.Appointments.AppointmentParticipantRole.Resource; break; } // Invitee Response switch (ResponseComboBox.SelectedIndex) { case 0: invitee.Response = Windows.ApplicationModel.Appointments.AppointmentParticipantResponse.None; break; case 1: invitee.Response = Windows.ApplicationModel.Appointments.AppointmentParticipantResponse.Tentative; break; case 2: invitee.Response = Windows.ApplicationModel.Appointments.AppointmentParticipantResponse.Accepted; break; case 3: invitee.Response = Windows.ApplicationModel.Appointments.AppointmentParticipantResponse.Declined; break; case 4: invitee.Response = Windows.ApplicationModel.Appointments.AppointmentParticipantResponse.Unknown; break; } appointment.Invitees.Add(invitee); } } } if (errorMessage == null) { rootPage.NotifyUser("The appointment was created successfully and is valid.", NotifyType.StatusMessage); } else { rootPage.NotifyUser(errorMessage, NotifyType.ErrorMessage); } } /// <summary> /// Organizer and Invitee properties are mutually exclusive. /// This radio button enables the organizer properties while disabling the invitees. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OrganizerRadioButton_Checked(object sender, RoutedEventArgs e) { OrganizerStackPanel.Visibility = Windows.UI.Xaml.Visibility.Visible; InviteeStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } /// <summary> /// Organizer and Invitee properties are mutually exclusive. /// This radio button enables the invitees properties while disabling the organizer. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void InviteeRadioButton_Checked(object sender, RoutedEventArgs e) { InviteeStackPanel.Visibility = Windows.UI.Xaml.Visibility.Visible; OrganizerStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } /// <summary> /// Displays the combo box containing various reminder times. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ReminderCheckBox_Checked(object sender, RoutedEventArgs e) { ReminderComboBox.Visibility = Windows.UI.Xaml.Visibility.Visible; } /// <summary> /// Hides the combo box containing various reminder times. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ReminderCheckBox_UnChecked(object sender, RoutedEventArgs e) { ReminderComboBox.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } } }
// 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.Globalization; using System.IO; using System.Reflection; namespace System.CodeDom.Compiler { public abstract class CodeGenerator : ICodeGenerator { private const int ParameterMultilineThreshold = 15; private ExposedTabStringIndentedTextWriter _output; private CodeGeneratorOptions _options; private CodeTypeDeclaration _currentClass; private CodeTypeMember _currentMember; private bool _inNestedBinary = false; protected CodeTypeDeclaration CurrentClass => _currentClass; protected string CurrentTypeName => _currentClass != null ? _currentClass.Name : "<% unknown %>"; protected CodeTypeMember CurrentMember => _currentMember; protected string CurrentMemberName => _currentMember != null ? _currentMember.Name : "<% unknown %>"; protected bool IsCurrentInterface => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; protected bool IsCurrentClass => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsClass : false; protected bool IsCurrentStruct => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsStruct : false; protected bool IsCurrentEnum => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; protected bool IsCurrentDelegate => _currentClass != null && _currentClass is CodeTypeDelegate; protected int Indent { get { return _output.Indent; } set { _output.Indent = value; } } protected abstract string NullToken { get; } protected TextWriter Output => _output; protected CodeGeneratorOptions Options => _options; private void GenerateType(CodeTypeDeclaration e) { _currentClass = e; if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); } GenerateCommentStatements(e.Comments); if (e.LinePragma != null) { GenerateLinePragmaStart(e.LinePragma); } GenerateTypeStart(e); if (Options.VerbatimOrder) { foreach (CodeTypeMember member in e.Members) { GenerateTypeMember(member, e); } } else { GenerateFields(e); GenerateSnippetMembers(e); GenerateTypeConstructors(e); GenerateConstructors(e); GenerateProperties(e); GenerateEvents(e); GenerateMethods(e); GenerateNestedTypes(e); } // Nested types clobber the current class, so reset it. _currentClass = e; GenerateTypeEnd(e); if (e.LinePragma != null) { GenerateLinePragmaEnd(e.LinePragma); } if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); } } protected virtual void GenerateDirectives(CodeDirectiveCollection directives) { } private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration declaredType) { if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (member is CodeTypeDeclaration) { ((ICodeGenerator)this).GenerateCodeFromType((CodeTypeDeclaration)member, _output.InnerWriter, _options); // Nested types clobber the current class, so reset it. _currentClass = declaredType; // For nested types, comments and line pragmas are handled separately, so return here return; } if (member.StartDirectives.Count > 0) { GenerateDirectives(member.StartDirectives); } GenerateCommentStatements(member.Comments); if (member.LinePragma != null) { GenerateLinePragmaStart(member.LinePragma); } if (member is CodeMemberField) { GenerateField((CodeMemberField)member); } else if (member is CodeMemberProperty) { GenerateProperty((CodeMemberProperty)member, declaredType); } else if (member is CodeMemberMethod) { if (member is CodeConstructor) { GenerateConstructor((CodeConstructor)member, declaredType); } else if (member is CodeTypeConstructor) { GenerateTypeConstructor((CodeTypeConstructor)member); } else if (member is CodeEntryPointMethod) { GenerateEntryPointMethod((CodeEntryPointMethod)member, declaredType); } else { GenerateMethod((CodeMemberMethod)member, declaredType); } } else if (member is CodeMemberEvent) { GenerateEvent((CodeMemberEvent)member, declaredType); } else if (member is CodeSnippetTypeMember) { // Don't indent snippets, in order to preserve the column // information from the original code. This improves the debugging // experience. int savedIndent = Indent; Indent = 0; GenerateSnippetMember((CodeSnippetTypeMember)member); // Restore the indent Indent = savedIndent; // Generate an extra new line at the end of the snippet. // If the snippet is comment and this type only contains comments. // The generated code will not compile. Output.WriteLine(); } if (member.LinePragma != null) { GenerateLinePragmaEnd(member.LinePragma); } if (member.EndDirectives.Count > 0) { GenerateDirectives(member.EndDirectives); } } private void GenerateTypeConstructors(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeTypeConstructor) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeTypeConstructor imp = (CodeTypeConstructor)current; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateTypeConstructor(imp); if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } protected void GenerateNamespaces(CodeCompileUnit e) { foreach (CodeNamespace n in e.Namespaces) { ((ICodeGenerator)this).GenerateCodeFromNamespace(n, _output.InnerWriter, _options); } } protected void GenerateTypes(CodeNamespace e) { foreach (CodeTypeDeclaration c in e.Types) { if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } ((ICodeGenerator)this).GenerateCodeFromType(c, _output.InnerWriter, _options); } } bool ICodeGenerator.Supports(GeneratorSupport support) => Supports(support); void ICodeGenerator.GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; if (_output != null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } if (_output == null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString); } try { GenerateType(e); } finally { if (setLocal) { _output = null; _options = null; } } } void ICodeGenerator.GenerateCodeFromExpression(CodeExpression e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; if (_output != null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } if (_output == null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString); } try { GenerateExpression(e); } finally { if (setLocal) { _output = null; _options = null; } } } void ICodeGenerator.GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; if (_output != null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } if (_output == null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString); } try { if (e is CodeSnippetCompileUnit) { GenerateSnippetCompileUnit((CodeSnippetCompileUnit)e); } else { GenerateCompileUnit(e); } } finally { if (setLocal) { _output = null; _options = null; } } } void ICodeGenerator.GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; if (_output != null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } if (_output == null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString); } try { GenerateNamespace(e); } finally { if (setLocal) { _output = null; _options = null; } } } void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; if (_output != null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } if (_output == null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString); } try { GenerateStatement(e); } finally { if (setLocal) { _output = null; _options = null; } } } public virtual void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options) { if (_output != null) { throw new InvalidOperationException(SR.CodeGenReentrance); } _options = options ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(writer, _options.IndentString); try { CodeTypeDeclaration dummyClass = new CodeTypeDeclaration(); _currentClass = dummyClass; GenerateTypeMember(member, dummyClass); } finally { _currentClass = null; _output = null; _options = null; } } bool ICodeGenerator.IsValidIdentifier(string value) => IsValidIdentifier(value); void ICodeGenerator.ValidateIdentifier(string value) => ValidateIdentifier(value); string ICodeGenerator.CreateEscapedIdentifier(string value) => CreateEscapedIdentifier(value); string ICodeGenerator.CreateValidIdentifier(string value) => CreateValidIdentifier(value); string ICodeGenerator.GetTypeOutput(CodeTypeReference type) => GetTypeOutput(type); private void GenerateConstructors(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeConstructor) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeConstructor imp = (CodeConstructor)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateConstructor(imp, e); if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } private void GenerateEvents(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeMemberEvent) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeMemberEvent imp = (CodeMemberEvent)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateEvent(imp, e); if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } protected void GenerateExpression(CodeExpression e) { if (e is CodeArrayCreateExpression) { GenerateArrayCreateExpression((CodeArrayCreateExpression)e); } else if (e is CodeBaseReferenceExpression) { GenerateBaseReferenceExpression((CodeBaseReferenceExpression)e); } else if (e is CodeBinaryOperatorExpression) { GenerateBinaryOperatorExpression((CodeBinaryOperatorExpression)e); } else if (e is CodeCastExpression) { GenerateCastExpression((CodeCastExpression)e); } else if (e is CodeDelegateCreateExpression) { GenerateDelegateCreateExpression((CodeDelegateCreateExpression)e); } else if (e is CodeFieldReferenceExpression) { GenerateFieldReferenceExpression((CodeFieldReferenceExpression)e); } else if (e is CodeArgumentReferenceExpression) { GenerateArgumentReferenceExpression((CodeArgumentReferenceExpression)e); } else if (e is CodeVariableReferenceExpression) { GenerateVariableReferenceExpression((CodeVariableReferenceExpression)e); } else if (e is CodeIndexerExpression) { GenerateIndexerExpression((CodeIndexerExpression)e); } else if (e is CodeArrayIndexerExpression) { GenerateArrayIndexerExpression((CodeArrayIndexerExpression)e); } else if (e is CodeSnippetExpression) { GenerateSnippetExpression((CodeSnippetExpression)e); } else if (e is CodeMethodInvokeExpression) { GenerateMethodInvokeExpression((CodeMethodInvokeExpression)e); } else if (e is CodeMethodReferenceExpression) { GenerateMethodReferenceExpression((CodeMethodReferenceExpression)e); } else if (e is CodeEventReferenceExpression) { GenerateEventReferenceExpression((CodeEventReferenceExpression)e); } else if (e is CodeDelegateInvokeExpression) { GenerateDelegateInvokeExpression((CodeDelegateInvokeExpression)e); } else if (e is CodeObjectCreateExpression) { GenerateObjectCreateExpression((CodeObjectCreateExpression)e); } else if (e is CodeParameterDeclarationExpression) { GenerateParameterDeclarationExpression((CodeParameterDeclarationExpression)e); } else if (e is CodeDirectionExpression) { GenerateDirectionExpression((CodeDirectionExpression)e); } else if (e is CodePrimitiveExpression) { GeneratePrimitiveExpression((CodePrimitiveExpression)e); } else if (e is CodePropertyReferenceExpression) { GeneratePropertyReferenceExpression((CodePropertyReferenceExpression)e); } else if (e is CodePropertySetValueReferenceExpression) { GeneratePropertySetValueReferenceExpression((CodePropertySetValueReferenceExpression)e); } else if (e is CodeThisReferenceExpression) { GenerateThisReferenceExpression((CodeThisReferenceExpression)e); } else if (e is CodeTypeReferenceExpression) { GenerateTypeReferenceExpression((CodeTypeReferenceExpression)e); } else if (e is CodeTypeOfExpression) { GenerateTypeOfExpression((CodeTypeOfExpression)e); } else if (e is CodeDefaultValueExpression) { GenerateDefaultValueExpression((CodeDefaultValueExpression)e); } else { if (e == null) { throw new ArgumentNullException(nameof(e)); } else { throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } } private void GenerateFields(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeMemberField) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeMemberField imp = (CodeMemberField)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateField(imp); if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } private void GenerateSnippetMembers(CodeTypeDeclaration e) { bool hasSnippet = false; foreach (CodeTypeMember current in e.Members) { if (current is CodeSnippetTypeMember) { hasSnippet = true; _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeSnippetTypeMember imp = (CodeSnippetTypeMember)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } // Don't indent snippets, in order to preserve the column // information from the original code. This improves the debugging // experience. int savedIndent = Indent; Indent = 0; GenerateSnippetMember(imp); // Restore the indent Indent = savedIndent; if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } // Generate an extra new line at the end of the snippet. // If the snippet is comment and this type only contains comments. // The generated code will not compile. if (hasSnippet) { Output.WriteLine(); } } protected virtual void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) { GenerateDirectives(e.StartDirectives); if (e.LinePragma != null) { GenerateLinePragmaStart(e.LinePragma); } Output.WriteLine(e.Value); if (e.LinePragma != null) { GenerateLinePragmaEnd(e.LinePragma); } if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); } } private void GenerateMethods(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeMemberMethod && !(current is CodeTypeConstructor) && !(current is CodeConstructor)) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeMemberMethod imp = (CodeMemberMethod)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } if (current is CodeEntryPointMethod) { GenerateEntryPointMethod((CodeEntryPointMethod)current, e); } else { GenerateMethod(imp, e); } if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } private void GenerateNestedTypes(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeTypeDeclaration) { if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } CodeTypeDeclaration currentClass = (CodeTypeDeclaration)current; ((ICodeGenerator)this).GenerateCodeFromType(currentClass, _output.InnerWriter, _options); } } } protected virtual void GenerateCompileUnit(CodeCompileUnit e) { GenerateCompileUnitStart(e); GenerateNamespaces(e); GenerateCompileUnitEnd(e); } protected virtual void GenerateNamespace(CodeNamespace e) { GenerateCommentStatements(e.Comments); GenerateNamespaceStart(e); GenerateNamespaceImports(e); Output.WriteLine(); GenerateTypes(e); GenerateNamespaceEnd(e); } protected void GenerateNamespaceImports(CodeNamespace e) { foreach (CodeNamespaceImport imp in e.Imports) { if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateNamespaceImport(imp); if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); } } private void GenerateProperties(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeMemberProperty) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeMemberProperty imp = (CodeMemberProperty)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateProperty(imp, e); if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } protected void GenerateStatement(CodeStatement e) { if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); } if (e.LinePragma != null) { GenerateLinePragmaStart(e.LinePragma); } if (e is CodeCommentStatement) { GenerateCommentStatement((CodeCommentStatement)e); } else if (e is CodeMethodReturnStatement) { GenerateMethodReturnStatement((CodeMethodReturnStatement)e); } else if (e is CodeConditionStatement) { GenerateConditionStatement((CodeConditionStatement)e); } else if (e is CodeTryCatchFinallyStatement) { GenerateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e); } else if (e is CodeAssignStatement) { GenerateAssignStatement((CodeAssignStatement)e); } else if (e is CodeExpressionStatement) { GenerateExpressionStatement((CodeExpressionStatement)e); } else if (e is CodeIterationStatement) { GenerateIterationStatement((CodeIterationStatement)e); } else if (e is CodeThrowExceptionStatement) { GenerateThrowExceptionStatement((CodeThrowExceptionStatement)e); } else if (e is CodeSnippetStatement) { // Don't indent snippet statements, in order to preserve the column // information from the original code. This improves the debugging // experience. int savedIndent = Indent; Indent = 0; GenerateSnippetStatement((CodeSnippetStatement)e); // Restore the indent Indent = savedIndent; } else if (e is CodeVariableDeclarationStatement) { GenerateVariableDeclarationStatement((CodeVariableDeclarationStatement)e); } else if (e is CodeAttachEventStatement) { GenerateAttachEventStatement((CodeAttachEventStatement)e); } else if (e is CodeRemoveEventStatement) { GenerateRemoveEventStatement((CodeRemoveEventStatement)e); } else if (e is CodeGotoStatement) { GenerateGotoStatement((CodeGotoStatement)e); } else if (e is CodeLabeledStatement) { GenerateLabeledStatement((CodeLabeledStatement)e); } else { throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } if (e.LinePragma != null) { GenerateLinePragmaEnd(e.LinePragma); } if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); } } protected void GenerateStatements(CodeStatementCollection stmts) { foreach (CodeStatement stmt in stmts) { ((ICodeGenerator)this).GenerateCodeFromStatement(stmt, _output.InnerWriter, _options); } } protected virtual void OutputAttributeDeclarations(CodeAttributeDeclarationCollection attributes) { if (attributes.Count == 0) return; GenerateAttributeDeclarationsStart(attributes); bool first = true; foreach (CodeAttributeDeclaration current in attributes) { if (first) { first = false; } else { ContinueOnNewLine(", "); } Output.Write(current.Name); Output.Write('('); bool firstArg = true; foreach (CodeAttributeArgument arg in current.Arguments) { if (firstArg) { firstArg = false; } else { Output.Write(", "); } OutputAttributeArgument(arg); } Output.Write(')'); } GenerateAttributeDeclarationsEnd(attributes); } protected virtual void OutputAttributeArgument(CodeAttributeArgument arg) { if (!string.IsNullOrEmpty(arg.Name)) { OutputIdentifier(arg.Name); Output.Write('='); } ((ICodeGenerator)this).GenerateCodeFromExpression(arg.Value, _output.InnerWriter, _options); } protected virtual void OutputDirection(FieldDirection dir) { switch (dir) { case FieldDirection.In: break; case FieldDirection.Out: Output.Write("out "); break; case FieldDirection.Ref: Output.Write("ref "); break; } } protected virtual void OutputFieldScopeModifier(MemberAttributes attributes) { switch (attributes & MemberAttributes.VTableMask) { case MemberAttributes.New: Output.Write("new "); break; } switch (attributes & MemberAttributes.ScopeMask) { case MemberAttributes.Final: break; case MemberAttributes.Static: Output.Write("static "); break; case MemberAttributes.Const: Output.Write("const "); break; default: break; } } protected virtual void OutputMemberAccessModifier(MemberAttributes attributes) { switch (attributes & MemberAttributes.AccessMask) { case MemberAttributes.Assembly: Output.Write("internal "); break; case MemberAttributes.FamilyAndAssembly: Output.Write("internal "); /*FamANDAssem*/ break; case MemberAttributes.Family: Output.Write("protected "); break; case MemberAttributes.FamilyOrAssembly: Output.Write("protected internal "); break; case MemberAttributes.Private: Output.Write("private "); break; case MemberAttributes.Public: Output.Write("public "); break; } } protected virtual void OutputMemberScopeModifier(MemberAttributes attributes) { switch (attributes & MemberAttributes.VTableMask) { case MemberAttributes.New: Output.Write("new "); break; } switch (attributes & MemberAttributes.ScopeMask) { case MemberAttributes.Abstract: Output.Write("abstract "); break; case MemberAttributes.Final: Output.Write(""); break; case MemberAttributes.Static: Output.Write("static "); break; case MemberAttributes.Override: Output.Write("override "); break; default: switch (attributes & MemberAttributes.AccessMask) { case MemberAttributes.Family: case MemberAttributes.Public: Output.Write("virtual "); break; default: // nothing; break; } break; } } protected abstract void OutputType(CodeTypeReference typeRef); protected virtual void OutputTypeAttributes(TypeAttributes attributes, bool isStruct, bool isEnum) { switch (attributes & TypeAttributes.VisibilityMask) { case TypeAttributes.Public: case TypeAttributes.NestedPublic: Output.Write("public "); break; case TypeAttributes.NestedPrivate: Output.Write("private "); break; } if (isStruct) { Output.Write("struct "); } else if (isEnum) { Output.Write("enum "); } else { switch (attributes & TypeAttributes.ClassSemanticsMask) { case TypeAttributes.Class: if ((attributes & TypeAttributes.Sealed) == TypeAttributes.Sealed) { Output.Write("sealed "); } if ((attributes & TypeAttributes.Abstract) == TypeAttributes.Abstract) { Output.Write("abstract "); } Output.Write("class "); break; case TypeAttributes.Interface: Output.Write("interface "); break; } } } protected virtual void OutputTypeNamePair(CodeTypeReference typeRef, string name) { OutputType(typeRef); Output.Write(' '); OutputIdentifier(name); } protected virtual void OutputIdentifier(string ident) { Output.Write(ident); } protected virtual void OutputExpressionList(CodeExpressionCollection expressions) { OutputExpressionList(expressions, newlineBetweenItems: false); } protected virtual void OutputExpressionList(CodeExpressionCollection expressions, bool newlineBetweenItems) { bool first = true; Indent++; foreach (CodeExpression current in expressions) { if (first) { first = false; } else { if (newlineBetweenItems) ContinueOnNewLine(","); else Output.Write(", "); } ((ICodeGenerator)this).GenerateCodeFromExpression(current, _output.InnerWriter, _options); } Indent--; } protected virtual void OutputOperator(CodeBinaryOperatorType op) { switch (op) { case CodeBinaryOperatorType.Add: Output.Write('+'); break; case CodeBinaryOperatorType.Subtract: Output.Write('-'); break; case CodeBinaryOperatorType.Multiply: Output.Write('*'); break; case CodeBinaryOperatorType.Divide: Output.Write('/'); break; case CodeBinaryOperatorType.Modulus: Output.Write('%'); break; case CodeBinaryOperatorType.Assign: Output.Write('='); break; case CodeBinaryOperatorType.IdentityInequality: Output.Write("!="); break; case CodeBinaryOperatorType.IdentityEquality: Output.Write("=="); break; case CodeBinaryOperatorType.ValueEquality: Output.Write("=="); break; case CodeBinaryOperatorType.BitwiseOr: Output.Write('|'); break; case CodeBinaryOperatorType.BitwiseAnd: Output.Write('&'); break; case CodeBinaryOperatorType.BooleanOr: Output.Write("||"); break; case CodeBinaryOperatorType.BooleanAnd: Output.Write("&&"); break; case CodeBinaryOperatorType.LessThan: Output.Write('<'); break; case CodeBinaryOperatorType.LessThanOrEqual: Output.Write("<="); break; case CodeBinaryOperatorType.GreaterThan: Output.Write('>'); break; case CodeBinaryOperatorType.GreaterThanOrEqual: Output.Write(">="); break; } } protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollection parameters) { bool first = true; bool multiline = parameters.Count > ParameterMultilineThreshold; if (multiline) { Indent += 3; } foreach (CodeParameterDeclarationExpression current in parameters) { if (first) { first = false; } else { Output.Write(", "); } if (multiline) { ContinueOnNewLine(""); } GenerateExpression(current); } if (multiline) { Indent -= 3; } } protected abstract void GenerateArrayCreateExpression(CodeArrayCreateExpression e); protected abstract void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e); protected virtual void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpression e) { bool indentedExpression = false; Output.Write('('); GenerateExpression(e.Left); Output.Write(' '); if (e.Left is CodeBinaryOperatorExpression || e.Right is CodeBinaryOperatorExpression) { // In case the line gets too long with nested binary operators, we need to output them on // different lines. However we want to indent them to maintain readability, but this needs // to be done only once; if (!_inNestedBinary) { indentedExpression = true; _inNestedBinary = true; Indent += 3; } ContinueOnNewLine(""); } OutputOperator(e.Operator); Output.Write(' '); GenerateExpression(e.Right); Output.Write(')'); if (indentedExpression) { Indent -= 3; _inNestedBinary = false; } } protected virtual void ContinueOnNewLine(string st) => Output.WriteLine(st); protected abstract void GenerateCastExpression(CodeCastExpression e); protected abstract void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e); protected abstract void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e); protected abstract void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e); protected abstract void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e); protected abstract void GenerateIndexerExpression(CodeIndexerExpression e); protected abstract void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e); protected abstract void GenerateSnippetExpression(CodeSnippetExpression e); protected abstract void GenerateMethodInvokeExpression(CodeMethodInvokeExpression e); protected abstract void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e); protected abstract void GenerateEventReferenceExpression(CodeEventReferenceExpression e); protected abstract void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e); protected abstract void GenerateObjectCreateExpression(CodeObjectCreateExpression e); protected virtual void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpression e) { if (e.CustomAttributes.Count > 0) { OutputAttributeDeclarations(e.CustomAttributes); Output.Write(' '); } OutputDirection(e.Direction); OutputTypeNamePair(e.Type, e.Name); } protected virtual void GenerateDirectionExpression(CodeDirectionExpression e) { OutputDirection(e.Direction); GenerateExpression(e.Expression); } protected virtual void GeneratePrimitiveExpression(CodePrimitiveExpression e) { if (e.Value == null) { Output.Write(NullToken); } else if (e.Value is string) { Output.Write(QuoteSnippetString((string)e.Value)); } else if (e.Value is char) { Output.Write("'" + e.Value.ToString() + "'"); } else if (e.Value is byte) { Output.Write(((byte)e.Value).ToString(CultureInfo.InvariantCulture)); } else if (e.Value is short) { Output.Write(((short)e.Value).ToString(CultureInfo.InvariantCulture)); } else if (e.Value is int) { Output.Write(((int)e.Value).ToString(CultureInfo.InvariantCulture)); } else if (e.Value is long) { Output.Write(((long)e.Value).ToString(CultureInfo.InvariantCulture)); } else if (e.Value is float) { GenerateSingleFloatValue((float)e.Value); } else if (e.Value is double) { GenerateDoubleValue((double)e.Value); } else if (e.Value is decimal) { GenerateDecimalValue((decimal)e.Value); } else if (e.Value is bool) { if ((bool)e.Value) { Output.Write("true"); } else { Output.Write("false"); } } else { throw new ArgumentException(SR.Format(SR.InvalidPrimitiveType, e.Value.GetType().ToString())); } } protected virtual void GenerateSingleFloatValue(float s) => Output.Write(s.ToString("R", CultureInfo.InvariantCulture)); protected virtual void GenerateDoubleValue(double d) => Output.Write(d.ToString("R", CultureInfo.InvariantCulture)); protected virtual void GenerateDecimalValue(decimal d) => Output.Write(d.ToString(CultureInfo.InvariantCulture)); protected virtual void GenerateDefaultValueExpression(CodeDefaultValueExpression e) { } protected abstract void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e); protected abstract void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e); protected abstract void GenerateThisReferenceExpression(CodeThisReferenceExpression e); protected virtual void GenerateTypeReferenceExpression(CodeTypeReferenceExpression e) { OutputType(e.Type); } protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e) { Output.Write("typeof("); OutputType(e.Type); Output.Write(')'); } protected abstract void GenerateExpressionStatement(CodeExpressionStatement e); protected abstract void GenerateIterationStatement(CodeIterationStatement e); protected abstract void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e); protected virtual void GenerateCommentStatement(CodeCommentStatement e) { if (e.Comment == null) { throw new ArgumentException(SR.Format(SR.Argument_NullComment, nameof(e)), nameof(e)); } GenerateComment(e.Comment); } protected virtual void GenerateCommentStatements(CodeCommentStatementCollection e) { foreach (CodeCommentStatement comment in e) { GenerateCommentStatement(comment); } } protected abstract void GenerateComment(CodeComment e); protected abstract void GenerateMethodReturnStatement(CodeMethodReturnStatement e); protected abstract void GenerateConditionStatement(CodeConditionStatement e); protected abstract void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e); protected abstract void GenerateAssignStatement(CodeAssignStatement e); protected abstract void GenerateAttachEventStatement(CodeAttachEventStatement e); protected abstract void GenerateRemoveEventStatement(CodeRemoveEventStatement e); protected abstract void GenerateGotoStatement(CodeGotoStatement e); protected abstract void GenerateLabeledStatement(CodeLabeledStatement e); protected virtual void GenerateSnippetStatement(CodeSnippetStatement e) => Output.WriteLine(e.Value); protected abstract void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e); protected abstract void GenerateLinePragmaStart(CodeLinePragma e); protected abstract void GenerateLinePragmaEnd(CodeLinePragma e); protected abstract void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c); protected abstract void GenerateField(CodeMemberField e); protected abstract void GenerateSnippetMember(CodeSnippetTypeMember e); protected abstract void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c); protected abstract void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c); protected abstract void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c); protected abstract void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c); protected abstract void GenerateTypeConstructor(CodeTypeConstructor e); protected abstract void GenerateTypeStart(CodeTypeDeclaration e); protected abstract void GenerateTypeEnd(CodeTypeDeclaration e); protected virtual void GenerateCompileUnitStart(CodeCompileUnit e) { if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); } } protected virtual void GenerateCompileUnitEnd(CodeCompileUnit e) { if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); } } protected abstract void GenerateNamespaceStart(CodeNamespace e); protected abstract void GenerateNamespaceEnd(CodeNamespace e); protected abstract void GenerateNamespaceImport(CodeNamespaceImport e); protected abstract void GenerateAttributeDeclarationsStart(CodeAttributeDeclarationCollection attributes); protected abstract void GenerateAttributeDeclarationsEnd(CodeAttributeDeclarationCollection attributes); protected abstract bool Supports(GeneratorSupport support); protected abstract bool IsValidIdentifier(string value); protected virtual void ValidateIdentifier(string value) { if (!IsValidIdentifier(value)) { throw new ArgumentException(SR.Format(SR.InvalidIdentifier, value)); } } protected abstract string CreateEscapedIdentifier(string value); protected abstract string CreateValidIdentifier(string value); protected abstract string GetTypeOutput(CodeTypeReference value); protected abstract string QuoteSnippetString(string value); public static bool IsValidLanguageIndependentIdentifier(string value) => CSharpHelpers.IsValidTypeNameOrIdentifier(value, false); internal static bool IsValidLanguageIndependentTypeName(string value) => CSharpHelpers.IsValidTypeNameOrIdentifier(value, true); public static void ValidateIdentifiers(CodeObject e) { CodeValidator codeValidator = new CodeValidator(); // This has internal state and hence is not static codeValidator.ValidateIdentifiers(e); } } }
// 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 ReadyToRun.SuperIlc; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; /// <summary> /// A set of helper to manipulate paths into a canonicalized form to ensure user-provided paths /// match those in the ETW log. /// </summary> static class PathExtensions { /// <summary> /// Millisecond timeout for file / directory deletion. /// </summary> const int DeletionTimeoutMilliseconds = 10000; /// <summary> /// Back-off for repeated checks for directory deletion. According to my local experience [trylek], /// when the directory is opened in the file explorer, the propagation typically takes 2 seconds. /// </summary> const int DirectoryDeletionBackoffMilliseconds = 500; internal static string OSExeSuffix(this string path) => (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? path + ".exe" : path); internal static string ToAbsolutePath(this string argValue) => Path.GetFullPath(argValue); internal static string ToAbsoluteDirectoryPath(this string argValue) => argValue.ToAbsolutePath().StripTrailingDirectorySeparators(); internal static string StripTrailingDirectorySeparators(this string str) { if (String.IsNullOrWhiteSpace(str)) { return str; } while (str.Length > 0 && str[str.Length - 1] == Path.DirectorySeparatorChar) { str = str.Remove(str.Length - 1); } return str; } internal static string ConcatenatePaths(this IEnumerable<string> paths) { return string.Join(Path.PathSeparator, paths); } // TODO: this assumes we're running tests from the CoreRT root internal static string DotNetAppPath => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet" : "Tools/dotnetcli/dotnet"; internal static void RecreateDirectory(this string path) { if (Directory.Exists(path)) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Task<bool> deleteSubtreeTask = path.DeleteSubtree(); deleteSubtreeTask.Wait(); if (deleteSubtreeTask.Result) { Console.WriteLine("Deleted {0} in {1} msecs", path, stopwatch.ElapsedMilliseconds); } else { throw new Exception($"Error: Could not delete output folder {path}"); } } Directory.CreateDirectory(path); } internal static bool IsParentOf(this DirectoryInfo outputPath, DirectoryInfo inputPath) { DirectoryInfo parentInfo = inputPath.Parent; while (parentInfo != null) { if (parentInfo == outputPath) return true; parentInfo = parentInfo.Parent; } return false; } public static string FindFile(this string fileName, IEnumerable<string> paths) { foreach (string path in paths) { string fileOnPath = Path.Combine(path, fileName); if (File.Exists(fileOnPath)) { return fileOnPath; } } return null; } /// <summary> /// Parallel deletion of multiple disjunct subtrees. /// </summary> /// <param name="path">List of directories to delete</param> /// <returns>Task returning true on success, false on failure</returns> public static bool DeleteSubtrees(this string[] paths) { return DeleteSubtreesAsync(paths).Result; } private static async Task<bool> DeleteSubtreesAsync(this string[] paths) { bool succeeded = true; var tasks = new List<Task<bool>>(); foreach (string path in paths) { try { if (!Directory.Exists(path)) { // Non-existent folders are harmless w.r.t. deletion Console.WriteLine("Skipping non-existent folder: '{0}'", path); } else { Console.WriteLine("Deleting '{0}'", path); tasks.Add(path.DeleteSubtree()); } } catch (Exception ex) { Console.Error.WriteLine("Error deleting '{0}': {1}", path, ex.Message); succeeded = false; } } await Task<bool>.WhenAll(tasks); foreach (var task in tasks) { if (!task.Result) { succeeded = false; break; } } return succeeded; } private static async Task<bool> DeleteSubtree(this string folder) { Task<bool>[] subtasks = new [] { DeleteSubtreesAsync(Directory.GetDirectories(folder)), DeleteFiles(Directory.GetFiles(folder)) }; await Task<bool>.WhenAll(subtasks); bool succeeded = subtasks.All(subtask => subtask.Result); if (succeeded) { Stopwatch folderDeletion = new Stopwatch(); folderDeletion.Start(); while (Directory.Exists(folder)) { try { Directory.Delete(folder, recursive: false); } catch (DirectoryNotFoundException) { // Directory not found is OK (the directory might have been deleted during the back-off delay). } catch (Exception) { Console.WriteLine("Folder deletion failure, maybe transient ({0} msecs): '{1}'", folderDeletion.ElapsedMilliseconds, folder); } if (!Directory.Exists(folder)) { break; } if (folderDeletion.ElapsedMilliseconds > DeletionTimeoutMilliseconds) { Console.Error.WriteLine("Timed out trying to delete directory '{0}'", folder); succeeded = false; break; } Thread.Sleep(DirectoryDeletionBackoffMilliseconds); } } return succeeded; } private static async Task<bool> DeleteFiles(string[] files) { Task<bool>[] tasks = new Task<bool>[files.Length]; for (int i = 0; i < files.Length; i++) { int temp = i; tasks[i] = Task<bool>.Run(() => files[temp].DeleteFile()); } await Task<bool>.WhenAll(tasks); return tasks.All(task => task.Result); } private static bool DeleteFile(this string file) { try { File.Delete(file); return true; } catch (Exception ex) { Console.Error.WriteLine($"{file}: {ex.Message}"); return false; } } public static string[] LocateOutputFolders(string folder, string coreRootFolder, IEnumerable<CompilerRunner> runners, bool recursive) { ConcurrentBag<string> directories = new ConcurrentBag<string>(); LocateOutputFoldersAsync(folder, coreRootFolder, runners, recursive, directories).Wait(); return directories.ToArray(); } private static async Task LocateOutputFoldersAsync(string folder, string coreRootFolder, IEnumerable<CompilerRunner> runners, bool recursive, ConcurrentBag<string> directories) { if (coreRootFolder == null || !StringComparer.OrdinalIgnoreCase.Equals(folder, coreRootFolder)) { List<Task> subfolderTasks = new List<Task>(); foreach (string dir in Directory.EnumerateDirectories(folder)) { if (Path.GetExtension(dir).Equals(".out", StringComparison.OrdinalIgnoreCase)) { foreach (CompilerRunner runner in runners) { if (runner.GetOutputPath(folder) == dir) { directories.Add(dir); } } } else if (recursive) { subfolderTasks.Add(Task.Run(() => LocateOutputFoldersAsync(dir, coreRootFolder, runners, recursive, directories))); } } await Task.WhenAll(subfolderTasks); } } public static bool DeleteOutputFolders(string folder, string coreRootFolder, IEnumerable<CompilerRunner> runners, bool recursive) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Console.WriteLine("Locating output {0} {1}", (recursive ? "subtree" : "folder"), folder); string[] outputFolders = LocateOutputFolders(folder, coreRootFolder, runners, recursive); Console.WriteLine("Deleting {0} output folders", outputFolders.Length); if (DeleteSubtrees(outputFolders)) { Console.WriteLine("Successfully deleted {0} output folders in {1} msecs", outputFolders.Length, stopwatch.ElapsedMilliseconds); return true; } else { Console.Error.WriteLine("Failed deleting {0} output folders in {1} msecs", outputFolders.Length, stopwatch.ElapsedMilliseconds); return false; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataLake; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for FirewallRulesOperations. /// </summary> public static partial class FirewallRulesOperationsExtensions { /// <summary> /// Creates or updates the specified firewall rule. During update, the firewall /// rule with the specified name will be replaced with this new firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to add or replace the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to create or update. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update the firewall rule. /// </param> public static FirewallRule CreateOrUpdate(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, FirewallRule parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, accountName, firewallRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the specified firewall rule. During update, the firewall /// rule with the specified name will be replaced with this new firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to add or replace the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to create or update. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update the firewall rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FirewallRule> CreateOrUpdateAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, FirewallRule parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the specified firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to update the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to update. /// </param> /// <param name='parameters'> /// Parameters supplied to update the firewall rule. /// </param> public static FirewallRule Update(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, UpdateFirewallRuleParameters parameters = default(UpdateFirewallRuleParameters)) { return operations.UpdateAsync(resourceGroupName, accountName, firewallRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates the specified firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to update the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to update. /// </param> /// <param name='parameters'> /// Parameters supplied to update the firewall rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FirewallRule> UpdateAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, UpdateFirewallRuleParameters parameters = default(UpdateFirewallRuleParameters), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified firewall rule from the specified Data Lake Store /// account /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to delete. /// </param> public static void Delete(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName) { operations.DeleteAsync(resourceGroupName, accountName, firewallRuleName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified firewall rule from the specified Data Lake Store /// account /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to delete. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified Data Lake Store firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to retrieve. /// </param> public static FirewallRule Get(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName) { return operations.GetAsync(resourceGroupName, accountName, firewallRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified Data Lake Store firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to retrieve. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FirewallRule> GetAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rules. /// </param> public static IPage<FirewallRule> ListByAccount(this IFirewallRulesOperations operations, string resourceGroupName, string accountName) { return operations.ListByAccountAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rules. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FirewallRule>> ListByAccountAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<FirewallRule> ListByAccountNext(this IFirewallRulesOperations operations, string nextPageLink) { return operations.ListByAccountNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FirewallRule>> ListByAccountNextAsync(this IFirewallRulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// This file was automatically generated by the PetaPoco T4 Template // Do not make changes directly to this file - edit the template instead // // The following connection settings were used to generate this file // // Connection String Name: `local` // Provider: `System.Data.SqlClient` // Connection String: `Server=(localdb)\ProjectsV12;Integrated Security=SSPI;Database=IbaMonitoring.SQL` // Schema: `` // Include Views: `False` // Factory Name: `SqlClientFactory` // <auto-generated /> // This file was generated by a T4 template. // Don't change it directly as your change would get overwritten. Instead, make changes // to the .tt file (i.e. the T4 template) and save it to regenerate this file. // Make sure the compiler doesn't complain about missing Xml comments #pragma warning disable 1591 using System; using NServiceKit.OrmLite; using NServiceKit.DataAnnotations; using NServiceKit.DesignPatterns.Model; using System.ComponentModel.DataAnnotations; namespace IbaMonitoring.ServiceTests.Orm { [Alias("IbaProgram")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class IbaProgram : IHasId<Guid> { [Alias("IbaProgramId")] [Required] public Guid Id { get; set;} public string ProgramDescription { get; set;} } [Alias("Location")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class Location : IHasId<Guid> { [Alias("LocationId")] [Required] public Guid Id { get; set;} [Required] public string LocationName { get; set;} public decimal? Latitude { get; set;} public decimal? Longitude { get; set;} [Required] public Guid LocationTypeId { get; set;} public Guid? ParentLocationId { get; set;} public string CodeName { get; set;} } [Alias("Lookup")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class Lookup : IHasId<Guid> { [Alias("LookupId")] [Required] public Guid Id { get; set;} [Required] public string Value { get; set;} public Guid? ParentLookupId { get; set;} } [Alias("Observation")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class Observation : IHasId<long> { [Alias("ObservationId")] [AutoIncrement] public long Id { get; set;} [Required] public Guid EventId { get; set;} [Required] public Guid SpeciesId { get; set;} public string Comments { get; set;} [Required] public Guid ObservationTypeId { get; set;} } [Alias("Person")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class Person : IHasId<Guid> { [Alias("PersonId")] [Required] public Guid Id { get; set;} [Required] public string FirstName { get; set;} [Required] public string LastName { get; set;} public string OpenId { get; set;} public string EmailAddress { get; set;} public string PhoneNumber { get; set;} [Required] public short PersonStatus { get; set;} [Required] public short PersonRole { get; set;} [Required] public bool HasBeenTrained { get; set;} [Required] public bool HasClipboard { get; set;} public string Address1 { get; set;} public string Address2 { get; set;} public string City { get; set;} public string State { get; set;} public string ZipCode { get; set;} public string Country { get; set;} } [Alias("PointSurvey")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class PointSurvey : IHasId<Guid> { [Alias("EventId")] [Required] public Guid Id { get; set;} public Guid? SiteVisitId { get; set;} [Required] public Guid LocationId { get; set;} [Required] public DateTime StartTime { get; set;} [Required] public DateTime EndTime { get; set;} public byte? NoiseCode { get; set;} } [Alias("Season")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class Season : IHasId<Guid> { [Alias("SeasonId")] [Required] public Guid Id { get; set;} [Required] public string SeasonDescription { get; set;} [Required] public Guid IbaProgramId { get; set;} public DateTime? StartWeek { get; set;} public DateTime? EndWeek { get; set;} } [Alias("SiteBoundary")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class SiteBoundary : IHasId<int> { [Alias("SiteBoundaryId")] [AutoIncrement] public int Id { get; set;} [Required] public Guid SiteId { get; set;} [Required] public decimal Latitude { get; set;} [Required] public decimal Longitude { get; set;} [Required] public int VertexSequence { get; set;} } [Alias("SiteCondition")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class SiteCondition : IHasId<Guid> { [Alias("ConditionId")] [Required] public Guid Id { get; set;} [Required] public int Temperature { get; set;} [Required] public string Scale { get; set;} [Required] public byte Wind { get; set;} [Required] public byte Sky { get; set;} [Required] public Guid SiteVisitId { get; set;} } [Alias("SiteVisit")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class SiteVisit : IHasId<Guid> { [Alias("EventId")] [Required] public Guid Id { get; set;} [Required] public bool IsDataEntryComplete { get; set;} [Required] public Guid LocationId { get; set;} [Required] public DateTime StartTime { get; set;} [Required] public DateTime EndTime { get; set;} [Required] public Guid StartConditionId { get; set;} public Guid? EndConditionId { get; set;} public Guid? ObserverId { get; set;} public Guid? RecorderId { get; set;} public string Comments { get; set;} [Compute] public int? StartYear { get; set;} } [Alias("Species")] [Schema("dbo")] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public partial class Species : IHasId<Guid> { [Alias("SpeciesId")] [Required] public Guid Id { get; set;} [Required] public string AlphaCode { get; set;} public string CommonName { get; set;} public string ScientificName { get; set;} [Required] public int WarningCount { get; set;} [Required] public bool UseForCommunityMeasures { get; set;} public string MigrationGuild { get; set;} public string ConservationGuild { get; set;} } } #pragma warning restore 1591
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Runtime.Serialization { using System; using System.IO; using System.Xml; using System.Security; using System.Collections; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.Serialization.Formatters; using System.Collections.Generic; #if !NO_CONFIGURATION using System.Runtime.Serialization.Configuration; #endif using System.Reflection; public sealed class NetDataContractSerializer : XmlObjectSerializer, IFormatter { XmlDictionaryString rootName; XmlDictionaryString rootNamespace; StreamingContext context; SerializationBinder binder; ISurrogateSelector surrogateSelector; int maxItemsInObjectGraph; bool ignoreExtensionDataObject; FormatterAssemblyStyle assemblyFormat; DataContract cachedDataContract; static Hashtable typeNameCache = new Hashtable(); public NetDataContractSerializer() : this(new StreamingContext(StreamingContextStates.All)) { } public NetDataContractSerializer(StreamingContext context) : this(context, Int32.MaxValue, false, FormatterAssemblyStyle.Full, null) { } public NetDataContractSerializer(StreamingContext context, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, FormatterAssemblyStyle assemblyFormat, ISurrogateSelector surrogateSelector) { Initialize(context, maxItemsInObjectGraph, ignoreExtensionDataObject, assemblyFormat, surrogateSelector); } public NetDataContractSerializer(string rootName, string rootNamespace) : this(rootName, rootNamespace, new StreamingContext(StreamingContextStates.All), Int32.MaxValue, false, FormatterAssemblyStyle.Full, null) { } public NetDataContractSerializer(string rootName, string rootNamespace, StreamingContext context, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, FormatterAssemblyStyle assemblyFormat, ISurrogateSelector surrogateSelector) { XmlDictionary dictionary = new XmlDictionary(2); Initialize(dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), context, maxItemsInObjectGraph, ignoreExtensionDataObject, assemblyFormat, surrogateSelector); } public NetDataContractSerializer(XmlDictionaryString rootName, XmlDictionaryString rootNamespace) : this(rootName, rootNamespace, new StreamingContext(StreamingContextStates.All), Int32.MaxValue, false, FormatterAssemblyStyle.Full, null) { } public NetDataContractSerializer(XmlDictionaryString rootName, XmlDictionaryString rootNamespace, StreamingContext context, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, FormatterAssemblyStyle assemblyFormat, ISurrogateSelector surrogateSelector) { Initialize(rootName, rootNamespace, context, maxItemsInObjectGraph, ignoreExtensionDataObject, assemblyFormat, surrogateSelector); } void Initialize(StreamingContext context, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, FormatterAssemblyStyle assemblyFormat, ISurrogateSelector surrogateSelector) { this.context = context; if (maxItemsInObjectGraph < 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxItemsInObjectGraph", SR.GetString(SR.ValueMustBeNonNegative))); this.maxItemsInObjectGraph = maxItemsInObjectGraph; this.ignoreExtensionDataObject = ignoreExtensionDataObject; this.surrogateSelector = surrogateSelector; this.AssemblyFormat = assemblyFormat; } void Initialize(XmlDictionaryString rootName, XmlDictionaryString rootNamespace, StreamingContext context, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, FormatterAssemblyStyle assemblyFormat, ISurrogateSelector surrogateSelector) { Initialize(context, maxItemsInObjectGraph, ignoreExtensionDataObject, assemblyFormat, surrogateSelector); this.rootName = rootName; this.rootNamespace = rootNamespace; } static bool? unsafeTypeForwardingEnabled; internal static bool UnsafeTypeForwardingEnabled { [Fx.Tag.SecurityNote(Critical = "Calls Security Critical method NetDataContractSerializerSection.TryUnsafeGetSection.", Safe = "The ConfigSection instance is not leaked.")] [SecuritySafeCritical] get { if (unsafeTypeForwardingEnabled == null) { #if NO_CONFIGURATION unsafeTypeForwardingEnabled = false; #else NetDataContractSerializerSection section; if (NetDataContractSerializerSection.TryUnsafeGetSection(out section)) { unsafeTypeForwardingEnabled = section.EnableUnsafeTypeForwarding; } else { unsafeTypeForwardingEnabled = false; } #endif } Fx.Assert(unsafeTypeForwardingEnabled != null, "unsafeTypeForwardingEnabled should not be null."); return unsafeTypeForwardingEnabled.Value; } } public StreamingContext Context { get { return context; } set { context = value; } } public SerializationBinder Binder { get { return binder; } set { binder = value; } } public ISurrogateSelector SurrogateSelector { get { return surrogateSelector; } set { surrogateSelector = value; } } public FormatterAssemblyStyle AssemblyFormat { get { return assemblyFormat; } set { if (value != FormatterAssemblyStyle.Full && value != FormatterAssemblyStyle.Simple) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.InvalidAssemblyFormat, value))); assemblyFormat = value; } } public int MaxItemsInObjectGraph { get { return maxItemsInObjectGraph; } } public bool IgnoreExtensionDataObject { get { return ignoreExtensionDataObject; } } public void Serialize(Stream stream, object graph) { base.WriteObject(stream, graph); } public object Deserialize(Stream stream) { return base.ReadObject(stream); } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) { Hashtable surrogateDataContracts = null; DataContract contract = GetDataContract(graph, ref surrogateDataContracts); InternalWriteStartObject(writer, graph, contract); InternalWriteObjectContent(writer, graph, contract, surrogateDataContracts); InternalWriteEndObject(writer); } public override void WriteObject(XmlWriter writer, object graph) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteStartObject(XmlWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteObjectContent(XmlWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteEndObject(XmlWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { Hashtable surrogateDataContracts = null; DataContract contract = GetDataContract(graph, ref surrogateDataContracts); InternalWriteStartObject(writer, graph, contract); } void InternalWriteStartObject(XmlWriterDelegator writer, object graph, DataContract contract) { WriteRootElement(writer, contract, rootName, rootNamespace, CheckIfNeedsContractNsAtRoot(rootName, rootNamespace, contract)); } public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { Hashtable surrogateDataContracts = null; DataContract contract = GetDataContract(graph, ref surrogateDataContracts); InternalWriteObjectContent(writer, graph, contract, surrogateDataContracts); } void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContract contract, Hashtable surrogateDataContracts) { if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); if (IsRootXmlAny(rootName, contract)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.IsAnyNotSupportedByNetDataContractSerializer, contract.UnderlyingType))); } else if (graph == null) { WriteNull(writer); } else { Type graphType = graph.GetType(); if (contract.UnderlyingType != graphType) contract = GetDataContract(graph, ref surrogateDataContracts); XmlObjectSerializerWriteContext context = null; if (contract.CanContainReferences) { context = XmlObjectSerializerWriteContext.CreateContext(this, surrogateDataContracts); context.HandleGraphAtTopLevel(writer, graph, contract); } WriteClrTypeInfo(writer, contract, binder); contract.WriteXmlValue(writer, graph, context); } } // Update the overloads whenever you are changing this method internal static void WriteClrTypeInfo(XmlWriterDelegator writer, DataContract dataContract, SerializationBinder binder) { if (!dataContract.IsISerializable && !(dataContract is SurrogateDataContract)) { TypeInformation typeInformation = null; Type clrType = dataContract.OriginalUnderlyingType; string clrTypeName = null; string clrAssemblyName = null; if (binder != null) { binder.BindToName(clrType, out clrAssemblyName, out clrTypeName); } if (clrTypeName == null) { typeInformation = NetDataContractSerializer.GetTypeInformation(clrType); clrTypeName = typeInformation.FullTypeName; } if (clrAssemblyName == null) { clrAssemblyName = (typeInformation == null) ? NetDataContractSerializer.GetTypeInformation(clrType).AssemblyString : typeInformation.AssemblyString; // Throw in the [TypeForwardedFrom] case to prevent a partially trusted assembly from forwarding itself to an assembly with higher privileges if (!UnsafeTypeForwardingEnabled && !clrType.Assembly.IsFullyTrusted && !IsAssemblyNameForwardingSafe(clrType.Assembly.FullName, clrAssemblyName)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.TypeCannotBeForwardedFrom, DataContract.GetClrTypeFullName(clrType), clrType.Assembly.FullName, clrAssemblyName))); } } WriteClrTypeInfo(writer, clrTypeName, clrAssemblyName); } } // Update the overloads whenever you are changing this method internal static void WriteClrTypeInfo(XmlWriterDelegator writer, Type dataContractType, SerializationBinder binder, string defaultClrTypeName, string defaultClrAssemblyName) { string clrTypeName = null; string clrAssemblyName = null; if (binder != null) { binder.BindToName(dataContractType, out clrAssemblyName, out clrTypeName); } if (clrTypeName == null) { clrTypeName = defaultClrTypeName; } if (clrAssemblyName == null) { clrAssemblyName = defaultClrAssemblyName; } WriteClrTypeInfo(writer, clrTypeName, clrAssemblyName); } // Update the overloads whenever you are changing this method internal static void WriteClrTypeInfo(XmlWriterDelegator writer, Type dataContractType, SerializationBinder binder, SerializationInfo serInfo) { TypeInformation typeInformation = null; string clrTypeName = null; string clrAssemblyName = null; if (binder != null) { binder.BindToName(dataContractType, out clrAssemblyName, out clrTypeName); } if (clrTypeName == null) { if (serInfo.IsFullTypeNameSetExplicit) { clrTypeName = serInfo.FullTypeName; } else { typeInformation = NetDataContractSerializer.GetTypeInformation(serInfo.ObjectType); clrTypeName = typeInformation.FullTypeName; } } if (clrAssemblyName == null) { if (serInfo.IsAssemblyNameSetExplicit) { clrAssemblyName = serInfo.AssemblyName; } else { clrAssemblyName = (typeInformation == null) ? NetDataContractSerializer.GetTypeInformation(serInfo.ObjectType).AssemblyString : typeInformation.AssemblyString; } } WriteClrTypeInfo(writer, clrTypeName, clrAssemblyName); } static void WriteClrTypeInfo(XmlWriterDelegator writer, string clrTypeName, string clrAssemblyName) { if (clrTypeName != null) writer.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.ClrTypeLocalName, DictionaryGlobals.SerializationNamespace, DataContract.GetClrTypeString(clrTypeName)); if (clrAssemblyName != null) writer.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.ClrAssemblyLocalName, DictionaryGlobals.SerializationNamespace, DataContract.GetClrTypeString(clrAssemblyName)); } public override void WriteEndObject(XmlDictionaryWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } internal override void InternalWriteEndObject(XmlWriterDelegator writer) { writer.WriteEndElement(); } public override object ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/); } public override object ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlDictionaryReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); // verifyObjectName has no effect in SharedType mode if (!IsStartElement(xmlReader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.GetString(SR.ExpectingElementAtDeserialize, XmlNodeType.Element), xmlReader)); } XmlObjectSerializerReadContext context = XmlObjectSerializerReadContext.CreateContext(this); return context.InternalDeserialize(xmlReader, null, null, null); } internal override bool InternalIsStartObject(XmlReaderDelegator reader) { return IsStartElement(reader); } internal DataContract GetDataContract(object obj, ref Hashtable surrogateDataContracts) { return GetDataContract(((obj == null) ? Globals.TypeOfObject : obj.GetType()), ref surrogateDataContracts); } internal DataContract GetDataContract(Type type, ref Hashtable surrogateDataContracts) { return GetDataContract(type.TypeHandle, type, ref surrogateDataContracts); } internal DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type, ref Hashtable surrogateDataContracts) { DataContract dataContract = GetDataContractFromSurrogateSelector(surrogateSelector, Context, typeHandle, type, ref surrogateDataContracts); if (dataContract != null) return dataContract; if (cachedDataContract == null) { dataContract = DataContract.GetDataContract(typeHandle, type, SerializationMode.SharedType); cachedDataContract = dataContract; return dataContract; } DataContract currentCachedDataContract = cachedDataContract; if (currentCachedDataContract.UnderlyingType.TypeHandle.Equals(typeHandle)) return currentCachedDataContract; return DataContract.GetDataContract(typeHandle, type, SerializationMode.SharedType); } [Fx.Tag.SecurityNote(Critical = "Calls the critical methods of ISurrogateSelector", Safe = "Demands for FullTrust")] [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] [MethodImpl(MethodImplOptions.NoInlining)] static ISerializationSurrogate GetSurrogate(Type type, ISurrogateSelector surrogateSelector, StreamingContext context) { ISurrogateSelector surrogateSelectorNotUsed; return surrogateSelector.GetSurrogate(type, context, out surrogateSelectorNotUsed); } internal static DataContract GetDataContractFromSurrogateSelector(ISurrogateSelector surrogateSelector, StreamingContext context, RuntimeTypeHandle typeHandle, Type type, ref Hashtable surrogateDataContracts) { if (surrogateSelector == null) return null; if (type == null) type = Type.GetTypeFromHandle(typeHandle); DataContract builtInDataContract = DataContract.GetBuiltInDataContract(type); if (builtInDataContract != null) return builtInDataContract; if (surrogateDataContracts != null) { DataContract cachedSurrogateContract = (DataContract)surrogateDataContracts[type]; if (cachedSurrogateContract != null) return cachedSurrogateContract; } DataContract surrogateContract = null; ISerializationSurrogate surrogate = GetSurrogate(type, surrogateSelector, context); if (surrogate != null) surrogateContract = new SurrogateDataContract(type, surrogate); else if (type.IsArray) { Type elementType = type.GetElementType(); DataContract itemContract = GetDataContractFromSurrogateSelector(surrogateSelector, context, elementType.TypeHandle, elementType, ref surrogateDataContracts); if (itemContract == null) itemContract = DataContract.GetDataContract(elementType.TypeHandle, elementType, SerializationMode.SharedType); surrogateContract = new CollectionDataContract(type, itemContract); } if (surrogateContract != null) { if (surrogateDataContracts == null) surrogateDataContracts = new Hashtable(); surrogateDataContracts.Add(type, surrogateContract); return surrogateContract; } return null; } internal static TypeInformation GetTypeInformation(Type type) { TypeInformation typeInformation = null; object typeInformationObject = typeNameCache[type]; if (typeInformationObject == null) { bool hasTypeForwardedFrom; string assemblyName = DataContract.GetClrAssemblyName(type, out hasTypeForwardedFrom); typeInformation = new TypeInformation(DataContract.GetClrTypeFullNameUsingTypeForwardedFromAttribute(type), assemblyName, hasTypeForwardedFrom); lock (typeNameCache) { typeNameCache[type] = typeInformation; } } else { typeInformation = (TypeInformation)typeInformationObject; } return typeInformation; } static bool IsAssemblyNameForwardingSafe(string originalAssemblyName, string newAssemblyName) { if (originalAssemblyName == newAssemblyName) { return true; } AssemblyName originalAssembly = new AssemblyName(originalAssemblyName); AssemblyName newAssembly = new AssemblyName(newAssemblyName); // mscorlib will get loaded by the runtime regardless of its string casing or its public key token, // so setting the assembly name to mscorlib is always unsafe if (string.Equals(newAssembly.Name, Globals.MscorlibAssemblySimpleName, StringComparison.OrdinalIgnoreCase) || string.Equals(newAssembly.Name, Globals.MscorlibFileName, StringComparison.OrdinalIgnoreCase)) { return false; } return IsPublicKeyTokenForwardingSafe(originalAssembly.GetPublicKeyToken(), newAssembly.GetPublicKeyToken()); } static bool IsPublicKeyTokenForwardingSafe(byte[] sourceToken, byte[] destinationToken) { if (sourceToken == null || destinationToken == null || sourceToken.Length == 0 || destinationToken.Length == 0 || sourceToken.Length != destinationToken.Length) { return false; } for (int i = 0; i < sourceToken.Length; i++) { if (sourceToken[i] != destinationToken[i]) { return false; } } return true; } } }
// Visual Studio Shared Project // 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.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; namespace Microsoft.VisualStudioTools.Project { internal class FileNode : HierarchyNode, IDiskBasedNode { private bool _isLinkFile; private uint _docCookie; private static readonly string[] _defaultOpensWithDesignViewExtensions = new[] { ".aspx", ".ascx", ".asax", ".asmx", ".xsd", ".resource", ".xaml" }; private static readonly string[] _supportsDesignViewExtensions = new[] { ".aspx", ".ascx", ".asax", ".asmx" }; private static readonly string[] _supportsDesignViewSubTypes = new[] { ProjectFileAttributeValue.Code, ProjectFileAttributeValue.Form, ProjectFileAttributeValue.UserControl, ProjectFileAttributeValue.Component, ProjectFileAttributeValue.Designer }; private string _caption; #region static fields #if !DEV14_OR_LATER private static Dictionary<string, int> extensionIcons; #endif #endregion #region overriden Properties public override bool DefaultOpensWithDesignView { get { // ASPX\ASCX files support design view but should be opened by default with // LOGVIEWID_Primary - this is because they support design and html view which // is a tools option setting for them. If we force designview this option // gets bypassed. We do a similar thing for asax/asmx/xsd. By doing so, we don't force // the designer to be invoked when double-clicking on the - it will now go through the // shell's standard open mechanism. string extension = Path.GetExtension(Url); return !_defaultOpensWithDesignViewExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) && !IsCodeBehindFile && SupportsDesignView; } } public override bool SupportsDesignView { get { if (ItemNode != null && !ItemNode.IsExcluded) { string extension = Path.GetExtension(Url); if (_supportsDesignViewExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) || IsCodeBehindFile) { return true; } else { var subType = ItemNode.GetMetadata("SubType"); if (subType != null && _supportsDesignViewExtensions.Contains(subType, StringComparer.OrdinalIgnoreCase)) { return true; } } } return false; } } public override bool IsNonMemberItem { get { return ItemNode is AllFilesProjectElement; } } /// <summary> /// overwrites of the generic hierarchyitem. /// </summary> [System.ComponentModel.BrowsableAttribute(false)] public override string Caption { get { return _caption; } } private void UpdateCaption() { // Use LinkedIntoProjectAt property if available string caption = this.ItemNode.GetMetadata(ProjectFileConstants.LinkedIntoProjectAt); if (caption == null || caption.Length == 0) { // Otherwise use filename caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include); caption = Path.GetFileName(caption); } _caption = caption; } public override string GetEditLabel() { if (IsLinkFile) { // cannot rename link files return null; } return Caption; } #if !DEV14_OR_LATER public override int ImageIndex { get { // Check if the file is there. if (!this.CanShowDefaultIcon()) { return (int)ProjectNode.ImageName.MissingFile; } //Check for known extensions int imageIndex; string extension = Path.GetExtension(this.FileName); if ((string.IsNullOrEmpty(extension)) || (!extensionIcons.TryGetValue(extension, out imageIndex))) { // Missing or unknown extension; let the base class handle this case. return base.ImageIndex; } // The file type is known and there is an image for it in the image list. return imageIndex; } } #endif public uint DocCookie { get { return this._docCookie; } set { this._docCookie = value; } } public override bool IsLinkFile { get { return _isLinkFile; } } internal void SetIsLinkFile(bool value) { _isLinkFile = value; } protected override VSOVERLAYICON OverlayIconIndex { get { if (IsLinkFile) { return VSOVERLAYICON.OVERLAYICON_SHORTCUT; } return VSOVERLAYICON.OVERLAYICON_NONE; } } public override Guid ItemTypeGuid { get { return VSConstants.GUID_ItemType_PhysicalFile; } } public override int MenuCommandId { get { return VsMenus.IDM_VS_CTXT_ITEMNODE; } } public override string Url { get { return ItemNode.Url; } } #endregion #region ctor #if !DEV14_OR_LATER [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static FileNode() { // Build the dictionary with the mapping between some well known extensions // and the index of the icons inside the standard image list. extensionIcons = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); extensionIcons.Add(".aspx", (int)ProjectNode.ImageName.WebForm); extensionIcons.Add(".asax", (int)ProjectNode.ImageName.GlobalApplicationClass); extensionIcons.Add(".asmx", (int)ProjectNode.ImageName.WebService); extensionIcons.Add(".ascx", (int)ProjectNode.ImageName.WebUserControl); extensionIcons.Add(".asp", (int)ProjectNode.ImageName.ASPPage); extensionIcons.Add(".config", (int)ProjectNode.ImageName.WebConfig); extensionIcons.Add(".htm", (int)ProjectNode.ImageName.HTMLPage); extensionIcons.Add(".html", (int)ProjectNode.ImageName.HTMLPage); extensionIcons.Add(".css", (int)ProjectNode.ImageName.StyleSheet); extensionIcons.Add(".xsl", (int)ProjectNode.ImageName.StyleSheet); extensionIcons.Add(".vbs", (int)ProjectNode.ImageName.ScriptFile); extensionIcons.Add(".js", (int)ProjectNode.ImageName.ScriptFile); extensionIcons.Add(".wsf", (int)ProjectNode.ImageName.ScriptFile); extensionIcons.Add(".txt", (int)ProjectNode.ImageName.TextFile); extensionIcons.Add(".resx", (int)ProjectNode.ImageName.Resources); extensionIcons.Add(".rc", (int)ProjectNode.ImageName.Resources); extensionIcons.Add(".bmp", (int)ProjectNode.ImageName.Bitmap); extensionIcons.Add(".ico", (int)ProjectNode.ImageName.Icon); extensionIcons.Add(".gif", (int)ProjectNode.ImageName.Image); extensionIcons.Add(".jpg", (int)ProjectNode.ImageName.Image); extensionIcons.Add(".png", (int)ProjectNode.ImageName.Image); extensionIcons.Add(".map", (int)ProjectNode.ImageName.ImageMap); extensionIcons.Add(".wav", (int)ProjectNode.ImageName.Audio); extensionIcons.Add(".mid", (int)ProjectNode.ImageName.Audio); extensionIcons.Add(".midi", (int)ProjectNode.ImageName.Audio); extensionIcons.Add(".avi", (int)ProjectNode.ImageName.Video); extensionIcons.Add(".mov", (int)ProjectNode.ImageName.Video); extensionIcons.Add(".mpg", (int)ProjectNode.ImageName.Video); extensionIcons.Add(".mpeg", (int)ProjectNode.ImageName.Video); extensionIcons.Add(".cab", (int)ProjectNode.ImageName.CAB); extensionIcons.Add(".jar", (int)ProjectNode.ImageName.JAR); extensionIcons.Add(".xslt", (int)ProjectNode.ImageName.XSLTFile); extensionIcons.Add(".xsd", (int)ProjectNode.ImageName.XMLSchema); extensionIcons.Add(".xml", (int)ProjectNode.ImageName.XMLFile); extensionIcons.Add(".pfx", (int)ProjectNode.ImageName.PFX); extensionIcons.Add(".snk", (int)ProjectNode.ImageName.SNK); } #endif /// <summary> /// Constructor for the FileNode /// </summary> /// <param name="root">Root of the hierarchy</param> /// <param name="e">Associated project element</param> public FileNode(ProjectNode root, ProjectElement element) : base(root, element) { UpdateCaption(); } #endregion #region overridden methods protected override NodeProperties CreatePropertiesObject() { if (IsLinkFile) { return new LinkFileNodeProperties(this); } else if (IsNonMemberItem) { return new ExcludedFileNodeProperties(this); } return new IncludedFileNodeProperties(this); } /// <summary> /// Get an instance of the automation object for a FileNode /// </summary> /// <returns>An instance of the Automation.OAFileNode if succeeded</returns> public override object GetAutomationObject() { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return null; } return new Automation.OAFileItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this); } /// <summary> /// Renames a file node. /// </summary> /// <param name="label">The new name.</param> /// <returns>An errorcode for failure or S_OK.</returns> /// <exception cref="InvalidOperationException" if the file cannot be validated> /// <devremark> /// We are going to throw instead of showing messageboxes, since this method is called from various places where a dialog box does not make sense. /// For example the FileNodeProperties are also calling this method. That should not show directly a messagebox. /// Also the automation methods are also calling SetEditLabel /// </devremark> public override int SetEditLabel(string label) { // IMPORTANT NOTE: This code will be called when a parent folder is renamed. As such, it is // expected that we can be called with a label which is the same as the current // label and this should not be considered a NO-OP. if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return VSConstants.E_FAIL; } // Validate the filename. if (String.IsNullOrEmpty(label)) { throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label)); } else if (label.Length > NativeMethods.MAX_PATH) { throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label)); } else if (Utilities.IsFileNameInvalid(label)) { throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label)); } for (HierarchyNode n = this.Parent.FirstChild; n != null; n = n.NextSibling) { // TODO: Distinguish between real Urls and fake ones (eg. "References") if (n != this && String.Equals(n.Caption, label, StringComparison.OrdinalIgnoreCase)) { //A file or folder with the name '{0}' already exists on disk at this location. Please choose another name. //If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu. throw new InvalidOperationException(SR.GetString(SR.FileOrFolderAlreadyExists, label)); } } string fileName = Path.GetFileNameWithoutExtension(label); // Verify that the file extension is unchanged string strRelPath = Path.GetFileName(this.ItemNode.GetMetadata(ProjectFileConstants.Include)); if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site) && !String.Equals(Path.GetExtension(strRelPath), Path.GetExtension(label), StringComparison.OrdinalIgnoreCase)) { // Prompt to confirm that they really want to change the extension of the file string message = SR.GetString(SR.ConfirmExtensionChange, label); IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell; Utilities.CheckNotNull(shell, "Could not get the UI shell from the project"); if (!VsShellUtilities.PromptYesNo(message, null, OLEMSGICON.OLEMSGICON_INFO, shell)) { // The user cancelled the confirmation for changing the extension. // Return S_OK in order not to show any extra dialog box return VSConstants.S_OK; } } // Build the relative path by looking at folder names above us as one scenarios // where we get called is when a folder above us gets renamed (in which case our path is invalid) HierarchyNode parent = this.Parent; while (parent != null && (parent is FolderNode)) { strRelPath = Path.Combine(parent.Caption, strRelPath); parent = parent.Parent; } return SetEditLabel(label, strRelPath); } public override string GetMkDocument() { Debug.Assert(!string.IsNullOrEmpty(this.Url), "No url specified for this node"); Debug.Assert(Path.IsPathRooted(this.Url), "Url should not be a relative path"); return this.Url; } /// <summary> /// Delete the item corresponding to the specified path from storage. /// </summary> /// <param name="path"></param> protected internal override void DeleteFromStorage(string path) { if (File.Exists(path)) { File.SetAttributes(path, FileAttributes.Normal); // make sure it's not readonly. File.Delete(path); } } /// <summary> /// Rename the underlying document based on the change the user just made to the edit label. /// </summary> protected internal override int SetEditLabel(string label, string relativePath) { int returnValue = VSConstants.S_OK; uint oldId = this.ID; string strSavePath = Path.GetDirectoryName(relativePath); strSavePath = CommonUtils.GetAbsoluteDirectoryPath(this.ProjectMgr.ProjectHome, strSavePath); string newName = Path.Combine(strSavePath, label); if (String.Equals(newName, this.Url, StringComparison.Ordinal)) { // This is really a no-op (including changing case), so there is nothing to do return VSConstants.S_FALSE; } else if (String.Equals(newName, this.Url, StringComparison.OrdinalIgnoreCase)) { // This is a change of file casing only. } else { // If the renamed file already exists then quit (unless it is the result of the parent having done the move). if (IsFileOnDisk(newName) && (IsFileOnDisk(this.Url) || !String.Equals(Path.GetFileName(newName), Path.GetFileName(this.Url), StringComparison.OrdinalIgnoreCase))) { throw new InvalidOperationException(SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, label)); } else if (newName.Length > NativeMethods.MAX_PATH) { throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label)); } } string oldName = this.Url; // must update the caption prior to calling RenameDocument, since it may // cause queries of that property (such as from open editors). string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include); try { if (!RenameDocument(oldName, newName)) { this.ItemNode.Rename(oldrelPath); } if (this is DependentFileNode) { ProjectMgr.OnInvalidateItems(this.Parent); } } catch (Exception e) { // Just re-throw the exception so we don't get duplicate message boxes. Trace.WriteLine("Exception : " + e.Message); this.RecoverFromRenameFailure(newName, oldrelPath); returnValue = Marshal.GetHRForException(e); throw; } // Return S_FALSE if the hierarchy item id has changed. This forces VS to flush the stale // hierarchy item id. if (returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED) { return (oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE; } return returnValue; } /// <summary> /// Returns a specific Document manager to handle files /// </summary> /// <returns>Document manager object</returns> protected internal override DocumentManager GetDocumentManager() { return new FileDocumentManager(this); } public override int QueryService(ref Guid guidService, out object result) { if (guidService == typeof(EnvDTE.Project).GUID) { result = ProjectMgr.GetAutomationObject(); return VSConstants.S_OK; } else if (guidService == typeof(EnvDTE.ProjectItem).GUID) { result = GetAutomationObject(); return VSConstants.S_OK; } return base.QueryService(ref guidService, out result); } /// <summary> /// Called by the drag&drop implementation to ask the node /// which is being dragged/droped over which nodes should /// process the operation. /// This allows for dragging to a node that cannot contain /// items to let its parent accept the drop, while a reference /// node delegate to the project and a folder/project node to itself. /// </summary> /// <returns></returns> protected internal override HierarchyNode GetDragTargetHandlerNode() { Debug.Assert(this.ProjectMgr != null, " The project manager is null for the filenode"); HierarchyNode handlerNode = this; while (handlerNode != null && !(handlerNode is ProjectNode || handlerNode is FolderNode)) handlerNode = handlerNode.Parent; if (handlerNode == null) handlerNode = this.ProjectMgr; return handlerNode; } internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } // Exec on special filenode commands if (cmdGroup == VsMenus.guidStandardCommandSet97) { IVsWindowFrame windowFrame = null; switch ((VsCommands)cmd) { case VsCommands.ViewCode: return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Code, out windowFrame, WindowFrameShowAction.Show); case VsCommands.ViewForm: return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Designer, out windowFrame, WindowFrameShowAction.Show); case VsCommands.Open: return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, WindowFrameShowAction.Show); case VsCommands.OpenWith: return ((FileDocumentManager)this.GetDocumentManager()).Open(false, true, VSConstants.LOGVIEWID_UserChooseView, out windowFrame, WindowFrameShowAction.Show); } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); } internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if (cmdGroup == VsMenus.guidStandardCommandSet97) { switch ((VsCommands)cmd) { case VsCommands.Copy: case VsCommands.Paste: case VsCommands.Cut: case VsCommands.Rename: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; case VsCommands.ViewCode: //case VsCommands.Delete: goto case VsCommands.OpenWith; case VsCommands.Open: case VsCommands.OpenWith: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } else if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } protected override void DoDefaultAction() { FileDocumentManager manager = this.GetDocumentManager() as FileDocumentManager; Utilities.CheckNotNull(manager, "Could not get the FileDocumentManager"); manager.Open(false, false, WindowFrameShowAction.Show); } /// <summary> /// Performs a SaveAs operation of an open document. Called from SaveItem after the running document table has been updated with the new doc data. /// </summary> /// <param name="docData">A pointer to the document in the rdt</param> /// <param name="newFilePath">The new file path to the document</param> /// <returns></returns> internal override int AfterSaveItemAs(IntPtr docData, string newFilePath) { Utilities.ArgumentNotNullOrEmpty("newFilePath", newFilePath); int returnCode = VSConstants.S_OK; newFilePath = newFilePath.Trim(); //Identify if Path or FileName are the same for old and new file string newDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(newFilePath)); string oldDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(this.GetMkDocument())); bool isSamePath = CommonUtils.IsSameDirectory(newDirectoryName, oldDirectoryName); bool isSameFile = CommonUtils.IsSamePath(newFilePath, this.Url); //Get target container HierarchyNode targetContainer = null; bool isLink = false; if (isSamePath) { targetContainer = this.Parent; } else if (!CommonUtils.IsSubpathOf(this.ProjectMgr.ProjectHome, newDirectoryName)) { targetContainer = this.Parent; isLink = true; } else if (CommonUtils.IsSameDirectory(this.ProjectMgr.ProjectHome, newDirectoryName)) { //the projectnode is the target container targetContainer = this.ProjectMgr; } else { //search for the target container among existing child nodes targetContainer = this.ProjectMgr.FindNodeByFullPath(newDirectoryName); if (targetContainer != null && (targetContainer is FileNode)) { // We already have a file node with this name in the hierarchy. throw new InvalidOperationException(SR.GetString(SR.FileAlreadyExistsAndCannotBeRenamed, Path.GetFileName(newFilePath))); } } if (targetContainer == null) { // Add a chain of subdirectories to the project. string relativeUri = CommonUtils.GetRelativeDirectoryPath(this.ProjectMgr.ProjectHome, newDirectoryName); targetContainer = this.ProjectMgr.CreateFolderNodes(relativeUri); } Utilities.CheckNotNull(targetContainer, "Could not find a target container"); //Suspend file changes while we rename the document string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include); string oldName = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, oldrelPath); SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName); sfc.Suspend(); try { // Rename the node. DocumentManager.UpdateCaption(this.ProjectMgr.Site, Path.GetFileName(newFilePath), docData); // Check if the file name was actually changed. // In same cases (e.g. if the item is a file and the user has changed its encoding) this function // is called even if there is no real rename. if (!isSameFile || (this.Parent.ID != targetContainer.ID)) { // The path of the file is changed or its parent is changed; in both cases we have // to rename the item. if (isLink != IsLinkFile) { if (isLink) { var newPath = CommonUtils.GetRelativeFilePath( this.ProjectMgr.ProjectHome, Path.Combine(Path.GetDirectoryName(Url), Path.GetFileName(newFilePath)) ); ItemNode.SetMetadata(ProjectFileConstants.Link, newPath); } else { ItemNode.SetMetadata(ProjectFileConstants.Link, null); } SetIsLinkFile(isLink); } RenameFileNode(oldName, newFilePath, targetContainer); ProjectMgr.OnInvalidateItems(this.Parent); } } catch (Exception e) { Trace.WriteLine("Exception : " + e.Message); this.RecoverFromRenameFailure(newFilePath, oldrelPath); throw; } finally { sfc.Resume(); } return returnCode; } /// <summary> /// Determines if this is node a valid node for painting the default file icon. /// </summary> /// <returns></returns> protected override bool CanShowDefaultIcon() { string moniker = this.GetMkDocument(); return File.Exists(moniker); } #endregion #region virtual methods public override object GetProperty(int propId) { switch ((__VSHPROPID)propId) { case __VSHPROPID.VSHPROPID_ItemDocCookie: if (this.DocCookie != 0) return (IntPtr)this.DocCookie; //cast to IntPtr as some callers expect VT_INT break; } return base.GetProperty(propId); } public virtual string FileName { get { return this.Caption; } set { this.SetEditLabel(value); } } /// <summary> /// Determine if this item is represented physical on disk and shows a messagebox in case that the file is not present and a UI is to be presented. /// </summary> /// <param name="showMessage">true if user should be presented for UI in case the file is not present</param> /// <returns>true if file is on disk</returns> internal protected virtual bool IsFileOnDisk(bool showMessage) { bool fileExist = IsFileOnDisk(this.Url); if (!fileExist && showMessage && !Utilities.IsInAutomationFunction(this.ProjectMgr.Site)) { string message = SR.GetString(SR.ItemDoesNotExistInProjectDirectory, Caption); string title = string.Empty; OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL; OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; Utilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton); } return fileExist; } /// <summary> /// Determine if the file represented by "path" exist in storage. /// Override this method if your files are not persisted on disk. /// </summary> /// <param name="path">Url representing the file</param> /// <returns>True if the file exist</returns> internal protected virtual bool IsFileOnDisk(string path) { return File.Exists(path); } /// <summary> /// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy. /// </summary> /// <param name="oldFileName">The old file name.</param> /// <param name="newFileName">The new file name</param> /// <param name="newParentId">The new parent id of the item.</param> /// <returns>The newly added FileNode.</returns> /// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks> internal FileNode RenameFileNode(string oldFileName, string newFileName, HierarchyNode newParent) { if (CommonUtils.IsSamePath(oldFileName, newFileName)) { // We do not want to rename the same file return null; } //If we are included in the project and our parent isn't then //we need to bring our parent into the project if (!this.IsNonMemberItem && newParent.IsNonMemberItem) { ErrorHandler.ThrowOnFailure(newParent.IncludeInProject(false)); } // Retrieve child nodes to add later. List<HierarchyNode> childNodes = this.GetChildNodes(); FileNode renamedNode; using (this.ProjectMgr.ExtensibilityEventsDispatcher.Suspend()) { // Remove this from its parent. ProjectMgr.OnItemDeleted(this); this.Parent.RemoveChild(this); // Update name in MSBuild this.ItemNode.Rename(CommonUtils.GetRelativeFilePath(ProjectMgr.ProjectHome, newFileName)); // Request a new file node be made. This is used to replace the old file node. This way custom // derived FileNode types will be used and correctly associated on rename. This is useful for things // like .txt -> .js where the file would now be able to be a startup project/file. renamedNode = this.ProjectMgr.CreateFileNode(this.ItemNode); renamedNode.ItemNode.RefreshProperties(); renamedNode.UpdateCaption(); newParent.AddChild(renamedNode); renamedNode.Parent = newParent; } UpdateCaption(); ProjectMgr.ReDrawNode(renamedNode, UIHierarchyElement.Caption); renamedNode.ProjectMgr.ExtensibilityEventsDispatcher.FireItemRenamed(this, oldFileName); //Update the new document in the RDT. DocumentManager.RenameDocument(renamedNode.ProjectMgr.Site, oldFileName, newFileName, renamedNode.ID); //Select the new node in the hierarchy renamedNode.ExpandItem(EXPANDFLAGS.EXPF_SelectItem); // Add children to new node and rename them appropriately. childNodes.ForEach(x => renamedNode.AddChild(x)); RenameChildNodes(renamedNode); return renamedNode; } /// <summary> /// Rename all childnodes /// </summary> /// <param name="newFileNode">The newly added Parent node.</param> protected virtual void RenameChildNodes(FileNode parentNode) { foreach (var childNode in GetChildNodes().OfType<FileNode>()) { string newfilename; if (childNode.HasParentNodeNameRelation) { string relationalName = childNode.Parent.GetRelationalName(); string extension = childNode.GetRelationNameExtension(); newfilename = relationalName + extension; newfilename = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), newfilename); } else { newfilename = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), childNode.Caption); } childNode.RenameDocument(childNode.GetMkDocument(), newfilename); //We must update the DependsUpon property since the rename operation will not do it if the childNode is not renamed //which happens if the is no name relation between the parent and the child string dependentOf = childNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon); if (!string.IsNullOrEmpty(dependentOf)) { childNode.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, childNode.Parent.ItemNode.GetMetadata(ProjectFileConstants.Include)); } } } /// <summary> /// Tries recovering from a rename failure. /// </summary> /// <param name="fileThatFailed"> The file that failed to be renamed.</param> /// <param name="originalFileName">The original filenamee</param> protected virtual void RecoverFromRenameFailure(string fileThatFailed, string originalFileName) { if (this.ItemNode != null && !String.IsNullOrEmpty(originalFileName)) { this.ItemNode.Rename(originalFileName); } } internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) { return this.ProjectMgr.CanProjectDeleteItems; } return false; } /// <summary> /// This should be overriden for node that are not saved on disk /// </summary> /// <param name="oldName">Previous name in storage</param> /// <param name="newName">New name in storage</param> internal virtual void RenameInStorage(string oldName, string newName) { // Make a few attempts over a short time period for (int retries = 4; retries > 0; --retries) { try { File.Move(oldName, newName); return; } catch (IOException) { System.Threading.Thread.Sleep(50); } } // Final attempt has no handling so exception propagates File.Move(oldName, newName); } /// <summary> /// This method should be overridden to provide the list of special files and associated flags for source control. /// </summary> /// <param name="sccFile">One of the file associated to the node.</param> /// <param name="files">The list of files to be placed under source control.</param> /// <param name="flags">The flags that are associated to the files.</param> protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) { if (this.ExcludeNodeFromScc) { return; } Utilities.ArgumentNotNull("files", files); Utilities.ArgumentNotNull("flags", flags); foreach (HierarchyNode node in this.GetChildNodes()) { files.Add(node.GetMkDocument()); } } #endregion #region Helper methods /// <summary> /// Gets called to rename the eventually running document this hierarchyitem points to /// </summary> /// returns FALSE if the doc can not be renamed internal bool RenameDocument(string oldName, string newName) { IVsRunningDocumentTable pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable; if (pRDT == null) return false; IntPtr docData = IntPtr.Zero; IVsHierarchy pIVsHierarchy; uint itemId; uint uiVsDocCookie; SuspendFileChanges sfc = null; if (File.Exists(oldName)) { sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName); sfc.Suspend(); } try { // Suspend ms build since during a rename operation no msbuild re-evaluation should be performed until we have finished. // Scenario that could fail if we do not suspend. // We have a project system relying on MPF that triggers a Compile target build (re-evaluates itself) whenever the project changes. (example: a file is added, property changed.) // 1. User renames a file in the above project sytem relying on MPF // 2. Our rename funstionality implemented in this method removes and readds the file and as a post step copies all msbuild entries from the removed file to the added file. // 3. The project system mentioned will trigger an msbuild re-evaluate with the new item, because it was listening to OnItemAdded. // The problem is that the item at the "add" time is only partly added to the project, since the msbuild part has not yet been copied over as mentioned in part 2 of the last step of the rename process. // The result is that the project re-evaluates itself wrongly. VSRENAMEFILEFLAGS renameflag = VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags; ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie)); if (pIVsHierarchy != null && !Utilities.IsSameComObject(pIVsHierarchy, this.ProjectMgr)) { // Don't rename it if it wasn't opened by us. return false; } // ask other potentially running packages if (!this.ProjectMgr.Tracker.CanRenameItem(oldName, newName, renameflag)) { return false; } if (IsFileOnDisk(oldName)) { RenameInStorage(oldName, newName); } // For some reason when ignoreFileChanges is called in Resume, we get an ArgumentException because // Somewhere a required fileWatcher is null. This issue only occurs when you copy and rename a typescript file, // Calling Resume here prevents said fileWatcher from being null. Don't know why it works, but it does. // Also fun! This is the only location it can go (between RenameInStorage and RenameFileNode) // So presumably there is some condition that is no longer met once both of these methods are called with a ts file. // https://nodejstools.codeplex.com/workitem/1510 if (sfc != null) { sfc.Resume(); sfc.Suspend(); } if (!CommonUtils.IsSamePath(oldName, newName)) { // Check out the project file if necessary. if (!this.ProjectMgr.QueryEditProjectFile(false)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } this.RenameFileNode(oldName, newName); } else { this.RenameCaseOnlyChange(oldName, newName); } DocumentManager.UpdateCaption(this.ProjectMgr.Site, Caption, docData); // changed from MPFProj: // http://mpfproj10.codeplex.com/WorkItem/View.aspx?WorkItemId=8231 this.ProjectMgr.Tracker.OnItemRenamed(oldName, newName, renameflag); } finally { if (sfc != null) { sfc.Resume(); } if (docData != IntPtr.Zero) { Marshal.Release(docData); } } return true; } internal virtual FileNode RenameFileNode(string oldFileName, string newFileName) { string newFolder = Path.GetDirectoryName(newFileName) + Path.DirectorySeparatorChar; var parentFolder = ProjectMgr.FindNodeByFullPath(newFolder); if (parentFolder == null) { Debug.Assert(newFolder == ProjectMgr.ProjectHome); parentFolder = ProjectMgr; } return this.RenameFileNode(oldFileName, newFileName, parentFolder); } /// <summary> /// Renames the file node for a case only change. /// </summary> /// <param name="newFileName">The new file name.</param> private void RenameCaseOnlyChange(string oldName, string newName) { //Update the include for this item. string relName = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, newName); Debug.Assert(String.Equals(this.ItemNode.GetMetadata(ProjectFileConstants.Include), relName, StringComparison.OrdinalIgnoreCase), "Not just changing the filename case"); this.ItemNode.Rename(relName); this.ItemNode.RefreshProperties(); UpdateCaption(); ProjectMgr.ReDrawNode(this, UIHierarchyElement.Caption); this.RenameChildNodes(this); // Refresh the property browser. IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell; Utilities.CheckNotNull(shell, "Could not get the UI shell from the project"); ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0)); //Select the new node in the hierarchy ExpandItem(EXPANDFLAGS.EXPF_SelectItem); } #endregion #region helpers /// <summary> /// Update the ChildNodes after the parent node has been renamed /// </summary> /// <param name="newFileNode">The new FileNode created as part of the rename of this node</param> private void SetNewParentOnChildNodes(FileNode newFileNode) { foreach (HierarchyNode childNode in GetChildNodes()) { childNode.Parent = newFileNode; } } private List<HierarchyNode> GetChildNodes() { List<HierarchyNode> childNodes = new List<HierarchyNode>(); HierarchyNode childNode = this.FirstChild; while (childNode != null) { childNodes.Add(childNode); childNode = childNode.NextSibling; } return childNodes; } #endregion void IDiskBasedNode.RenameForDeferredSave(string basePath, string baseNewPath) { string oldLoc = CommonUtils.GetAbsoluteFilePath(basePath, ItemNode.GetMetadata(ProjectFileConstants.Include)); string newLoc = CommonUtils.GetAbsoluteFilePath(baseNewPath, ItemNode.GetMetadata(ProjectFileConstants.Include)); ProjectMgr.UpdatePathForDeferredSave(oldLoc, newLoc); // make sure the directory is there Directory.CreateDirectory(Path.GetDirectoryName(newLoc)); if (File.Exists(oldLoc)) { File.Move(oldLoc, newLoc); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: A collection of methods for manipulating Files. ** ** April 09,2000 (some design refactorization) ** ===========================================================*/ using Win32Native = Microsoft.Win32.Win32Native; using System.Runtime.InteropServices; using System.Security; using System.Text; using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO { // Class for creating FileStream objects, and some basic file management // routines such as Delete, etc. internal static class File { private const int ERROR_INVALID_PARAMETER = 87; internal const int GENERIC_READ = unchecked((int)0x80000000); private const int GetFileExInfoStandard = 0; // Tests if a file exists. The result is true if the file // given by the specified path exists; otherwise, the result is // false. Note that if path describes a directory, // Exists will return true. public static bool Exists(String path) { return InternalExistsHelper(path); } private static bool InternalExistsHelper(String path) { try { if (path == null) return false; if (path.Length == 0) return false; path = Path.GetFullPath(path); // After normalizing, check whether path ends in directory separator. // Otherwise, FillAttributeInfo removes it and we may return a false positive. // GetFullPath should never return null Debug.Assert(path != null, "File.Exists: GetFullPath returned null"); if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1])) { return false; } return InternalExists(path); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } internal static bool InternalExists(String path) { Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(path, ref data, false, true); return (dataInitialised == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0); } public static byte[] ReadAllBytes(String path) { byte[] bytes; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None)) { // Do a blocking read int index = 0; long fileLength = fs.Length; if (fileLength > Int32.MaxValue) throw new IOException(SR.IO_FileTooLong2GB); int count = (int)fileLength; bytes = new byte[count]; while (count > 0) { int n = fs.Read(bytes, index, count); if (n == 0) __Error.EndOfFile(); index += n; count -= n; } } return bytes; } #if PLATFORM_UNIX public static String[] ReadAllLines(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath); Contract.EndContractBlock(); return InternalReadAllLines(path, Encoding.UTF8); } private static String[] InternalReadAllLines(String path, Encoding encoding) { Contract.Requires(path != null); Contract.Requires(encoding != null); Contract.Requires(path.Length != 0); String line; List<String> lines = new List<String>(); using (StreamReader sr = new StreamReader(path, encoding)) while ((line = sr.ReadLine()) != null) lines.Add(line); return lines.ToArray(); } #endif // PLATFORM_UNIX // Returns 0 on success, otherwise a Win32 error code. Note that // classes should use -1 as the uninitialized state for dataInitialized. internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound) { int dataInitialised = 0; if (tryagain) // someone has a handle to the file open, or other error { Win32Native.WIN32_FIND_DATA findData; findData = new Win32Native.WIN32_FIND_DATA(); // Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error String tempPath = path.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { bool error = false; SafeFindHandle handle = Win32Native.FindFirstFile(tempPath, findData); try { if (handle.IsInvalid) { error = true; dataInitialised = Marshal.GetLastWin32Error(); if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND || dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND || dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready { if (!returnErrorOnNotFound) { // Return default value for backward compatibility dataInitialised = 0; data.fileAttributes = -1; } } return dataInitialised; } } finally { // Close the Win32 handle try { handle.Close(); } catch { // if we're already returning an error, don't throw another one. if (!error) { Debug.Assert(false, "File::FillAttributeInfo - FindClose failed!"); __Error.WinIOError(); } } } } finally { Win32Native.SetErrorMode(oldMode); } // Copy the information to data data.PopulateFrom(findData); } else { // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. bool success = false; int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data); } finally { Win32Native.SetErrorMode(oldMode); } if (!success) { dataInitialised = Marshal.GetLastWin32Error(); if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND && dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND && dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready { // In case someone latched onto the file. Take the perf hit only for failure return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound); } else { if (!returnErrorOnNotFound) { // Return default value for backward compbatibility dataInitialised = 0; data.fileAttributes = -1; } } } } return dataInitialised; } } }
using Signum.Utilities.Reflection; using Signum.Entities.Reflection; using System.ComponentModel; using System.Collections.Concurrent; namespace Signum.Entities.DynamicQuery; public abstract class QueryToken : IEquatable<QueryToken> { public int Priority = 0; public abstract override string ToString(); public abstract string NiceName(); public abstract string? Format { get; } public abstract string? Unit { get; } public abstract Type Type { get; } public abstract string Key { get; } public virtual bool IsGroupable { get { switch (QueryUtils.TryGetFilterType(this.Type)) { case FilterType.Boolean: case FilterType.Enum: case FilterType.Guid: case FilterType.Integer: case FilterType.Lite: case FilterType.String: return true; case FilterType.Decimal: case FilterType.Embedded: case FilterType.Time: return false; case FilterType.DateTime: { if (this.Type.UnNullify() == typeof(DateOnly)) return true; PropertyRoute? route = this.GetPropertyRoute(); if (route != null && route.PropertyRouteType == PropertyRouteType.FieldOrProperty) { if (route.Type.UnNullify() == typeof(DateOnly)) return true; var pp = Validator.TryGetPropertyValidator(route); if (pp != null) { DateTimePrecisionValidatorAttribute? datetimePrecision = pp.Validators.OfType<DateTimePrecisionValidatorAttribute>().SingleOrDefaultEx(); if (datetimePrecision != null && datetimePrecision.Precision == DateTimePrecision.Days) return true; } } return false; } } return false; } } protected abstract List<QueryToken> SubTokensOverride(SubTokensOptions options); public virtual object QueryName => this.Parent!.QueryName; public Func<object, T> GetAccessor<T>(BuildExpressionContext context) { return Expression.Lambda<Func<object, T>>(this.BuildExpression(context), context.Parameter).Compile(); } public Expression BuildExpression(BuildExpressionContext context) { if (context.Replacements != null && context.Replacements.TryGetValue(this, out var result)) return result.GetExpression(); return BuildExpressionInternal(context); } protected abstract Expression BuildExpressionInternal(BuildExpressionContext context); public abstract PropertyRoute? GetPropertyRoute(); internal PropertyRoute? NormalizePropertyRoute() { if (typeof(ModelEntity).IsAssignableFrom(Type)) return PropertyRoute.Root(Type); Type? type = Lite.Extract(Type); //Because Add doesn't work with lites if (type != null) return PropertyRoute.Root(type); PropertyRoute? pr = GetPropertyRoute(); if (pr == null) return null; return pr; } public abstract Implementations? GetImplementations(); public abstract string? IsAllowed(); public abstract QueryToken Clone(); public abstract QueryToken? Parent { get; } public QueryToken() { } static ConcurrentDictionary<(QueryToken, SubTokensOptions), Dictionary<string, QueryToken>> subTokensOverrideCache = new ConcurrentDictionary<(QueryToken, SubTokensOptions), Dictionary<string, QueryToken>>(); public QueryToken? SubTokenInternal(string key, SubTokensOptions options) { var result = CachedSubTokensOverride(options).TryGetC(key) ?? OnEntityExtension(this).SingleOrDefaultEx(a => a.Key == key); if (result == null) return null; string? allowed = result.IsAllowed(); if (allowed != null) throw new UnauthorizedAccessException($"Access to token '{this.FullKey()}.{key}' in query '{QueryUtils.GetKey(this.QueryName)}' is not allowed because: {allowed}"); return result; } public List<QueryToken> SubTokensInternal(SubTokensOptions options) { return CachedSubTokensOverride(options).Values .Concat(OnEntityExtension(this)) .Where(t => t.IsAllowed() == null) .OrderByDescending(a => a.Priority) .ThenBy(a => a.ToString()) .ToList(); } Dictionary<string, QueryToken> CachedSubTokensOverride(SubTokensOptions options) { return subTokensOverrideCache.GetOrAdd((this, options), (tup) => tup.Item1.SubTokensOverride(tup.Item2).ToDictionaryEx(a => a.Key, "subtokens for " + this.Key)); } public static Func<QueryToken, Type, SubTokensOptions, List<QueryToken>> ImplementedByAllSubTokens = (quetyToken, type, options) => throw new NotImplementedException("QueryToken.ImplementedByAllSubTokens not set"); public static Func<Type, bool> IsSystemVersioned = t => false; protected List<QueryToken> SubTokensBase(Type type, SubTokensOptions options, Implementations? implementations) { var ut = type.UnNullify(); if (ut == typeof(DateTime)) return DateTimeProperties(this, DateTimePrecision.Milliseconds).AndHasValue(this); if (ut == typeof(DateOnly)) return DateOnlyProperties(this).AndHasValue(this); if (ut == typeof(TimeSpan)) return TimeSpanProperties(this, DateTimePrecision.Milliseconds).AndHasValue(this); if (ut == typeof(float) || ut == typeof(double) || ut == typeof(decimal)) return StepTokens(this, 4).AndHasValue(this); if (ut == typeof(int) || ut == typeof(long) || ut == typeof(short)) return StepTokens(this, 0).AndModuloTokens(this).AndHasValue(this); if (ut == typeof(string)) return StringTokens().AndHasValue(this); Type cleanType = type.CleanType(); if (cleanType.IsIEntity()) { if (implementations!.Value.IsByAll) return ImplementedByAllSubTokens(this, type, options); // new[] { EntityPropertyToken.IdProperty(this) }; var onlyType = implementations.Value.Types.Only(); if (onlyType != null && onlyType == cleanType) return new[] { EntityPropertyToken.IdProperty(this), new EntityToStringToken(this), IsSystemVersioned(onlyType) ? new SystemTimeToken(this, SystemTimeProperty.SystemValidFrom): null, IsSystemVersioned(onlyType) ? new SystemTimeToken(this, SystemTimeProperty.SystemValidTo): null, } .NotNull() .Concat(EntityProperties(onlyType)).ToList().AndHasValue(this); return implementations.Value.Types.Select(t => (QueryToken)new AsTypeToken(this, t)).ToList().AndHasValue(this); } if (type.IsEmbeddedEntity() || type.IsModelEntity()) { return EntityProperties(type).OrderBy(a => a.ToString()).ToList().AndHasValue(this); } if (IsCollection(type)) { return CollectionProperties(this, options).AndHasValue(this); } return new List<QueryToken>(); } public List<QueryToken> StringTokens() { return new List<QueryToken> { new NetPropertyToken(this, ReflectionTools.GetPropertyInfo((string str) => str.Length), ()=>QueryTokenMessage.Length.NiceToString()) }; } public static IEnumerable<QueryToken> OnEntityExtension(QueryToken parent) { if (EntityExtensions == null) throw new InvalidOperationException("QuertToken.EntityExtensions function not set"); return EntityExtensions(parent); } public static Func<QueryToken, IEnumerable<QueryToken>>? EntityExtensions; public static List<QueryToken> DateTimeProperties(QueryToken parent, DateTimePrecision precision) { string utc = Clock.Mode == TimeZoneMode.Utc ? "Utc - " : ""; return new List<QueryToken?> { new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateTime dt)=>dt.Year), () => utc + QueryTokenMessage.Year.NiceToString()), new NetPropertyToken(parent, ReflectionTools.GetMethodInfo((DateTime dt ) => dt.Quarter()), ()=> utc + QueryTokenMessage.Quarter.NiceToString()), new DatePartStartToken(parent, QueryTokenMessage.QuarterStart), new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateTime dt)=>dt.Month),() => utc + QueryTokenMessage.Month.NiceToString()), new DatePartStartToken(parent, QueryTokenMessage.MonthStart), new NetPropertyToken(parent, ReflectionTools.GetMethodInfo((DateTime dt ) => dt.WeekNumber()), ()=> utc + QueryTokenMessage.WeekNumber.NiceToString()), new DatePartStartToken(parent, QueryTokenMessage.WeekStart), new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateTime dt)=>dt.Day), () => utc + QueryTokenMessage.Day.NiceToString()), new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateTime dt)=>dt.DayOfYear), () => utc + QueryTokenMessage.DayOfYear.NiceToString()), new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateTime dt)=>dt.DayOfWeek), () => utc + QueryTokenMessage.DayOfWeek.NiceToString()), new DateToken(parent), precision < DateTimePrecision.Hours ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateTime dt)=>dt.TimeOfDay), () => utc + QueryTokenMessage.TimeOfDay.NiceToString()), precision < DateTimePrecision.Hours ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateTime dt)=>dt.Hour), () => utc + QueryTokenMessage.Hour.NiceToString()), precision < DateTimePrecision.Hours ? null: new DatePartStartToken(parent, QueryTokenMessage.HourStart), precision < DateTimePrecision.Minutes ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateTime dt)=>dt.Minute), () => utc + QueryTokenMessage.Minute.NiceToString()), precision < DateTimePrecision.Minutes ? null: new DatePartStartToken(parent, QueryTokenMessage.MinuteStart), precision < DateTimePrecision.Seconds ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateTime dt)=>dt.Second), () => utc + QueryTokenMessage.Second.NiceToString()), precision < DateTimePrecision.Seconds ? null: new DatePartStartToken(parent, QueryTokenMessage.SecondStart), precision < DateTimePrecision.Milliseconds? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateTime dt)=>dt.Millisecond), () => utc + QueryTokenMessage.Millisecond.NiceToString()), }.NotNull().ToList(); } public static List<QueryToken> TimeSpanProperties(QueryToken parent, DateTimePrecision precision) { return new List<QueryToken?> { precision < DateTimePrecision.Hours ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeSpan dt)=>dt.Hours), () => QueryTokenMessage.Hour.NiceToString()), precision < DateTimePrecision.Hours ? null: new DatePartStartToken(parent, QueryTokenMessage.HourStart), precision < DateTimePrecision.Minutes ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeSpan dt)=>dt.Minutes), () => QueryTokenMessage.Minute.NiceToString()), precision < DateTimePrecision.Minutes ? null: new DatePartStartToken(parent, QueryTokenMessage.MinuteStart), precision < DateTimePrecision.Seconds ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeSpan dt)=>dt.Seconds), () => QueryTokenMessage.Second.NiceToString()), precision < DateTimePrecision.Seconds ? null: new DatePartStartToken(parent, QueryTokenMessage.SecondStart), precision < DateTimePrecision.Milliseconds ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeSpan dt)=>dt.Milliseconds), () => QueryTokenMessage.Millisecond.NiceToString()), new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeSpan dt)=>dt.TotalDays), () => QueryTokenMessage.TotalDays.NiceToString()), precision < DateTimePrecision.Hours ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeSpan dt)=>dt.TotalHours), () => QueryTokenMessage.TotalHours.NiceToString()), precision < DateTimePrecision.Minutes ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeSpan dt)=>dt.TotalMinutes), () => QueryTokenMessage.TotalMinutes.NiceToString()), precision < DateTimePrecision.Seconds ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeSpan dt)=>dt.TotalSeconds), () => QueryTokenMessage.TotalSeconds.NiceToString()), precision < DateTimePrecision.Milliseconds ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeSpan dt)=>dt.TotalMilliseconds), () => QueryTokenMessage.TotalMilliseconds.NiceToString()), }.NotNull().ToList(); } public static List<QueryToken> TimeOnlyProperties(QueryToken parent, DateTimePrecision precision) { string utc = Clock.Mode == TimeZoneMode.Utc ? "Utc - " : ""; return new List<QueryToken?> { precision < DateTimePrecision.Hours ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeOnly dt)=>dt.Hour), () => QueryTokenMessage.Hour.NiceToString()), new DatePartStartToken(parent, QueryTokenMessage.HourStart), precision < DateTimePrecision.Minutes ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeOnly dt)=>dt.Minute), () => QueryTokenMessage.Minute.NiceToString()), new DatePartStartToken(parent, QueryTokenMessage.MinuteStart), precision < DateTimePrecision.Seconds ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeOnly dt)=>dt.Second), () => QueryTokenMessage.Second.NiceToString()), new DatePartStartToken(parent, QueryTokenMessage.SecondStart), precision < DateTimePrecision.Milliseconds ? null: new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((TimeOnly dt)=>dt.Millisecond), () => QueryTokenMessage.Millisecond.NiceToString()), }.NotNull().ToList(); } public static List<QueryToken> DateOnlyProperties(QueryToken parent) { return new List<QueryToken?> { new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateOnly dt)=>dt.Year), () => QueryTokenMessage.Year.NiceToString()), new NetPropertyToken(parent, ReflectionTools.GetMethodInfo((DateOnly dt ) => dt.Quarter()), ()=> QueryTokenMessage.Quarter.NiceToString()), new DatePartStartToken(parent, QueryTokenMessage.QuarterStart), new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateOnly dt)=>dt.Month),() => QueryTokenMessage.Month.NiceToString()), new DatePartStartToken(parent, QueryTokenMessage.MonthStart), new NetPropertyToken(parent, ReflectionTools.GetMethodInfo((DateOnly dt ) => dt.WeekNumber()), ()=> QueryTokenMessage.WeekNumber.NiceToString()), new DatePartStartToken(parent, QueryTokenMessage.WeekStart), new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateOnly dt)=>dt.Day), () => QueryTokenMessage.Day.NiceToString()), new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateOnly dt)=>dt.DayOfYear), () => QueryTokenMessage.DayOfYear.NiceToString()), new NetPropertyToken(parent, ReflectionTools.GetPropertyInfo((DateOnly dt)=>dt.DayOfWeek), () => QueryTokenMessage.DayOfWeek.NiceToString()), }.NotNull().ToList(); } public static List<QueryToken> StepTokens(QueryToken parent, int decimals) { return new List<QueryToken?> { decimals >= 4? new StepToken(parent, 0.0001m): null, decimals >= 3? new StepToken(parent, 0.001m) : null, decimals >= 2? new StepToken(parent, 0.01m) : null, decimals >= 1? new StepToken(parent, 0.1m) : null, new StepToken(parent, 1m), new StepToken(parent, 10m), new StepToken(parent, 100m), new StepToken(parent, 1000m), new StepToken(parent, 10000m), new StepToken(parent, 100000m), new StepToken(parent, 1000000m), }.NotNull().ToList(); } public static List<QueryToken> CollectionProperties(QueryToken parent, SubTokensOptions options) { if (parent.HasAllOrAny()) options &= ~SubTokensOptions.CanElement; List<QueryToken> tokens = new List<QueryToken>() { new CountToken(parent) }; if ((options & SubTokensOptions.CanElement) == SubTokensOptions.CanElement) tokens.AddRange(EnumExtensions.GetValues<CollectionElementType>().Select(cet => new CollectionElementToken(parent, cet))); if ((options & SubTokensOptions.CanAnyAll) == SubTokensOptions.CanAnyAll) tokens.AddRange(EnumExtensions.GetValues<CollectionAnyAllType>().Select(caat => new CollectionAnyAllToken(parent, caat))); return tokens; } public virtual bool HasAllOrAny() { return Parent != null && Parent.HasAllOrAny(); } public virtual bool HasElement() { return Parent != null && Parent.HasElement(); } IEnumerable<QueryToken> EntityProperties(Type type) { var normalizedPr = NormalizePropertyRoute(); var result = from p in Reflector.PublicInstancePropertiesInOrder(type) where Reflector.QueryableProperty(type, p) select (QueryToken)new EntityPropertyToken(this, p, (normalizedPr?.Add(p))!); var mixinProperties = from mt in MixinDeclarations.GetMixinDeclarations(type) from p in Reflector.PublicInstancePropertiesInOrder(mt) where Reflector.QueryableProperty(mt, p) select (QueryToken)new EntityPropertyToken(this, p, (normalizedPr?.Add(mt).Add(p))!); return result.Concat(mixinProperties); } public string FullKey() { if (Parent == null) return Key; return Parent.FullKey() + "." + Key; } public override bool Equals(object? obj) { return obj is QueryToken token && obj.GetType() == this.GetType() && Equals(token); } public bool Equals(QueryToken? other) { return other != null && other.QueryName.Equals(this.QueryName) && other.FullKey() == this.FullKey(); } public override int GetHashCode() { return this.FullKey().GetHashCode() ^ this.QueryName.GetHashCode(); } public virtual string TypeColor { get { if (IsCollection(Type)) return "#CE6700"; return QueryUtils.TryGetFilterType(Type) switch { FilterType.Integer or FilterType.Decimal or FilterType.String or FilterType.Guid or FilterType.Boolean => "#000000", FilterType.DateTime => "#5100A1", FilterType.Time => "#9956db", FilterType.Enum => "#800046", FilterType.Lite => "#2B91AF", FilterType.Embedded => "#156F8A", _ => "#7D7D7D", }; } } public string NiceTypeName { get { Type type = Type.CleanType(); if (IsCollection(type)) { return QueryTokenMessage.ListOf0.NiceToString().FormatWith(GetNiceTypeName(Type.ElementType()!, GetElementImplementations())); } return GetNiceTypeName(Type, GetImplementations()); } } protected internal virtual Implementations? GetElementImplementations() { var pr = GetPropertyRoute(); if (pr != null) return pr.Add("Item").TryGetImplementations(); return null; } public static bool IsCollection(Type type) { return type != typeof(string) && type != typeof(byte[]) && type.ElementType() != null; } static string GetNiceTypeName(Type type, Implementations? implementations) { switch (QueryUtils.TryGetFilterType(type)) { case FilterType.Integer: return QueryTokenMessage.Number.NiceToString(); case FilterType.Decimal: return QueryTokenMessage.DecimalNumber.NiceToString(); case FilterType.String: return QueryTokenMessage.Text.NiceToString(); case FilterType.Time: return QueryTokenMessage.TimeOfDay.NiceToString(); case FilterType.DateTime: if (type.UnNullify() == typeof(DateOnly)) return QueryTokenMessage.Date.NiceToString(); return QueryTokenMessage.DateTime.NiceToString(); case FilterType.Boolean: return QueryTokenMessage.Check.NiceToString(); case FilterType.Guid: return QueryTokenMessage.GlobalUniqueIdentifier.NiceToString(); case FilterType.Enum: return type.UnNullify().NiceName(); case FilterType.Lite: { var cleanType = type.CleanType(); var imp = implementations!.Value; if (imp.IsByAll) return QueryTokenMessage.AnyEntity.NiceToString(); return imp.Types.CommaOr(t => t.NiceName()); } case FilterType.Embedded: return QueryTokenMessage.Embedded0.NiceToString().FormatWith(type.NiceName()); default: return type.TypeName(); } } public bool ContainsKey(string key) { return this.Key == key || this.Parent != null && this.Parent.ContainsKey(key); } internal bool Dominates(QueryToken t) { if (t is CollectionAnyAllToken) return false; if (t is CollectionElementToken) return false; if (t.Parent == null) return false; return t.Parent.Equals(this) || this.Dominates(t.Parent); } } public class BuildExpressionContext { public BuildExpressionContext(Type tupleType, ParameterExpression parameter, Dictionary<QueryToken, ExpressionBox> replacements) { this.TupleType = tupleType; this.Parameter = parameter; this.Replacements = replacements; } public readonly Type TupleType; public readonly ParameterExpression Parameter; public readonly Dictionary<QueryToken, ExpressionBox> Replacements; public Expression<Func<object, Lite<Entity>>> GetEntitySelector() { return Expression.Lambda<Func<object, Lite<Entity>>>(Replacements.Single(a=>a.Key.FullKey() == "Entity").Value.GetExpression(), Parameter); } public Expression<Func<object, Entity>> GetEntityFullSelector() { return Expression.Lambda<Func<object, Entity>>(Replacements.Single(a => a.Key.FullKey() == "Entity").Value.GetExpression().ExtractEntity(false), Parameter); } } public struct ExpressionBox { public ExpressionBox(Expression rawExpression, PropertyRoute? mlistElementRoute) { this.RawExpression = rawExpression; this.MListElementRoute = mlistElementRoute; } public readonly PropertyRoute? MListElementRoute; public readonly Expression RawExpression; public Expression GetExpression() { if (RawExpression.Type.IsInstantiationOf(typeof(MListElement<,>))) return Expression.Property(RawExpression, "Element").BuildLiteNullifyUnwrapPrimaryKey(new[] { MListElementRoute! }); return RawExpression; } } public enum QueryTokenMessage { [Description("({0} as {1})")] _0As1, [Description(" and ")] And, [Description("any entity")] AnyEntity, [Description("As {0}")] As0, [Description("check")] Check, [Description("Column {0} not found")] Column0NotFound, Count, Date, [Description("date and time")] DateTime, [Description("date and time with time zone")] DateTimeOffset, Day, DayOfWeek, DayOfYear, [Description("decimal number")] DecimalNumber, [Description("embedded {0}")] Embedded0, [Description("global unique identifier")] GlobalUniqueIdentifier, Hour, [Description("list of {0}")] ListOf0, Millisecond, TotalDays, TotalHours, TotalSeconds, TotalMinutes, TotalMilliseconds, Minute, Month, [Description("Month Start")] MonthStart, [Description("Quarter")] Quarter, [Description("Quarter Start")] QuarterStart, [Description("Week Start")] WeekStart, [Description("Hour Start")] HourStart, [Description("Minute Start")] MinuteStart, [Description("Second Start")] SecondStart, TimeOfDay, [Description("More than one column named {0}")] MoreThanOneColumnNamed0, [Description("number")] Number, Second, [Description("text")] Text, Year, WeekNumber, [Description("{0} step {1}")] _0Steps1, [Description("Step {0}")] Step0, Length, [Description("{0} has value")] _0HasValue, [Description("Has value")] HasValue, [Description("Modulo {0}")] Modulo0, [Description("{0} mod {1}")] _0Mod1, Null, Not, Distinct, [Description("{0} of {1}")] _0Of1, [Description("RowOrder")] RowOrder, [Description("RowID")] RowId, }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Linq.JsonPath { internal class JPath { private readonly string _expression; public List<PathFilter> Filters { get; } private int _currentIndex; public JPath(string expression) { ValidationUtils.ArgumentNotNull(expression, nameof(expression)); _expression = expression; Filters = new List<PathFilter>(); ParseMain(); } private void ParseMain() { int currentPartStartIndex = _currentIndex; EatWhitespace(); if (_expression.Length == _currentIndex) { return; } if (_expression[_currentIndex] == '$') { if (_expression.Length == 1) { return; } // only increment position for "$." or "$[" // otherwise assume property that starts with $ char c = _expression[_currentIndex + 1]; if (c == '.' || c == '[') { _currentIndex++; currentPartStartIndex = _currentIndex; } } if (!ParsePath(Filters, currentPartStartIndex, false)) { int lastCharacterIndex = _currentIndex; EatWhitespace(); if (_currentIndex < _expression.Length) { throw new JsonException("Unexpected character while parsing path: " + _expression[lastCharacterIndex]); } } } private bool ParsePath(List<PathFilter> filters, int currentPartStartIndex, bool query) { bool scan = false; bool followingIndexer = false; bool followingDot = false; bool ended = false; while (_currentIndex < _expression.Length && !ended) { char currentChar = _expression[_currentIndex]; switch (currentChar) { case '[': case '(': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); if (member == "*") { member = null; } filters.Add(CreatePathFilter(member, scan)); scan = false; } filters.Add(ParseIndexer(currentChar, scan)); _currentIndex++; currentPartStartIndex = _currentIndex; followingIndexer = true; followingDot = false; break; case ']': case ')': ended = true; break; case ' ': if (_currentIndex < _expression.Length) { ended = true; } break; case '.': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); if (member == "*") { member = null; } filters.Add(CreatePathFilter(member, scan)); scan = false; } if (_currentIndex + 1 < _expression.Length && _expression[_currentIndex + 1] == '.') { scan = true; _currentIndex++; } _currentIndex++; currentPartStartIndex = _currentIndex; followingIndexer = false; followingDot = true; break; default: if (query && (currentChar == '=' || currentChar == '<' || currentChar == '!' || currentChar == '>' || currentChar == '|' || currentChar == '&')) { ended = true; } else { if (followingIndexer) { throw new JsonException("Unexpected character following indexer: " + currentChar); } _currentIndex++; } break; } } bool atPathEnd = (_currentIndex == _expression.Length); if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd(); if (member == "*") { member = null; } filters.Add(CreatePathFilter(member, scan)); } else { // no field name following dot in path and at end of base path/query if (followingDot && (atPathEnd || query)) { throw new JsonException("Unexpected end while parsing path."); } } return atPathEnd; } private static PathFilter CreatePathFilter(string member, bool scan) { PathFilter filter = (scan) ? (PathFilter)new ScanFilter {Name = member} : new FieldFilter {Name = member}; return filter; } private PathFilter ParseIndexer(char indexerOpenChar, bool scan) { _currentIndex++; char indexerCloseChar = (indexerOpenChar == '[') ? ']' : ')'; EnsureLength("Path ended with open indexer."); EatWhitespace(); if (_expression[_currentIndex] == '\'') { return ParseQuotedField(indexerCloseChar, scan); } else if (_expression[_currentIndex] == '?') { return ParseQuery(indexerCloseChar, scan); } else { return ParseArrayIndexer(indexerCloseChar); } } private PathFilter ParseArrayIndexer(char indexerCloseChar) { int start = _currentIndex; int? end = null; List<int> indexes = null; int colonCount = 0; int? startIndex = null; int? endIndex = null; int? step = null; while (_currentIndex < _expression.Length) { char currentCharacter = _expression[_currentIndex]; if (currentCharacter == ' ') { end = _currentIndex; EatWhitespace(); continue; } if (currentCharacter == indexerCloseChar) { int length = (end ?? _currentIndex) - start; if (indexes != null) { if (length == 0) { throw new JsonException("Array index expected."); } string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); indexes.Add(index); return new ArrayMultipleIndexFilter { Indexes = indexes }; } else if (colonCount > 0) { if (length > 0) { string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); if (colonCount == 1) { endIndex = index; } else { step = index; } } return new ArraySliceFilter { Start = startIndex, End = endIndex, Step = step }; } else { if (length == 0) { throw new JsonException("Array index expected."); } string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); return new ArrayIndexFilter { Index = index }; } } else if (currentCharacter == ',') { int length = (end ?? _currentIndex) - start; if (length == 0) { throw new JsonException("Array index expected."); } if (indexes == null) { indexes = new List<int>(); } string indexer = _expression.Substring(start, length); indexes.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture)); _currentIndex++; EatWhitespace(); start = _currentIndex; end = null; } else if (currentCharacter == '*') { _currentIndex++; EnsureLength("Path ended with open indexer."); EatWhitespace(); if (_expression[_currentIndex] != indexerCloseChar) { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); } return new ArrayIndexFilter(); } else if (currentCharacter == ':') { int length = (end ?? _currentIndex) - start; if (length > 0) { string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); if (colonCount == 0) { startIndex = index; } else if (colonCount == 1) { endIndex = index; } else { step = index; } } colonCount++; _currentIndex++; EatWhitespace(); start = _currentIndex; end = null; } else if (!char.IsDigit(currentCharacter) && currentCharacter != '-') { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); } else { if (end != null) { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); } _currentIndex++; } } throw new JsonException("Path ended with open indexer."); } private void EatWhitespace() { while (_currentIndex < _expression.Length) { if (_expression[_currentIndex] != ' ') { break; } _currentIndex++; } } private PathFilter ParseQuery(char indexerCloseChar, bool scan) { _currentIndex++; EnsureLength("Path ended with open indexer."); if (_expression[_currentIndex] != '(') { throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); } _currentIndex++; QueryExpression expression = ParseExpression(); _currentIndex++; EnsureLength("Path ended with open indexer."); EatWhitespace(); if (_expression[_currentIndex] != indexerCloseChar) { throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); } if (!scan) { return new QueryFilter { Expression = expression }; } else { return new QueryScanFilter { Expression = expression }; } } private bool TryParseExpression(out List<PathFilter> expressionPath) { if (_expression[_currentIndex] == '$') { expressionPath = new List<PathFilter>(); expressionPath.Add(RootFilter.Instance); } else if (_expression[_currentIndex] == '@') { expressionPath = new List<PathFilter>(); } else { expressionPath = null; return false; } _currentIndex++; if (ParsePath(expressionPath, _currentIndex, true)) { throw new JsonException("Path ended with open query."); } return true; } private JsonException CreateUnexpectedCharacterException() { return new JsonException("Unexpected character while parsing path query: " + _expression[_currentIndex]); } private object ParseSide() { EatWhitespace(); if (TryParseExpression(out var expressionPath)) { EatWhitespace(); EnsureLength("Path ended with open query."); return expressionPath; } if (TryParseValue(out var value)) { EatWhitespace(); EnsureLength("Path ended with open query."); return new JValue(value); } throw CreateUnexpectedCharacterException(); } private QueryExpression ParseExpression() { QueryExpression rootExpression = null; CompositeExpression parentExpression = null; while (_currentIndex < _expression.Length) { object left = ParseSide(); object right = null; QueryOperator op; if (_expression[_currentIndex] == ')' || _expression[_currentIndex] == '|' || _expression[_currentIndex] == '&') { op = QueryOperator.Exists; } else { op = ParseOperator(); right = ParseSide(); } BooleanQueryExpression booleanExpression = new BooleanQueryExpression { Left = left, Operator = op, Right = right }; if (_expression[_currentIndex] == ')') { if (parentExpression != null) { parentExpression.Expressions.Add(booleanExpression); return rootExpression; } return booleanExpression; } if (_expression[_currentIndex] == '&') { if (!Match("&&")) { throw CreateUnexpectedCharacterException(); } if (parentExpression == null || parentExpression.Operator != QueryOperator.And) { CompositeExpression andExpression = new CompositeExpression { Operator = QueryOperator.And }; parentExpression?.Expressions.Add(andExpression); parentExpression = andExpression; if (rootExpression == null) { rootExpression = parentExpression; } } parentExpression.Expressions.Add(booleanExpression); } if (_expression[_currentIndex] == '|') { if (!Match("||")) { throw CreateUnexpectedCharacterException(); } if (parentExpression == null || parentExpression.Operator != QueryOperator.Or) { CompositeExpression orExpression = new CompositeExpression { Operator = QueryOperator.Or }; parentExpression?.Expressions.Add(orExpression); parentExpression = orExpression; if (rootExpression == null) { rootExpression = parentExpression; } } parentExpression.Expressions.Add(booleanExpression); } } throw new JsonException("Path ended with open query."); } private bool TryParseValue(out object value) { char currentChar = _expression[_currentIndex]; if (currentChar == '\'') { value = ReadQuotedString(); return true; } else if (char.IsDigit(currentChar) || currentChar == '-') { StringBuilder sb = new StringBuilder(); sb.Append(currentChar); _currentIndex++; while (_currentIndex < _expression.Length) { currentChar = _expression[_currentIndex]; if (currentChar == ' ' || currentChar == ')') { string numberText = sb.ToString(); if (numberText.IndexOfAny(new[] { '.', 'E', 'e' }) != -1) { bool result = double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var d); value = d; return result; } else { bool result = long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var l); value = l; return result; } } else { sb.Append(currentChar); _currentIndex++; } } } else if (currentChar == 't') { if (Match("true")) { value = true; return true; } } else if (currentChar == 'f') { if (Match("false")) { value = false; return true; } } else if (currentChar == 'n') { if (Match("null")) { value = null; return true; } } value = null; return false; } private string ReadQuotedString() { StringBuilder sb = new StringBuilder(); _currentIndex++; while (_currentIndex < _expression.Length) { char currentChar = _expression[_currentIndex]; if (currentChar == '\\' && _currentIndex + 1 < _expression.Length) { _currentIndex++; if (_expression[_currentIndex] == '\'') { sb.Append('\''); } else if (_expression[_currentIndex] == '\\') { sb.Append('\\'); } else { throw new JsonException(@"Unknown escape character: \" + _expression[_currentIndex]); } _currentIndex++; } else if (currentChar == '\'') { _currentIndex++; { return sb.ToString(); } } else { _currentIndex++; sb.Append(currentChar); } } throw new JsonException("Path ended with an open string."); } private bool Match(string s) { int currentPosition = _currentIndex; foreach (char c in s) { if (currentPosition < _expression.Length && _expression[currentPosition] == c) { currentPosition++; } else { return false; } } _currentIndex = currentPosition; return true; } private QueryOperator ParseOperator() { if (_currentIndex + 1 >= _expression.Length) { throw new JsonException("Path ended with open query."); } if (Match("==")) { return QueryOperator.Equals; } if (Match("!=") || Match("<>")) { return QueryOperator.NotEquals; } if (Match("<=")) { return QueryOperator.LessThanOrEquals; } if (Match("<")) { return QueryOperator.LessThan; } if (Match(">=")) { return QueryOperator.GreaterThanOrEquals; } if (Match(">")) { return QueryOperator.GreaterThan; } throw new JsonException("Could not read query operator."); } private PathFilter ParseQuotedField(char indexerCloseChar, bool scan) { List<string> fields = null; while (_currentIndex < _expression.Length) { string field = ReadQuotedString(); EatWhitespace(); EnsureLength("Path ended with open indexer."); if (_expression[_currentIndex] == indexerCloseChar) { if (fields != null) { fields.Add(field); return (scan) ? (PathFilter)new ScanMultipleFilter { Names = fields } : (PathFilter)new FieldMultipleFilter { Names = fields }; } else { return CreatePathFilter(field, scan); } } else if (_expression[_currentIndex] == ',') { _currentIndex++; EatWhitespace(); if (fields == null) { fields = new List<string>(); } fields.Add(field); } else { throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); } } throw new JsonException("Path ended with open indexer."); } private void EnsureLength(string message) { if (_currentIndex >= _expression.Length) { throw new JsonException(message); } } internal IEnumerable<JToken> Evaluate(JToken root, JToken t, bool errorWhenNoMatch) { return Evaluate(Filters, root, t, errorWhenNoMatch); } internal static IEnumerable<JToken> Evaluate(List<PathFilter> filters, JToken root, JToken t, bool errorWhenNoMatch) { IEnumerable<JToken> current = new[] { t }; foreach (PathFilter filter in filters) { current = filter.ExecuteFilter(root, current, errorWhenNoMatch); } return current; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Immutable.Test { public class ImmutableListBuilderTest : ImmutableListTestBase { [Fact] public void CreateBuilder() { ImmutableList<string>.Builder builder = ImmutableList.CreateBuilder<string>(); Assert.NotNull(builder); } [Fact] public void ToBuilder() { var builder = ImmutableList<int>.Empty.ToBuilder(); builder.Add(3); builder.Add(5); builder.Add(5); Assert.Equal(3, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var list = builder.ToImmutable(); Assert.Equal(builder.Count, list.Count); builder.Add(8); Assert.Equal(4, builder.Count); Assert.Equal(3, list.Count); Assert.True(builder.Contains(8)); Assert.False(list.Contains(8)); } [Fact] public void BuilderFromList() { var list = ImmutableList<int>.Empty.Add(1); var builder = list.ToBuilder(); Assert.True(builder.Contains(1)); builder.Add(3); builder.Add(5); builder.Add(5); Assert.Equal(4, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var list2 = builder.ToImmutable(); Assert.Equal(builder.Count, list2.Count); Assert.True(list2.Contains(1)); builder.Add(8); Assert.Equal(5, builder.Count); Assert.Equal(4, list2.Count); Assert.True(builder.Contains(8)); Assert.False(list.Contains(8)); Assert.False(list2.Contains(8)); } [Fact] public void SeveralChanges() { var mutable = ImmutableList<int>.Empty.ToBuilder(); var immutable1 = mutable.ToImmutable(); Assert.Same(immutable1, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences."); mutable.Add(1); var immutable2 = mutable.ToImmutable(); Assert.NotSame(immutable1, immutable2); //, "Mutating the collection did not reset the Immutable property."); Assert.Same(immutable2, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences."); Assert.Equal(1, immutable2.Count); } [Fact] public void EnumerateBuilderWhileMutating() { var builder = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 10)).ToBuilder(); Assert.Equal(Enumerable.Range(1, 10), builder); var enumerator = builder.GetEnumerator(); Assert.True(enumerator.MoveNext()); builder.Add(11); // Verify that a new enumerator will succeed. Assert.Equal(Enumerable.Range(1, 11), builder); // Try enumerating further with the previous enumerable now that we've changed the collection. Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.Reset(); enumerator.MoveNext(); // resetting should fix the problem. // Verify that by obtaining a new enumerator, we can enumerate all the contents. Assert.Equal(Enumerable.Range(1, 11), builder); } [Fact] public void BuilderReusesUnchangedImmutableInstances() { var collection = ImmutableList<int>.Empty.Add(1); var builder = collection.ToBuilder(); Assert.Same(collection, builder.ToImmutable()); // no changes at all. builder.Add(2); var newImmutable = builder.ToImmutable(); Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance. Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance. } [Fact] public void Insert() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.Insert(0, 1); mutable.Insert(0, 0); mutable.Insert(2, 3); Assert.Equal(new[] { 0, 1, 3 }, mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.Insert(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.Insert(4, 0)); } [Fact] public void InsertRange() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.InsertRange(0, new[] { 1, 4, 5 }); Assert.Equal(new[] { 1, 4, 5 }, mutable); mutable.InsertRange(1, new[] { 2, 3 }); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, mutable); mutable.InsertRange(5, new[] { 6 }); Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable); mutable.InsertRange(5, new int[0]); Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(-1, new int[0])); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(mutable.Count + 1, new int[0])); } [Fact] public void AddRange() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.AddRange(new[] { 1, 4, 5 }); Assert.Equal(new[] { 1, 4, 5 }, mutable); mutable.AddRange(new[] { 2, 3 }); Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable); mutable.AddRange(new int[0]); Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable); Assert.Throws<ArgumentNullException>(() => mutable.AddRange(null)); } [Fact] public void Remove() { var mutable = ImmutableList<int>.Empty.ToBuilder(); Assert.False(mutable.Remove(5)); mutable.Add(1); mutable.Add(2); mutable.Add(3); Assert.True(mutable.Remove(2)); Assert.Equal(new[] { 1, 3 }, mutable); Assert.True(mutable.Remove(1)); Assert.Equal(new[] { 3 }, mutable); Assert.True(mutable.Remove(3)); Assert.Equal(new int[0], mutable); Assert.False(mutable.Remove(5)); } [Fact] public void RemoveAt() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.Add(1); mutable.Add(2); mutable.Add(3); mutable.RemoveAt(2); Assert.Equal(new[] { 1, 2 }, mutable); mutable.RemoveAt(0); Assert.Equal(new[] { 2 }, mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(1)); mutable.RemoveAt(0); Assert.Equal(new int[0], mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(1)); } [Fact] public void Reverse() { var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); mutable.Reverse(); Assert.Equal(Enumerable.Range(1, 3).Reverse(), mutable); } [Fact] public void Clear() { var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); mutable.Clear(); Assert.Equal(0, mutable.Count); // Do it again for good measure. :) mutable.Clear(); Assert.Equal(0, mutable.Count); } [Fact] public void IsReadOnly() { ICollection<int> builder = ImmutableList.Create<int>().ToBuilder(); Assert.False(builder.IsReadOnly); } [Fact] public void Indexer() { var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Equal(2, mutable[1]); mutable[1] = 5; Assert.Equal(5, mutable[1]); mutable[0] = -2; mutable[2] = -3; Assert.Equal(new[] { -2, 5, -3 }, mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable[3] = 4); Assert.Throws<ArgumentOutOfRangeException>(() => mutable[-1] = 4); Assert.Throws<ArgumentOutOfRangeException>(() => mutable[3]); Assert.Throws<ArgumentOutOfRangeException>(() => mutable[-1]); } [Fact] public void IndexOf() { IndexOfTests.IndexOfTest( seq => ImmutableList.CreateRange(seq).ToBuilder(), (b, v) => b.IndexOf(v), (b, v, i) => b.IndexOf(v, i), (b, v, i, c) => b.IndexOf(v, i, c), (b, v, i, c, eq) => b.IndexOf(v, i, c, eq)); } [Fact] public void LastIndexOf() { IndexOfTests.LastIndexOfTest( seq => ImmutableList.CreateRange(seq).ToBuilder(), (b, v) => b.LastIndexOf(v), (b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq), (b, v, i) => b.LastIndexOf(v, i), (b, v, i, c) => b.LastIndexOf(v, i, c), (b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq)); } [Fact] public void GetEnumeratorExplicit() { ICollection<int> builder = ImmutableList.Create<int>().ToBuilder(); var enumerator = builder.GetEnumerator(); Assert.NotNull(enumerator); } [Fact] public void IsSynchronized() { ICollection collection = ImmutableList.Create<int>().ToBuilder(); Assert.False(collection.IsSynchronized); } [Fact] public void IListMembers() { IList list = ImmutableList.Create<int>().ToBuilder(); Assert.False(list.IsReadOnly); Assert.False(list.IsFixedSize); Assert.Equal(0, list.Add(5)); Assert.Equal(1, list.Add(8)); Assert.True(list.Contains(5)); Assert.False(list.Contains(7)); list.Insert(1, 6); Assert.Equal(6, list[1]); list.Remove(5); list[0] = 9; Assert.Equal(new[] { 9, 8 }, list.Cast<int>().ToArray()); list.Clear(); Assert.Equal(0, list.Count); } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { return ImmutableList<T>.Empty.AddRange(contents).ToBuilder(); } protected override void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test) { var builder = list.ToBuilder(); var bcl = list.ToList(); int expected = bcl.RemoveAll(test); var actual = builder.RemoveAll(test); Assert.Equal(expected, actual); Assert.Equal<T>(bcl, builder.ToList()); } protected override void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count) { var expected = list.ToList(); expected.Reverse(index, count); var builder = list.ToBuilder(); builder.Reverse(index, count); Assert.Equal<T>(expected, builder.ToList()); } internal override IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list) { return list.ToBuilder(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list) { var builder = list.ToBuilder(); builder.Sort(); return builder.ToImmutable().ToList(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison) { var builder = list.ToBuilder(); builder.Sort(comparison); return builder.ToImmutable().ToList(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer) { var builder = list.ToBuilder(); builder.Sort(comparer); return builder.ToImmutable().ToList(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer) { var builder = list.ToBuilder(); builder.Sort(index, count, comparer); return builder.ToImmutable().ToList(); } } }
// 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> /// Bulk API Result Event Store ///<para>SObject Name: BulkApiResultEventStore</para> ///<para>Custom Object: False</para> ///</summary> public class SfBulkApiResultEventStore : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "BulkApiResultEventStore"; } } ///<summary> /// Bulk API Result Event Store 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> /// 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> /// Event Identifier /// <para>Name: EventIdentifier</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "eventIdentifier")] [Updateable(false), Createable(false)] public string EventIdentifier { get; set; } ///<summary> /// User ID /// <para>Name: UserId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "userId")] [Updateable(false), Createable(false)] public string UserId { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: User</para> ///</summary> [JsonProperty(PropertyName = "user")] [Updateable(false), Createable(false)] public SfUser User { get; set; } ///<summary> /// Username /// <para>Name: Username</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "username")] [Updateable(false), Createable(false)] public string Username { get; set; } ///<summary> /// Event Date /// <para>Name: EventDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "eventDate")] [Updateable(false), Createable(false)] public DateTimeOffset? EventDate { get; set; } ///<summary> /// Related Event Identifier /// <para>Name: RelatedEventIdentifier</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "relatedEventIdentifier")] [Updateable(false), Createable(false)] public string RelatedEventIdentifier { get; set; } ///<summary> /// Transaction Security Policy ID /// <para>Name: PolicyId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "policyId")] [Updateable(false), Createable(false)] public string PolicyId { get; set; } ///<summary> /// ReferenceTo: TransactionSecurityPolicy /// <para>RelationshipName: Policy</para> ///</summary> [JsonProperty(PropertyName = "policy")] [Updateable(false), Createable(false)] public SfTransactionSecurityPolicy Policy { get; set; } ///<summary> /// Policy Outcome /// <para>Name: PolicyOutcome</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "policyOutcome")] [Updateable(false), Createable(false)] public string PolicyOutcome { get; set; } ///<summary> /// Evaluation Time /// <para>Name: EvaluationTime</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "evaluationTime")] [Updateable(false), Createable(false)] public double? EvaluationTime { get; set; } ///<summary> /// Session Key /// <para>Name: SessionKey</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "sessionKey")] [Updateable(false), Createable(false)] public string SessionKey { get; set; } ///<summary> /// Login Key /// <para>Name: LoginKey</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "loginKey")] [Updateable(false), Createable(false)] public string LoginKey { get; set; } ///<summary> /// Session Level /// <para>Name: SessionLevel</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "sessionLevel")] [Updateable(false), Createable(false)] public string SessionLevel { get; set; } ///<summary> /// Source IP /// <para>Name: SourceIp</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "sourceIp")] [Updateable(false), Createable(false)] public string SourceIp { get; set; } ///<summary> /// Login History ID /// <para>Name: LoginHistoryId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "loginHistoryId")] [Updateable(false), Createable(false)] public string LoginHistoryId { get; set; } ///<summary> /// ReferenceTo: LoginHistory /// <para>RelationshipName: LoginHistory</para> ///</summary> [JsonProperty(PropertyName = "loginHistory")] [Updateable(false), Createable(false)] public SfLoginHistory LoginHistory { get; set; } ///<summary> /// Query /// <para>Name: Query</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "query")] [Updateable(false), Createable(false)] public string Query { get; set; } } }
// 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 Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class IdentifiersShouldHaveCorrectSuffixTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new IdentifiersShouldHaveCorrectSuffixAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new IdentifiersShouldHaveCorrectSuffixAnalyzer(); } [Fact] public void CA1710_AllScenarioDiagnostics_CSharp() { VerifyCSharp(@" using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Security; using System.Security.Policy; using System.Text; using System.Threading.Tasks; public class EventsItemsEventArgs : EventArgs { } public class EventsItemsDerived : EventsItemsEventArgs { } public class EventsItems : EventArgs { } public delegate void EventCallback(object sender, EventArgs e); public class EventHandlerTest { public event EventCallback EventOne; } [Serializable] public class DiskError : Exception { public DiskError() { } public DiskError(string message) : base(message) { } public DiskError(string message, Exception innerException) : base(message, innerException) { } protected DiskError(SerializationInfo info, StreamingContext context) : base(info, context) { } } [AttributeUsage(AttributeTargets.Class)] public sealed class Verifiable : Attribute { } public class ConditionClass : IMembershipCondition { public bool Check(Evidence evidence) { return false; } public IMembershipCondition Copy() { return (IMembershipCondition)null; } public void FromXml(SecurityElement e, PolicyLevel level) { } public SecurityElement ToXml(PolicyLevel level) { return (SecurityElement)null; } public void FromXml(SecurityElement e) { } public SecurityElement ToXml() { return (SecurityElement)null; } } [Serializable] public class MyTable<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue> { protected MyTable(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class MyStringObjectHashtable : System.Collections.Generic.Dictionary<string, object> { protected MyStringObjectHashtable(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class MyList<T> : System.Collections.ObjectModel.Collection<T> { } public class StringGrouping<T> : System.Collections.ObjectModel.Collection<T> { } public class LastInFirstOut<T> : System.Collections.Generic.Stack<T> { } public class StackOfIntegers : System.Collections.Generic.Stack<int> { } public class FirstInFirstOut<T> : System.Collections.Generic.Queue<T> { } public class QueueOfNumbers : System.Collections.Generic.Queue<int> { } public class MyDataStructure : Stack { } public class AnotherDataStructure : Queue { } public class WronglyNamedPermissionClass : CodeAccessPermission { public override IPermission Copy() { return (IPermission)null; } public override void FromXml(SecurityElement e) { } public override IPermission Intersect(IPermission target) { return (IPermission)null; } public override bool IsSubsetOf(IPermission target) { return false; } public override SecurityElement ToXml() { return (SecurityElement)null; } } public class WronglyNamedIPermissionClass : IPermission { public IPermission Copy() { return (IPermission)null; } public void FromXml(SecurityElement e) { } public IPermission Intersect(IPermission target) { return (IPermission)null; } public bool IsSubsetOf(IPermission target) { return false; } public SecurityElement ToXml() { return (SecurityElement)null; } public IPermission Union(IPermission target) { return (IPermission)null; } public void Demand() { } } public class WronglyNamedType : Stream { public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } public override void Close() { base.Close(); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { } } public class MyCollectionIsEnumerable : IEnumerable { public void CopyTo(Array destination, int index) { System.Console.WriteLine(this); System.Console.WriteLine(destination); System.Console.WriteLine(index); } public int Count { get { Console.WriteLine(this); return 0; } set { System.Console.WriteLine(this); System.Console.WriteLine(value); } } public bool IsSynchronized { get { Console.WriteLine(this); return true; } set { System.Console.WriteLine(this); System.Console.WriteLine(value); } } public object SyncRoot { get { return this; } set { System.Console.WriteLine(this); System.Console.WriteLine(value); } } public IEnumerator GetEnumerator() { return null; } } public class CollectionDoesNotEndInCollectionClass : StringCollection { } [Serializable] public class DictionaryDoesNotEndInDictionaryClass : Hashtable { protected DictionaryDoesNotEndInDictionaryClass(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class MyTest<T> : List<T> { } [Serializable] public class DataSetWithWrongSuffix : DataSet { protected DataSetWithWrongSuffix(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class DataTableWithWrongSuffix : DataTable { protected DataTableWithWrongSuffix(SerializationInfo info, StreamingContext context) : base(info, context) { } }", GetCA1710CSharpResultAt(line: 16, column: 14, symbolName: "EventsItemsDerived", replacementName: "EventArgs"), GetCA1710CSharpResultAt(line: 18, column: 14, symbolName: "EventsItems", replacementName: "EventArgs"), GetCA1710CSharpResultAt(line: 24, column: 32, symbolName: "EventCallback", replacementName: "EventHandler"), GetCA1710CSharpResultAt(line: 28, column: 14, symbolName: "DiskError", replacementName: "Exception"), GetCA1710CSharpResultAt(line: 39, column: 21, symbolName: "Verifiable", replacementName: "Attribute"), GetCA1710CSharpResultAt(line: 43, column: 14, symbolName: "ConditionClass", replacementName: "Condition"), GetCA1710CSharpResultAt(line: 54, column: 14, symbolName: "MyTable<TKey, TValue>", replacementName: "Dictionary"), GetCA1710CSharpResultAt(line: 60, column: 14, symbolName: "MyStringObjectHashtable", replacementName: "Dictionary"), GetCA1710CSharpResultAt(line: 65, column: 14, symbolName: "MyList<T>", replacementName: "Collection"), GetCA1710CSharpResultAt(line: 67, column: 14, symbolName: "StringGrouping<T>", replacementName: "Collection"), GetCA1710CSharpResultAt(line: 69, column: 14, symbolName: "LastInFirstOut<T>", replacementName: "Stack", isSpecial: true), GetCA1710CSharpResultAt(line: 71, column: 14, symbolName: "StackOfIntegers", replacementName: "Stack", isSpecial: true), GetCA1710CSharpResultAt(line: 73, column: 14, symbolName: "FirstInFirstOut<T>", replacementName: "Queue", isSpecial: true), GetCA1710CSharpResultAt(line: 75, column: 14, symbolName: "QueueOfNumbers", replacementName: "Queue", isSpecial: true), GetCA1710CSharpResultAt(line: 77, column: 14, symbolName: "MyDataStructure", replacementName: "Stack", isSpecial: true), GetCA1710CSharpResultAt(line: 79, column: 14, symbolName: "AnotherDataStructure", replacementName: "Queue", isSpecial: true), GetCA1710CSharpResultAt(line: 81, column: 14, symbolName: "WronglyNamedPermissionClass", replacementName: "Permission"), GetCA1710CSharpResultAt(line: 90, column: 14, symbolName: "WronglyNamedIPermissionClass", replacementName: "Permission"), GetCA1710CSharpResultAt(line: 101, column: 14, symbolName: "WronglyNamedType", replacementName: "Stream"), GetCA1710CSharpResultAt(line: 116, column: 14, symbolName: "MyCollectionIsEnumerable", replacementName: "Collection"), GetCA1710CSharpResultAt(line: 165, column: 14, symbolName: "CollectionDoesNotEndInCollectionClass", replacementName: "Collection"), GetCA1710CSharpResultAt(line: 168, column: 14, symbolName: "DictionaryDoesNotEndInDictionaryClass", replacementName: "Dictionary"), GetCA1710CSharpResultAt(line: 174, column: 14, symbolName: "MyTest<T>", replacementName: "Collection"), GetCA1710CSharpResultAt(line: 179, column: 14, symbolName: "DataSetWithWrongSuffix", replacementName: "DataSet"), GetCA1710CSharpResultAt(line: 186, column: 14, symbolName: "DataTableWithWrongSuffix", replacementName: "DataTable", isSpecial: true)); } [Fact] public void CA1710_NoDiagnostics_CSharp() { VerifyCSharp(@" using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Security; using System.Security.Policy; using System.Text; using System.Threading.Tasks; [Serializable] public class MyDictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue> { protected MyDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class MyStringObjectDictionary : System.Collections.Generic.Dictionary<string, object> { protected MyStringObjectDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class MyCollection<T> : System.Collections.ObjectModel.Collection<T> { } public class MyStringCollection : System.Collections.ObjectModel.Collection<string> { } public class MyStack<T> : System.Collections.Generic.Stack<T> { } public class MyIntegerStack : System.Collections.Generic.Stack<int> { } public class StackCollection<T> : System.Collections.Generic.Stack<T> { } public class IntegerStackCollection : System.Collections.Generic.Stack<int> { } public class MyQueue<T> : System.Collections.Generic.Queue<T> { } public class MyIntegerQueue : System.Collections.Generic.Queue<int> { } public class QueueCollection<T> : System.Collections.Generic.Queue<T> { } public class IntegerQueueCollection : System.Collections.Generic.Queue<int> { } public delegate void SimpleEventHandler(object sender, EventArgs e); public class EventHandlerTest { public event SimpleEventHandler EventOne; public event EventHandler<EventArgs> EventTwo; } [Serializable] public class DiskErrorException : Exception { public DiskErrorException() { } public DiskErrorException(string message) : base(message) { } public DiskErrorException(string message, Exception innerException) : base(message, innerException) { } protected DiskErrorException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [AttributeUsage(AttributeTargets.Class)] public sealed class VerifiableAttribute : Attribute { } public class MyCondition : IMembershipCondition { public bool Check(Evidence evidence) { return false; } public IMembershipCondition Copy() { return (IMembershipCondition)null; } public void FromXml(SecurityElement e, PolicyLevel level) { } public SecurityElement ToXml(PolicyLevel level) { return (SecurityElement)null; } public void FromXml(SecurityElement e) { } public SecurityElement ToXml() { return (SecurityElement)null; } } public class CorrectlyNamedPermission : CodeAccessPermission { public override IPermission Copy() { return (IPermission)null; } public override void FromXml(SecurityElement e) { } public override IPermission Intersect(IPermission target) { return (IPermission)null; } public override bool IsSubsetOf(IPermission target) { return false; } public override SecurityElement ToXml() { return (SecurityElement)null; } } public class CorrectlyNamedIPermission : IPermission { public IPermission Copy() { return (IPermission)null; } public void FromXml(SecurityElement e) { } public IPermission Intersect(IPermission target) { return (IPermission)null; } public bool IsSubsetOf(IPermission target) { return false; } public SecurityElement ToXml() { return (SecurityElement)null; } public IPermission Union(IPermission target) { return (IPermission)null; } public void Demand() { } } public class CorrectlyNamedTypeStream : Stream { public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } public override void Close() { base.Close(); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { } } public class CollectionEndsInCollection : StringCollection { } [Serializable] public class DictionaryEndsInDictionary : Hashtable { public DictionaryEndsInDictionary() { } protected DictionaryEndsInDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class MySpecialQueue : Queue { } public class QueueCollection : Queue { } [Serializable] public class MyStack : Stack { } public class StackCollection : Stack { } [Serializable] public class MyDataSet : DataSet { public MyDataSet() { } protected MyDataSet(SerializationInfo info, StreamingContext context) : base(info, context) { } public void DoWork() { Console.WriteLine(this); } } [Serializable] public class MyDataTable : DataTable { public MyDataTable() { } protected MyDataTable(SerializationInfo info, StreamingContext context) : base(info, context) { } public void DoWork() { Console.WriteLine(this); } } [Serializable] public class MyCollectionDataTable : DataTable, IEnumerable { public MyCollectionDataTable() { } protected MyCollectionDataTable(SerializationInfo info, StreamingContext context) : base(info, context) { } public void DoWork() { Console.WriteLine(this); } public IEnumerator GetEnumerator() { return null; } }"); } [Fact] public void CA1710_AllScenarioDiagnostics_VisualBasic() { this.PrintActualDiagnosticsOnFailure = true; VerifyBasic(@" Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Collections.ObjectModel Imports System.Collections.Specialized Imports System.Data Imports System.IO Imports System.Runtime.Serialization Imports System.Security Imports System.Security.Policy Public Class AnotherDataStructure Inherits Queue End Class Public Class CollectionDoesNotEndInCollectionClass Inherits StringCollection End Class Public Class ConditionClass Implements IMembershipCondition, ISecurityEncodable, ISecurityPolicyEncodable ' Methods Public Function Check(ByVal evidence As Evidence) As Boolean Implements IMembershipCondition.Check Return False End Function Public Function Copy() As IMembershipCondition Implements IMembershipCondition.Copy Return Nothing End Function Public Sub FromXml(ByVal e As SecurityElement) Implements ISecurityEncodable.FromXml End Sub Public Sub FromXml(ByVal e As SecurityElement, ByVal level As PolicyLevel) Implements ISecurityPolicyEncodable.FromXml End Sub Public Function ToXml() As SecurityElement Implements ISecurityEncodable.ToXml Return Nothing End Function Public Function ToXml(ByVal level As PolicyLevel) As SecurityElement Implements ISecurityPolicyEncodable.ToXml Return Nothing End Function Public Overrides Function ToString() As String Implements IMembershipCondition.ToString Return MyBase.ToString() End Function Public Overrides Function Equals(ByVal obj As Object) As Boolean Implements IMembershipCondition.Equals Return MyBase.Equals(obj) End Function Public Overrides Function GetHashCode() As Integer Return MyBase.GetHashCode() End Function End Class <Serializable()> Public Class DataSetWithWrongSuffix Inherits DataSet ' Methods Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub End Class <Serializable()> Public Class DataTableWithWrongSuffix Inherits DataTable ' Methods Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub End Class <Serializable()> Public Class DictionaryDoesNotEndInDictionaryClass Inherits Hashtable ' Methods Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub End Class <Serializable()> Public Class DiskError Inherits Exception ' Methods Public Sub New() End Sub Public Sub New(ByVal message As String) MyBase.New(message) End Sub Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub Public Sub New(ByVal message As String, ByVal innerException As Exception) MyBase.New(message, innerException) End Sub End Class Public Delegate Sub EventCallback(ByVal sender As Object, ByVal e As EventArgs) Public Class EventHandlerTest ' Events Public Event EventOne As EventCallback End Class Public Class EventsItems Inherits EventArgs End Class Public Class FirstInFirstOut(Of T) Inherits Queue(Of T) End Class Public Class LastInFirstOut(Of T) Inherits Stack(Of T) End Class Public Class MyCollectionIsEnumerable Implements IEnumerable Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Class Public Class MyDataStructure Inherits Stack End Class Public Class MyList(Of T) Inherits Collection(Of T) End Class <Serializable()> Public Class MyStringObjectHashtable Inherits Dictionary(Of String, Object) ' Methods Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub End Class <Serializable()> Public Class MyTable(Of TKey, TValue) Inherits Dictionary(Of TKey, TValue) ' Methods Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub End Class Public Class MyTest(Of T) Inherits List(Of T) End Class Public Class QueueOfNumbers Inherits Queue(Of Integer) End Class Public Class StackOfIntegers Inherits Stack(Of Integer) End Class Public Class StringGrouping(Of T) Inherits Collection(Of T) End Class <AttributeUsage(AttributeTargets.Class)> Public NotInheritable Class Verifiable Inherits Attribute End Class Public Class WronglyNamedIPermissionClass Implements IPermission, ISecurityEncodable ' Methods Public Function Copy() As IPermission Implements IPermission.Copy Return Nothing End Function Public Sub Demand() Implements IPermission.Demand End Sub Public Sub FromXml(ByVal e As SecurityElement) Implements ISecurityEncodable.FromXml End Sub Public Function Intersect(ByVal target As IPermission) As IPermission Implements IPermission.Intersect Return Nothing End Function Public Function IsSubsetOf(ByVal target As IPermission) As Boolean Implements IPermission.IsSubsetOf Return False End Function Public Function ToXml() As SecurityElement Implements ISecurityEncodable.ToXml Return Nothing End Function Public Function Union(ByVal target As IPermission) As IPermission Implements IPermission.Union Return Nothing End Function End Class Public Class WronglyNamedPermissionClass Inherits CodeAccessPermission ' Methods Public Overrides Function Copy() As IPermission Return Nothing End Function Public Overrides Sub FromXml(ByVal e As SecurityElement) End Sub Public Overrides Function Intersect(ByVal target As IPermission) As IPermission Return Nothing End Function Public Overrides Function IsSubsetOf(ByVal target As IPermission) As Boolean Return False End Function Public Overrides Function ToXml() As SecurityElement Return Nothing End Function End Class Public Class WronglyNamedType Inherits Stream ' Methods Public Overrides Sub Close() MyBase.Close() End Sub Public Overrides Sub Flush() End Sub Public Overrides Function Read(ByVal buffer As Byte(), ByVal offset As Integer, ByVal count As Integer) As Integer Return 0 End Function Public Overrides Function Seek(ByVal offset As Long, ByVal origin As SeekOrigin) As Long Return CType(0, Long) End Function Public Overrides Sub SetLength(ByVal value As Long) End Sub Public Overrides Sub Write(ByVal buffer As Byte(), ByVal offset As Integer, ByVal count As Integer) End Sub ' Properties Public Overrides ReadOnly Property CanRead() As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property CanSeek() As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property CanWrite() As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Length() As Long Get Return CType(0, Long) End Get End Property Public Overrides Property Position() As Long Get Return CType(0, Long) End Get Set(ByVal value As Long) End Set End Property End Class", GetCA1710BasicResultAt(line: 13, column: 14, symbolName: "AnotherDataStructure", replacementName: "Queue", isSpecial: true), GetCA1710BasicResultAt(line: 17, column: 14, symbolName: "CollectionDoesNotEndInCollectionClass", replacementName: "Collection"), GetCA1710BasicResultAt(line: 22, column: 14, symbolName: "ConditionClass", replacementName: "Condition"), GetCA1710BasicResultAt(line: 64, column: 14, symbolName: "DataSetWithWrongSuffix", replacementName: "DataSet"), GetCA1710BasicResultAt(line: 75, column: 14, symbolName: "DataTableWithWrongSuffix", replacementName: "DataTable", isSpecial: true), GetCA1710BasicResultAt(line: 86, column: 14, symbolName: "DictionaryDoesNotEndInDictionaryClass", replacementName: "Dictionary"), GetCA1710BasicResultAt(line: 97, column: 14, symbolName: "DiskError", replacementName: "Exception"), GetCA1710BasicResultAt(line: 122, column: 18, symbolName: "EventCallback", replacementName: "EventHandler"), GetCA1710BasicResultAt(line: 125, column: 14, symbolName: "EventsItems", replacementName: "EventArgs"), GetCA1710BasicResultAt(line: 130, column: 14, symbolName: "FirstInFirstOut(Of T)", replacementName: "Queue", isSpecial: true), GetCA1710BasicResultAt(line: 135, column: 14, symbolName: "LastInFirstOut(Of T)", replacementName: "Stack", isSpecial: true), GetCA1710BasicResultAt(line: 140, column: 14, symbolName: "MyCollectionIsEnumerable", replacementName: "Collection"), GetCA1710BasicResultAt(line: 148, column: 14, symbolName: "MyDataStructure", replacementName: "Stack", isSpecial: true), GetCA1710BasicResultAt(line: 153, column: 14, symbolName: "MyList(Of T)", replacementName: "Collection"), GetCA1710BasicResultAt(line: 159, column: 14, symbolName: "MyStringObjectHashtable", replacementName: "Dictionary"), GetCA1710BasicResultAt(line: 170, column: 14, symbolName: "MyTable(Of TKey, TValue)", replacementName: "Dictionary"), GetCA1710BasicResultAt(line: 180, column: 14, symbolName: "MyTest(Of T)", replacementName: "Collection"), GetCA1710BasicResultAt(line: 185, column: 14, symbolName: "QueueOfNumbers", replacementName: "Queue", isSpecial: true), GetCA1710BasicResultAt(line: 190, column: 14, symbolName: "StackOfIntegers", replacementName: "Stack", isSpecial: true), GetCA1710BasicResultAt(line: 195, column: 14, symbolName: "StringGrouping(Of T)", replacementName: "Collection"), GetCA1710BasicResultAt(line: 201, column: 29, symbolName: "Verifiable", replacementName: "Attribute"), GetCA1710BasicResultAt(line: 206, column: 14, symbolName: "WronglyNamedIPermissionClass", replacementName: "Permission"), GetCA1710BasicResultAt(line: 238, column: 14, symbolName: "WronglyNamedPermissionClass", replacementName: "Permission"), GetCA1710BasicResultAt(line: 263, column: 14, symbolName: "WronglyNamedType", replacementName: "Stream")); } [Fact] public void CA1710_NoDiagnostics_VisualBasic() { this.PrintActualDiagnosticsOnFailure = true; VerifyBasic(@" Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Collections.ObjectModel Imports System.Collections.Specialized Imports System.Data Imports System.IO Imports System.Runtime.Serialization Imports System.Security Imports System.Security.Policy Public Class CollectionEndsInCollection Inherits StringCollection End Class Public Class CorrectlyNamedIPermission Implements IPermission, ISecurityEncodable Public Function Copy() As System.Security.IPermission Implements System.Security.IPermission.Copy Return Me End Function Public Sub Demand() Implements System.Security.IPermission.Demand End Sub Public Function Intersect(ByVal target As System.Security.IPermission) As System.Security.IPermission Implements System.Security.IPermission.Intersect Return Nothing End Function Public Function IsSubsetOf(ByVal target As System.Security.IPermission) As Boolean Implements System.Security.IPermission.IsSubsetOf Return False End Function Public Function Union(ByVal target As System.Security.IPermission) As System.Security.IPermission Implements System.Security.IPermission.Union Return Me End Function Public Sub FromXml(ByVal e As System.Security.SecurityElement) Implements System.Security.ISecurityEncodable.FromXml End Sub Public Function ToXml() As System.Security.SecurityElement Implements System.Security.ISecurityEncodable.ToXml End Function End Class Public Class CorrectlyNamedPermission Inherits CodeAccessPermission Public Overrides Function Copy() As System.Security.IPermission End Function Public Overrides Sub FromXml(ByVal elem As System.Security.SecurityElement) End Sub Public Overrides Function Intersect(ByVal target As System.Security.IPermission) As System.Security.IPermission End Function Public Overrides Function IsSubsetOf(ByVal target As System.Security.IPermission) As Boolean End Function Public Overrides Function ToXml() As System.Security.SecurityElement End Function End Class Public Class CorrectlyNamedTypeStream Inherits FileStream Public Sub New() MyBase.New("""", FileMode.Open) End Sub End Class <Serializable()> Public Class DictionaryEndsInDictionary Inherits Hashtable ' Methods Public Sub New() End Sub Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub End Class <Serializable()> Public Class DiskErrorException Inherits Exception ' Methods Public Sub New() End Sub Public Sub New(ByVal message As String) MyBase.New(message) End Sub Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub Public Sub New(ByVal message As String, ByVal innerException As Exception) MyBase.New(message, innerException) End Sub End Class Public Class EventHandlerTest ' Events Public Event EventOne As SimpleEventHandler End Class Public Class EventsItemsEventArgs Inherits EventArgs End Class Public Class IntegerQueueCollection Inherits Queue(Of Integer) End Class Public Class IntegerStackCollection Inherits Stack(Of Integer) End Class Public Class MyCollection(Of T) Inherits Collection(Of T) End Class Public Class MyCondition Implements IMembershipCondition, ISecurityEncodable, ISecurityPolicyEncodable Public Sub FromXml(ByVal e As System.Security.SecurityElement) Implements System.Security.ISecurityEncodable.FromXml End Sub Public Function ToXml() As System.Security.SecurityElement Implements System.Security.ISecurityEncodable.ToXml End Function Public Sub FromXml1(ByVal e As System.Security.SecurityElement, ByVal level As System.Security.Policy.PolicyLevel) Implements System.Security.ISecurityPolicyEncodable.FromXml End Sub Public Function ToXml1(ByVal level As System.Security.Policy.PolicyLevel) As System.Security.SecurityElement Implements System.Security.ISecurityPolicyEncodable.ToXml End Function Public Function Check(ByVal evidence As System.Security.Policy.Evidence) As Boolean Implements System.Security.Policy.IMembershipCondition.Check End Function Public Function Copy() As System.Security.Policy.IMembershipCondition Implements System.Security.Policy.IMembershipCondition.Copy End Function Public Function Equals1(ByVal obj As Object) As Boolean Implements System.Security.Policy.IMembershipCondition.Equals End Function Public Function ToString1() As String Implements System.Security.Policy.IMembershipCondition.ToString End Function End Class <Serializable()> Public Class MyDataSet Inherits DataSet ' Methods Public Sub New() End Sub Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub Public Sub DoWork() Console.WriteLine(Me) End Sub End Class <Serializable()> Public Class MyDataTable Inherits DataTable ' Methods Public Sub New() End Sub Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub Public Sub DoWork() Console.WriteLine(Me) End Sub End Class <Serializable()> Public Class MyDictionary(Of TKey, TValue) Inherits Dictionary(Of TKey, TValue) ' Methods Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub End Class Public Class MyIntegerQueue Inherits Queue(Of Integer) End Class Public Class MyIntegerStack Inherits Stack(Of Integer) End Class Public Class MyQueue(Of T) Inherits Queue(Of T) End Class <Serializable()> Public Class MySpecialQueue Inherits Queue End Class Public Class MyStack(Of T) Inherits Stack(Of T) End Class <Serializable()> Public Class MyStack Inherits Stack End Class Public Class MyStringCollection Inherits Collection(Of String) End Class <Serializable()> Public Class MyStringObjectDictionary Inherits Dictionary(Of String, Object) ' Methods Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) MyBase.New(info, context) End Sub End Class Public Class QueueCollection(Of T) Inherits Queue(Of T) End Class Public Class QueueCollection Inherits Queue End Class Public Delegate Sub SimpleEventHandler(ByVal sender As Object, ByVal e As EventArgs) Public Class StackCollection(Of T) Inherits Stack(Of T) End Class Public Class StackCollection Inherits Stack End Class <AttributeUsage(AttributeTargets.Class)> Public NotInheritable Class VerifiableAttribute Inherits Attribute End Class"); } private static DiagnosticResult GetCA1710BasicResultAt(int line, int column, string symbolName, string replacementName, bool isSpecial = false) { return GetBasicResultAt( line, column, IdentifiersShouldHaveCorrectSuffixAnalyzer.RuleId, string.Format( isSpecial ? MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldHaveCorrectSuffixMessageSpecialCollection : MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldHaveCorrectSuffixMessageDefault, symbolName, replacementName)); } private static DiagnosticResult GetCA1710CSharpResultAt(int line, int column, string symbolName, string replacementName, bool isSpecial = false) { return GetCSharpResultAt( line, column, IdentifiersShouldHaveCorrectSuffixAnalyzer.RuleId, string.Format( isSpecial ? MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldHaveCorrectSuffixMessageSpecialCollection : MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldHaveCorrectSuffixMessageDefault, symbolName, replacementName)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeX509ChainHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid { internal SafeX509ChainHandle() : base (default(bool)) { } protected override void Dispose(bool disposing) { } protected override bool ReleaseHandle() { throw null; } } } namespace System.Security.Cryptography.X509Certificates { public sealed partial class CertificateRequest { public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.ECDsa key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { } public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.X509Certificates.PublicKey publicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public CertificateRequest(string subjectName, System.Security.Cryptography.ECDsa key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public CertificateRequest(string subjectName, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { } public System.Collections.ObjectModel.Collection<System.Security.Cryptography.X509Certificates.X509Extension> CertificateExtensions { get { throw null; } } public System.Security.Cryptography.HashAlgorithmName HashAlgorithm { get { throw null; } } public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Certificate2 Create(System.Security.Cryptography.X509Certificates.X500DistinguishedName issuerName, System.Security.Cryptography.X509Certificates.X509SignatureGenerator generator, System.DateTimeOffset notBefore, System.DateTimeOffset notAfter, byte[] serialNumber) { throw null; } public System.Security.Cryptography.X509Certificates.X509Certificate2 Create(System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCertificate, System.DateTimeOffset notBefore, System.DateTimeOffset notAfter, byte[] serialNumber) { throw null; } public System.Security.Cryptography.X509Certificates.X509Certificate2 CreateSelfSigned(System.DateTimeOffset notBefore, System.DateTimeOffset notAfter) { throw null; } public byte[] CreateSigningRequest() { throw null; } public byte[] CreateSigningRequest(System.Security.Cryptography.X509Certificates.X509SignatureGenerator signatureGenerator) { throw null; } } public static partial class DSACertificateExtensions { public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.DSA privateKey) { throw null; } public static System.Security.Cryptography.DSA GetDSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public static System.Security.Cryptography.DSA GetDSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } } public static partial class ECDsaCertificateExtensions { public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.ECDsa privateKey) { throw null; } public static System.Security.Cryptography.ECDsa GetECDsaPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public static System.Security.Cryptography.ECDsa GetECDsaPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } } [System.FlagsAttribute] public enum OpenFlags { IncludeArchived = 8, MaxAllowed = 2, OpenExistingOnly = 4, ReadOnly = 0, ReadWrite = 1, } public sealed partial class PublicKey { public PublicKey(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedData parameters, System.Security.Cryptography.AsnEncodedData keyValue) { } public System.Security.Cryptography.AsnEncodedData EncodedKeyValue { get { throw null; } } public System.Security.Cryptography.AsnEncodedData EncodedParameters { get { throw null; } } public System.Security.Cryptography.AsymmetricAlgorithm Key { get { throw null; } } public System.Security.Cryptography.Oid Oid { get { throw null; } } } public static partial class RSACertificateExtensions { public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.RSA privateKey) { throw null; } public static System.Security.Cryptography.RSA GetRSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public static System.Security.Cryptography.RSA GetRSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } } public enum StoreLocation { CurrentUser = 1, LocalMachine = 2, } public enum StoreName { AddressBook = 1, AuthRoot = 2, CertificateAuthority = 3, Disallowed = 4, My = 5, Root = 6, TrustedPeople = 7, TrustedPublisher = 8, } public sealed partial class SubjectAlternativeNameBuilder { public SubjectAlternativeNameBuilder() { } public void AddDnsName(string dnsName) { } public void AddEmailAddress(string emailAddress) { } public void AddIpAddress(System.Net.IPAddress ipAddress) { } public void AddUri(System.Uri uri) { } public void AddUserPrincipalName(string upn) { } public System.Security.Cryptography.X509Certificates.X509Extension Build(bool critical = false) { throw null; } } public sealed partial class X500DistinguishedName : System.Security.Cryptography.AsnEncodedData { public X500DistinguishedName(byte[] encodedDistinguishedName) { } public X500DistinguishedName(System.Security.Cryptography.AsnEncodedData encodedDistinguishedName) { } public X500DistinguishedName(System.Security.Cryptography.X509Certificates.X500DistinguishedName distinguishedName) { } public X500DistinguishedName(string distinguishedName) { } public X500DistinguishedName(string distinguishedName, System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { } public string Name { get { throw null; } } public string Decode(System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { throw null; } public override string Format(bool multiLine) { throw null; } } [System.FlagsAttribute] public enum X500DistinguishedNameFlags { DoNotUsePlusSign = 32, DoNotUseQuotes = 64, ForceUTF8Encoding = 16384, None = 0, Reversed = 1, UseCommas = 128, UseNewLines = 256, UseSemicolons = 16, UseT61Encoding = 8192, UseUTF8Encoding = 4096, } public sealed partial class X509BasicConstraintsExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509BasicConstraintsExtension() { } public X509BasicConstraintsExtension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical) { } public X509BasicConstraintsExtension(System.Security.Cryptography.AsnEncodedData encodedBasicConstraints, bool critical) { } public bool CertificateAuthority { get { throw null; } } public bool HasPathLengthConstraint { get { throw null; } } public int PathLengthConstraint { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public partial class X509Certificate : System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public X509Certificate() { } public X509Certificate(byte[] data) { } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate(byte[] rawData, string password) { } public X509Certificate(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate(System.IntPtr handle) { } public X509Certificate(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public X509Certificate(System.Security.Cryptography.X509Certificates.X509Certificate cert) { } public X509Certificate(string fileName) { } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate(string fileName, string password) { } public X509Certificate(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public System.IntPtr Handle { get { throw null; } } public string Issuer { get { throw null; } } public string Subject { get { throw null; } } public static System.Security.Cryptography.X509Certificates.X509Certificate CreateFromCertFile(string filename) { throw null; } public static System.Security.Cryptography.X509Certificates.X509Certificate CreateFromSignedFile(string filename) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public override bool Equals(object obj) { throw null; } public virtual bool Equals(System.Security.Cryptography.X509Certificates.X509Certificate other) { throw null; } public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { throw null; } [System.CLSCompliantAttribute(false)] public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, System.Security.SecureString password) { throw null; } public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { throw null; } protected static string FormatDate(System.DateTime date) { throw null; } public virtual byte[] GetCertHash() { throw null; } public virtual byte[] GetCertHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual string GetCertHashString() { throw null; } public virtual string GetCertHashString(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual string GetEffectiveDateString() { throw null; } public virtual string GetExpirationDateString() { throw null; } public virtual string GetFormat() { throw null; } public override int GetHashCode() { throw null; } [System.ObsoleteAttribute("This method has been deprecated. Please use the Issuer property instead. https://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetIssuerName() { throw null; } public virtual string GetKeyAlgorithm() { throw null; } public virtual byte[] GetKeyAlgorithmParameters() { throw null; } public virtual string GetKeyAlgorithmParametersString() { throw null; } [System.ObsoleteAttribute("This method has been deprecated. Please use the Subject property instead. https://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetName() { throw null; } public virtual byte[] GetPublicKey() { throw null; } public virtual string GetPublicKeyString() { throw null; } public virtual byte[] GetRawCertData() { throw null; } public virtual string GetRawCertDataString() { throw null; } public virtual byte[] GetSerialNumber() { throw null; } public virtual string GetSerialNumberString() { throw null; } public virtual void Import(byte[] rawData) { } [System.CLSCompliantAttribute(false)] public virtual void Import(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Import(string fileName) { } [System.CLSCompliantAttribute(false)] public virtual void Import(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Reset() { } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } public virtual string ToString(bool fVerbose) { throw null; } public virtual bool TryGetCertHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class X509Certificate2 : System.Security.Cryptography.X509Certificates.X509Certificate { public X509Certificate2() { } public X509Certificate2(byte[] rawData) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(byte[] rawData, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(byte[] rawData, string password) { } public X509Certificate2(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(System.IntPtr handle) { } protected X509Certificate2(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public X509Certificate2(System.Security.Cryptography.X509Certificates.X509Certificate certificate) { } public X509Certificate2(string fileName) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(string fileName, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(string fileName, string password) { } public X509Certificate2(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public bool Archived { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509ExtensionCollection Extensions { get { throw null; } } public string FriendlyName { get { throw null; } set { } } public bool HasPrivateKey { get { throw null; } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName IssuerName { get { throw null; } } public System.DateTime NotAfter { get { throw null; } } public System.DateTime NotBefore { get { throw null; } } public System.Security.Cryptography.AsymmetricAlgorithm PrivateKey { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } } public byte[] RawData { get { throw null; } } public string SerialNumber { get { throw null; } } public System.Security.Cryptography.Oid SignatureAlgorithm { get { throw null; } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { throw null; } } public string Thumbprint { get { throw null; } } public int Version { get { throw null; } } public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(byte[] rawData) { throw null; } public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(string fileName) { throw null; } public string GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType nameType, bool forIssuer) { throw null; } public override void Import(byte[] rawData) { } [System.CLSCompliantAttribute(false)] public override void Import(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Import(string fileName) { } [System.CLSCompliantAttribute(false)] public override void Import(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Reset() { } public override string ToString() { throw null; } public override string ToString(bool verbose) { throw null; } public bool Verify() { throw null; } } public partial class X509Certificate2Collection : System.Security.Cryptography.X509Certificates.X509CertificateCollection { public X509Certificate2Collection() { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public new System.Security.Cryptography.X509Certificates.X509Certificate2 this[int index] { get { throw null; } set { } } public int Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { throw null; } public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { throw null; } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Find(System.Security.Cryptography.X509Certificates.X509FindType findType, object findValue, bool validOnly) { throw null; } public new System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator GetEnumerator() { throw null; } public void Import(byte[] rawData) { } public void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public void Import(string fileName) { } public void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } } public sealed partial class X509Certificate2Enumerator : System.Collections.IEnumerator { internal X509Certificate2Enumerator() { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } bool System.Collections.IEnumerator.MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } public partial class X509CertificateCollection : System.Collections.CollectionBase { public X509CertificateCollection() { } public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { } public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { } public System.Security.Cryptography.X509Certificates.X509Certificate this[int index] { get { throw null; } set { } } public int Add(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; } public void AddRange(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { } public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; } public void CopyTo(System.Security.Cryptography.X509Certificates.X509Certificate[] array, int index) { } public new System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator GetEnumerator() { throw null; } public override int GetHashCode() { throw null; } public int IndexOf(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; } public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate value) { } protected override void OnValidate(object value) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate value) { } public partial class X509CertificateEnumerator : System.Collections.IEnumerator { public X509CertificateEnumerator(System.Security.Cryptography.X509Certificates.X509CertificateCollection mappings) { } public System.Security.Cryptography.X509Certificates.X509Certificate Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } bool System.Collections.IEnumerator.MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public partial class X509Chain : System.IDisposable { public X509Chain() { } public X509Chain(bool useMachineContext) { } public X509Chain(System.IntPtr chainContext) { } public System.IntPtr ChainContext { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainElementCollection ChainElements { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainPolicy ChainPolicy { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainStatus { get { throw null; } } public Microsoft.Win32.SafeHandles.SafeX509ChainHandle SafeHandle { get { throw null; } } public bool Build(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public static System.Security.Cryptography.X509Certificates.X509Chain Create() { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void Reset() { } } public partial class X509ChainElement { internal X509ChainElement() { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainElementStatus { get { throw null; } } public string Information { get { throw null; } } } public sealed partial class X509ChainElementCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal X509ChainElementCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainElement this[int index] { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(System.Security.Cryptography.X509Certificates.X509ChainElement[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class X509ChainElementEnumerator : System.Collections.IEnumerator { internal X509ChainElementEnumerator() { } public System.Security.Cryptography.X509Certificates.X509ChainElement Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } public sealed partial class X509ChainPolicy { public X509ChainPolicy() { } public System.Security.Cryptography.OidCollection ApplicationPolicy { get { throw null; } } public System.Security.Cryptography.OidCollection CertificatePolicy { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection ExtraStore { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509RevocationFlag RevocationFlag { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode RevocationMode { get { throw null; } set { } } public System.TimeSpan UrlRetrievalTimeout { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509VerificationFlags VerificationFlags { get { throw null; } set { } } public System.DateTime VerificationTime { get { throw null; } set { } } public void Reset() { } } public partial struct X509ChainStatus { private object _dummy; public System.Security.Cryptography.X509Certificates.X509ChainStatusFlags Status { get { throw null; } set { } } public string StatusInformation { get { throw null; } set { } } } [System.FlagsAttribute] public enum X509ChainStatusFlags { CtlNotSignatureValid = 262144, CtlNotTimeValid = 131072, CtlNotValidForUsage = 524288, Cyclic = 128, ExplicitDistrust = 67108864, HasExcludedNameConstraint = 32768, HasNotDefinedNameConstraint = 8192, HasNotPermittedNameConstraint = 16384, HasNotSupportedCriticalExtension = 134217728, HasNotSupportedNameConstraint = 4096, HasWeakSignature = 1048576, InvalidBasicConstraints = 1024, InvalidExtension = 256, InvalidNameConstraints = 2048, InvalidPolicyConstraints = 512, NoError = 0, NoIssuanceChainPolicy = 33554432, NotSignatureValid = 8, NotTimeNested = 2, NotTimeValid = 1, NotValidForUsage = 16, OfflineRevocation = 16777216, PartialChain = 65536, RevocationStatusUnknown = 64, Revoked = 4, UntrustedRoot = 32, } public enum X509ContentType { Authenticode = 6, Cert = 1, Pfx = 3, Pkcs12 = 3, Pkcs7 = 5, SerializedCert = 2, SerializedStore = 4, Unknown = 0, } public sealed partial class X509EnhancedKeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509EnhancedKeyUsageExtension() { } public X509EnhancedKeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedEnhancedKeyUsages, bool critical) { } public X509EnhancedKeyUsageExtension(System.Security.Cryptography.OidCollection enhancedKeyUsages, bool critical) { } public System.Security.Cryptography.OidCollection EnhancedKeyUsages { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public partial class X509Extension : System.Security.Cryptography.AsnEncodedData { protected X509Extension() { } public X509Extension(System.Security.Cryptography.AsnEncodedData encodedExtension, bool critical) { } public X509Extension(System.Security.Cryptography.Oid oid, byte[] rawData, bool critical) { } public X509Extension(string oid, byte[] rawData, bool critical) { } public bool Critical { get { throw null; } set { } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class X509ExtensionCollection : System.Collections.ICollection, System.Collections.IEnumerable { public X509ExtensionCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Extension this[int index] { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Extension this[string oid] { get { throw null; } } public object SyncRoot { get { throw null; } } public int Add(System.Security.Cryptography.X509Certificates.X509Extension extension) { throw null; } public void CopyTo(System.Security.Cryptography.X509Certificates.X509Extension[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class X509ExtensionEnumerator : System.Collections.IEnumerator { internal X509ExtensionEnumerator() { } public System.Security.Cryptography.X509Certificates.X509Extension Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } public enum X509FindType { FindByApplicationPolicy = 10, FindByCertificatePolicy = 11, FindByExtension = 12, FindByIssuerDistinguishedName = 4, FindByIssuerName = 3, FindByKeyUsage = 13, FindBySerialNumber = 5, FindBySubjectDistinguishedName = 2, FindBySubjectKeyIdentifier = 14, FindBySubjectName = 1, FindByTemplateName = 9, FindByThumbprint = 0, FindByTimeExpired = 8, FindByTimeNotYetValid = 7, FindByTimeValid = 6, } public enum X509IncludeOption { EndCertOnly = 2, ExcludeRoot = 1, None = 0, WholeChain = 3, } [System.FlagsAttribute] public enum X509KeyStorageFlags { DefaultKeySet = 0, EphemeralKeySet = 32, Exportable = 4, MachineKeySet = 2, PersistKeySet = 16, UserKeySet = 1, UserProtected = 8, } public sealed partial class X509KeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509KeyUsageExtension() { } public X509KeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedKeyUsage, bool critical) { } public X509KeyUsageExtension(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags keyUsages, bool critical) { } public System.Security.Cryptography.X509Certificates.X509KeyUsageFlags KeyUsages { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } [System.FlagsAttribute] public enum X509KeyUsageFlags { CrlSign = 2, DataEncipherment = 16, DecipherOnly = 32768, DigitalSignature = 128, EncipherOnly = 1, KeyAgreement = 8, KeyCertSign = 4, KeyEncipherment = 32, None = 0, NonRepudiation = 64, } public enum X509NameType { DnsFromAlternativeName = 4, DnsName = 3, EmailName = 1, SimpleName = 0, UpnName = 2, UrlName = 5, } public enum X509RevocationFlag { EndCertificateOnly = 0, EntireChain = 1, ExcludeRoot = 2, } public enum X509RevocationMode { NoCheck = 0, Offline = 2, Online = 1, } public abstract partial class X509SignatureGenerator { protected X509SignatureGenerator() { } public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } } protected abstract System.Security.Cryptography.X509Certificates.PublicKey BuildPublicKey(); public static System.Security.Cryptography.X509Certificates.X509SignatureGenerator CreateForECDsa(System.Security.Cryptography.ECDsa key) { throw null; } public static System.Security.Cryptography.X509Certificates.X509SignatureGenerator CreateForRSA(System.Security.Cryptography.RSA key, System.Security.Cryptography.RSASignaturePadding signaturePadding) { throw null; } public abstract byte[] GetSignatureAlgorithmIdentifier(System.Security.Cryptography.HashAlgorithmName hashAlgorithm); public abstract byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm); } public sealed partial class X509Store : System.IDisposable { public X509Store() { } public X509Store(System.IntPtr storeHandle) { } public X509Store(System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName) { } public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.OpenFlags flags) { } public X509Store(string storeName) { } public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.OpenFlags flags) { } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { throw null; } } public bool IsOpen { get { throw null; } } public System.Security.Cryptography.X509Certificates.StoreLocation Location { get { throw null; } } public string Name { get { throw null; } } public System.IntPtr StoreHandle { get { throw null; } } public void Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public void Close() { } public void Dispose() { } public void Open(System.Security.Cryptography.X509Certificates.OpenFlags flags) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } } public sealed partial class X509SubjectKeyIdentifierExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509SubjectKeyIdentifierExtension() { } public X509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.AsnEncodedData encodedSubjectKeyIdentifier, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical) { } public X509SubjectKeyIdentifierExtension(string subjectKeyIdentifier, bool critical) { } public string SubjectKeyIdentifier { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public enum X509SubjectKeyIdentifierHashAlgorithm { CapiSha1 = 2, Sha1 = 0, ShortSha1 = 1, } [System.FlagsAttribute] public enum X509VerificationFlags { AllFlags = 4095, AllowUnknownCertificateAuthority = 16, IgnoreCertificateAuthorityRevocationUnknown = 1024, IgnoreCtlNotTimeValid = 2, IgnoreCtlSignerRevocationUnknown = 512, IgnoreEndRevocationUnknown = 256, IgnoreInvalidBasicConstraints = 8, IgnoreInvalidName = 64, IgnoreInvalidPolicy = 128, IgnoreNotTimeNested = 4, IgnoreNotTimeValid = 1, IgnoreRootRevocationUnknown = 2048, IgnoreWrongUsage = 32, NoFlag = 0, } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics.CodeAnalysis; using Common.Logging; using NHibernate; using NHibernate.Engine; using NHibernate.SqlTypes; using NHibernate.UserTypes; using ToolKit.Cryptography; using ToolKit.Validation; namespace ToolKit.Data.NHibernate.UserTypes { /// <summary> /// Use symmetric encryption to store the string encrypted in the database and "translate" when /// the object is saved or retrieved from the database. /// </summary> public class SymmetricEncryptedString : DisposableObject, IUserType, IParameterizedType { private static readonly ILog _log = LogManager.GetLogger<SymmetricEncryptedString>(); private static readonly string _hash = SHA256Hash.Create().Compute(new EncryptionData(Environment.MachineName)); private static EncryptionData _encryptionKey = new EncryptionData(_hash); private static EncryptionData _initializationVector = new EncryptionData(_hash); private readonly SymmetricEncryption _encryptor = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael); /// <summary> /// Gets or sets the encryption key to use when saving or reading from database. /// </summary> public static EncryptionData EncryptionKey { get => _encryptionKey; set { _log.Info("Changing the Encryption Key for SymmetricEncryptedStrings."); _encryptionKey = value; } } /// <summary> /// Gets or sets the initialization vector to use when saving or reading from database. /// </summary> public static EncryptionData InitializationVector { get => _initializationVector; set { _log.Info("Changing the Initialization Vector for SymmetricEncryptedStrings."); _initializationVector = value; } } /// <summary> /// Gets a value indicating whether this instance is mutable. /// </summary> /// <value><c>true</c> if this instance is mutable; otherwise, <c>false</c>.</value> public bool IsMutable => false; /// <summary> /// Gets the type returned by <c>NullSafeGet</c>. /// </summary> /// <value>The type returned by <c>NullSafeGet</c>.</value> public Type ReturnedType => typeof(string); /// <summary> /// Gets the SQL types for the columns mapped by this type. In this case just a SQL Type /// will be returned: <seealso cref="DbType.String" />. /// </summary> [SuppressMessage( "Performance", "CA1819:Properties should not return arrays", Justification = "Constrained by the Interface")] public SqlType[] SqlTypes { get { var types = new SqlType[1]; types[0] = new SqlType(DbType.String); return types; } } /// <summary> /// Reconstruct an object from the cacheable representation. At the very least this method /// should perform a deep copy if the type is mutable. /// </summary> /// <param name="cached">the object to be cached.</param> /// <param name="owner">the owner of the cached object.</param> /// <returns>a reconstructed string from the cacheable representation.</returns> public object Assemble(object cached, object owner) => DeepCopy(cached); /// <summary> /// Return a deep copy of the persistent state, stopping at entities and at collections. /// </summary> /// <param name="value">generally a collection element or entity field.</param> /// <returns>a copy of the collection element or entity field.</returns> public object DeepCopy(object value) => value == null ? null : string.Copy((string)value); /// <summary> /// Transform the object into its cacheable representation. At the very least this method /// should perform a deep copy if the type is mutable. That may not be enough for some /// implementations, however; for example, associations must be cached as identifier values. /// </summary> /// <param name="value">the object to be cached.</param> /// <returns>a cacheable representation of the object.</returns> public object Disassemble(object value) => DeepCopy(value); /// <summary> /// Compare two instances of the class mapped by this type for persistent "equality" or /// equality of persistent state. /// </summary> /// <param name="x">string to compare 1.</param> /// <param name="y">string to compare 2.</param> /// <returns><c>true</c> if objects are equals; otherwise, <c>false</c>.</returns> public new bool Equals(object x, object y) { if (x == null || y == null) { return false; } return x.Equals(y); } /// <summary> /// Get a hash code for the instance, consistent with persistence "equality". /// </summary> /// <param name="x">The object to calculate the hash code.</param> /// <returns>the hash code.</returns> public int GetHashCode(object x) => x?.GetHashCode() ?? 0; /// <summary> /// Retrieve an instance of the mapped class from a ADO.Net result set. Classes that inherit /// from this class should handle possibility of null values. /// </summary> /// <param name="rs">a DbDataReader.</param> /// <param name="names">column names.</param> /// <param name="session">the NHibernate session.</param> /// <param name="owner">the containing entity.</param> /// <returns>Trimmed string or null.</returns> public object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner) { names = Check.NotNull(names, nameof(names)); var resultString = (string)NHibernateUtil.String.NullSafeGet(rs, names[0], session); if (resultString == null) { return null; } var data = new EncryptionData { Base64 = resultString }; _encryptor.Key = _encryptionKey; _encryptor.InitializationVector = _initializationVector; return _encryptor.Decrypt(data).Text; } /// <summary> /// Write an instance of the mapped class to a prepared statement. Handle possibility of /// null values. A multi-column type should be written to parameters starting from index. /// </summary> /// <param name="cmd">an object that implements the Database Command interface.</param> /// <param name="value">the object to write.</param> /// <param name="index">command parameter index.</param> /// <param name="session">the NHibernate session.</param> public void NullSafeSet(DbCommand cmd, object value, int index, ISessionImplementor session) { if (value == null) { NHibernateUtil.String.NullSafeSet(cmd, null, index, session); return; } _encryptor.Key = _encryptionKey; _encryptor.InitializationVector = _initializationVector; var data = _encryptor.Encrypt(new EncryptionData((string)value)); value = data.Base64; NHibernateUtil.String.NullSafeSet(cmd, value, index, session); } /// <summary> /// During merge, replace the existing (target) value in the entity we are merging to with a /// new (original) value from the detached entity we are merging. For immutable objects, or /// null values, it is safe to simply return the first parameter. For mutable objects, it is /// safe to return a copy of the first parameter. For objects with component values, it /// might make sense to recursively replace component values. /// </summary> /// <param name="original">the value from the detached entity being merged.</param> /// <param name="target">the value in the managed entity.</param> /// <param name="owner">the managed entity.</param> /// <returns>Returns the first parameter because it is immutable.</returns> public object Replace(object original, object target, object owner) => original; /// <inheritdoc /> /// <summary> /// Gets called by Hibernate to pass the configured type parameters to the implementation. /// </summary> /// <param name="parameters">a dictionary key/value pairs of parameters to configure.</param> public void SetParameterValues(IDictionary<string, string> parameters) { // Method intentionally left empty. } /// <summary>Disposes the resources used by the inherited class.</summary> /// <param name="disposing"> /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only /// unmanaged resources.</param> protected override void DisposeResources(bool disposing) { _encryptor?.Dispose(); } } }
using System.Diagnostics; using va_list = System.Object; namespace System.Data.SQLite { internal partial class Sqlite3 { /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#if !_OS_COMMON_H_ //#define _OS_COMMON_H_ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #if MEMORY_DEBUG //# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif #if SQLITE_DEBUG || TRACE static bool sqlite3OsTrace = false; //#define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X static void OSTRACE( string X, params va_list[] ap ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, ap ); } #else //#define OSTRACE(X) static void OSTRACE(string X, params object[] ap) { } #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #if SQLITE_PERFORMANCE_TRACE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ //#include "hwtime.h" static sqlite_u3264 g_start; static sqlite_u3264 g_elapsed; //#define TIMER_START g_start=sqlite3Hwtime() //#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start //#define TIMER_ELAPSED g_elapsed #else const int TIMER_START = 0; //#define TIMER_START const int TIMER_END = 0; //#define TIMER_END const int TIMER_ELAPSED = 0; //#define TIMER_ELAPSED ((sqlite_u3264)0) #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if SQLITE_TEST #if !TCLSH static int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ static int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ static int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ static int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ static int sqlite3_io_error_benign = 0; /* True if errors are benign */ static int sqlite3_diskfull_pending = 0; static int sqlite3_diskfull = 0; #else static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_hit = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_hit" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_hardhit = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_hardhit" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_pending = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_pending" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_persist = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_persist" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_benign = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_benign" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_diskfull_pending = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_diskfull_pending" ); static tcl.lang.Var.SQLITE3_GETSET sqlite3_diskfull = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_diskfull" ); #endif static void SimulateIOErrorBenign( int X ) { #if !TCLSH sqlite3_io_error_benign = ( X ); #else sqlite3_io_error_benign.iValue = ( X ); #endif } //#define SimulateIOError(CODE) \ // if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ // || sqlite3_io_error_pending-- == 1 ) \ // { local_ioerr(); CODE; } static bool SimulateIOError() { #if !TCLSH if ( ( sqlite3_io_error_persist != 0 && sqlite3_io_error_hit != 0 ) || sqlite3_io_error_pending-- == 1 ) #else if ( ( sqlite3_io_error_persist.iValue != 0 && sqlite3_io_error_hit.iValue != 0 ) || sqlite3_io_error_pending.iValue-- == 1 ) #endif { local_ioerr(); return true; } return false; } static void local_ioerr() { #if TRACE IOTRACE( "IOERR\n" ); #endif #if !TCLSH sqlite3_io_error_hit++; if ( sqlite3_io_error_benign == 0 ) sqlite3_io_error_hardhit++; #else sqlite3_io_error_hit.iValue++; if ( sqlite3_io_error_benign.iValue == 0 ) sqlite3_io_error_hardhit.iValue++; #endif } //#define SimulateDiskfullError(CODE) \ // if( sqlite3_diskfull_pending ){ \ // if( sqlite3_diskfull_pending == 1 ){ \ // local_ioerr(); \ // sqlite3_diskfull = 1; \ // sqlite3_io_error_hit = 1; \ // CODE; \ // }else{ \ // sqlite3_diskfull_pending--; \ // } \ // } static bool SimulateDiskfullError() { #if !TCLSH if ( sqlite3_diskfull_pending != 0 ) { if ( sqlite3_diskfull_pending == 1 ) { #else if ( sqlite3_diskfull_pending.iValue != 0 ) { if ( sqlite3_diskfull_pending.iValue == 1 ) { #endif local_ioerr(); #if !TCLSH sqlite3_diskfull = 1; sqlite3_io_error_hit = 1; #else sqlite3_diskfull.iValue = 1; sqlite3_io_error_hit.iValue = 1; #endif return true; } else { #if !TCLSH sqlite3_diskfull_pending--; #else sqlite3_diskfull_pending.iValue--; #endif } } return false; } #else static bool SimulateIOError() { return false; } //#define SimulateIOErrorBenign(X) static void SimulateIOErrorBenign(int x) { } //#define SimulateIOError(A) //#define SimulateDiskfullError(A) #endif /* ** When testing, keep a count of the number of open files. */ #if SQLITE_TEST #if !TCLSH static int sqlite3_open_file_count = 0; #else static tcl.lang.Var.SQLITE3_GETSET sqlite3_open_file_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_open_file_count" ); #endif static void OpenCounter( int X ) { #if !TCLSH sqlite3_open_file_count += ( X ); #else sqlite3_open_file_count.iValue += ( X ); #endif } #else //#define OpenCounter(X) #endif //#endif //* !_OS_COMMON_H_) */ } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Apress.Recipes.WebApi.WebHost.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System.Collections.Generic; using SixLabors.Fonts.Tables.AdvancedTypographic.GSub; using SixLabors.Fonts.Tables.AdvancedTypographic.Shapers; using SixLabors.Fonts.Unicode; namespace SixLabors.Fonts.Tables.AdvancedTypographic { /// <summary> /// The Glyph Substitution (GSUB) table provides data for substitution of glyphs for appropriate rendering of scripts, /// such as cursively-connecting forms in Arabic script, or for advanced typographic effects, such as ligatures. /// <see href="https://docs.microsoft.com/en-us/typography/opentype/spec/gsub"/> /// </summary> [TableName(TableName)] internal class GSubTable : Table { internal const string TableName = "GSUB"; public GSubTable(ScriptList scriptList, FeatureListTable featureList, LookupListTable lookupList) { this.ScriptList = scriptList; this.FeatureList = featureList; this.LookupList = lookupList; } public ScriptList ScriptList { get; } public FeatureListTable FeatureList { get; } public LookupListTable LookupList { get; } public static GSubTable? Load(FontReader fontReader) { if (!fontReader.TryGetReaderAtTablePosition(TableName, out BigEndianBinaryReader? binaryReader)) { return null; } using (binaryReader) { return Load(binaryReader); } } internal static GSubTable Load(BigEndianBinaryReader reader) { // GSUB Header, Version 1.0 // +----------+-------------------+-----------------------------------------------------------+ // | Type | Name | Description | // +==========+===================+===========================================================+ // | uint16 | majorVersion | Major version of the GSUB table, = 1 | // +----------+-------------------+-----------------------------------------------------------+ // | uint16 | minorVersion | Minor version of the GSUB table, = 0 | // +----------+-------------------+-----------------------------------------------------------+ // | Offset16 | scriptListOffset | Offset to ScriptList table, from beginning of GSUB table | // +----------+-------------------+-----------------------------------------------------------+ // | Offset16 | featureListOffset | Offset to FeatureList table, from beginning of GSUB table | // +----------+-------------------+-----------------------------------------------------------+ // | Offset16 | lookupListOffset | Offset to LookupList table, from beginning of GSUB table | // +----------+-------------------+-----------------------------------------------------------+ // GSUB Header, Version 1.1 // +----------+-------------------------+-------------------------------------------------------------------------------+ // | Type | Name | Description | // +==========+=========================+===============================================================================+ // | uint16 | majorVersion | Major version of the GSUB table, = 1 | // +----------+-------------------------+-------------------------------------------------------------------------------+ // | uint16 | minorVersion | Minor version of the GSUB table, = 1 | // +----------+-------------------------+-------------------------------------------------------------------------------+ // | Offset16 | scriptListOffset | Offset to ScriptList table, from beginning of GSUB table | // +----------+-------------------------+-------------------------------------------------------------------------------+ // | Offset16 | featureListOffset | Offset to FeatureList table, from beginning of GSUB table | // +----------+-------------------------+-------------------------------------------------------------------------------+ // | Offset16 | lookupListOffset | Offset to LookupList table, from beginning of GSUB table | // +----------+-------------------------+-------------------------------------------------------------------------------+ // | Offset32 | featureVariationsOffset | Offset to FeatureVariations table, from beginning of GSUB table (may be NULL) | // +----------+-------------------------+-------------------------------------------------------------------------------+ ushort majorVersion = reader.ReadUInt16(); ushort minorVersion = reader.ReadUInt16(); ushort scriptListOffset = reader.ReadOffset16(); ushort featureListOffset = reader.ReadOffset16(); ushort lookupListOffset = reader.ReadOffset16(); uint featureVariationsOffset = (minorVersion == 1) ? reader.ReadOffset32() : 0; // TODO: Optimization. Allow only reading the scriptList. var scriptList = ScriptList.Load(reader, scriptListOffset); var featureList = FeatureListTable.Load(reader, featureListOffset); var lookupList = LookupListTable.Load(reader, lookupListOffset); // TODO: Feature Variations. return new GSubTable(scriptList, featureList, lookupList); } public void ApplySubstitution(FontMetrics fontMetrics, GlyphSubstitutionCollection collection) { for (ushort i = 0; i < collection.Count; i++) { // Choose a shaper based on the script. // This determines which features to apply to which glyphs. ScriptClass current = CodePoint.GetScriptClass(collection.GetGlyphShapingData(i).CodePoint); BaseShaper shaper = ShaperFactory.Create(current, collection.TextOptions); ushort index = i; ushort count = 1; while (i < collection.Count - 1) { // We want to assign the same feature lookups to individual sections of the text rather // than the text as a whole to ensure that different language shapers do not interfere // with each other when the text contains multiple languages. GlyphShapingData nextData = collection.GetGlyphShapingData(i + 1); ScriptClass next = CodePoint.GetScriptClass(nextData.CodePoint); if (next is not ScriptClass.Common and not ScriptClass.Unknown and not ScriptClass.Inherited && next != current) { break; } i++; count++; } // Assign Substitution features to each glyph. shaper.AssignFeatures(collection, index, count); IEnumerable<Tag> stageFeatures = shaper.GetShapingStageFeatures(); int currentCount = collection.Count; SkippingGlyphIterator iterator = new(fontMetrics, collection, index, default); foreach (Tag stageFeature in stageFeatures) { List<(Tag Feature, ushort Index, LookupTable LookupTable)> lookups = this.GetFeatureLookups(in stageFeature, current); if (lookups.Count == 0) { continue; } // Apply features in order. foreach ((Tag Feature, ushort Index, LookupTable LookupTable) featureLookup in lookups) { Tag feature = featureLookup.Feature; iterator.Reset(index, featureLookup.LookupTable.LookupFlags); while (iterator.Index < index + count) { List<TagEntry> glyphFeatures = collection.GetGlyphShapingData(iterator.Index).Features; if (!HasFeature(glyphFeatures, in feature)) { iterator.Next(); continue; } featureLookup.LookupTable.TrySubstitution(fontMetrics, this, collection, featureLookup.Feature, iterator.Index, count - (iterator.Index - index)); iterator.Next(); // Account for substitutions changing the length of the collection. if (collection.Count != currentCount) { count = (ushort)(count - (currentCount - collection.Count)); currentCount = collection.Count; } } } } } } private List<(Tag Feature, ushort Index, LookupTable LookupTable)> GetFeatureLookups(in Tag stageFeature, ScriptClass script) { ScriptListTable scriptListTable = this.ScriptList.Default(); Tag[] tags = UnicodeScriptTagMap.Instance[script]; for (int i = 0; i < tags.Length; i++) { if (this.ScriptList.TryGetValue(tags[i].Value, out ScriptListTable? table)) { scriptListTable = table; break; } } LangSysTable? defaultLangSysTable = scriptListTable.DefaultLangSysTable; if (defaultLangSysTable != null) { return this.GetFeatureLookups(stageFeature, defaultLangSysTable); } return this.GetFeatureLookups(stageFeature, scriptListTable.LangSysTables); } private List<(Tag Feature, ushort Index, LookupTable LookupTable)> GetFeatureLookups(in Tag stageFeature, params LangSysTable[] langSysTables) { List<(Tag Feature, ushort Index, LookupTable LookupTable)> lookups = new(); for (int i = 0; i < langSysTables.Length; i++) { ushort[] featureIndices = langSysTables[i].FeatureIndices; for (int j = 0; j < featureIndices.Length; j++) { FeatureTable featureTable = this.FeatureList.FeatureTables[featureIndices[j]]; Tag feature = featureTable.FeatureTag; if (stageFeature != feature) { continue; } ushort[] lookupListIndices = featureTable.LookupListIndices; for (int k = 0; k < lookupListIndices.Length; k++) { ushort lookupIndex = lookupListIndices[k]; LookupTable lookupTable = this.LookupList.LookupTables[lookupIndex]; lookups.Add(new(feature, lookupIndex, lookupTable)); } } } lookups.Sort((x, y) => x.Index - y.Index); return lookups; } private static bool HasFeature(List<TagEntry> glyphFeatures, in Tag feature) { for (int i = 0; i < glyphFeatures.Count; i++) { TagEntry entry = glyphFeatures[i]; if (entry.Tag == feature && entry.Enabled) { return true; } } return false; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using System.Threading; using Thrift.Collections; using Thrift.Protocol; using Thrift.Transport; using Thrift.Test; namespace Test { public class TestClient { private static int numIterations = 1; private static string protocol = ""; public static void Execute(string[] args) { try { string host = "localhost"; int port = 9090; string url = null, pipe = null; int numThreads = 1; bool buffered = false, framed = false, encrypted = false; try { for (int i = 0; i < args.Length; i++) { if (args[i] == "-u") { url = args[++i]; } else if (args[i] == "-n") { numIterations = Convert.ToInt32(args[++i]); } else if (args[i] == "-pipe") // -pipe <name> { pipe = args[++i]; Console.WriteLine("Using named pipes transport"); } else if (args[i].Contains("--host=")) { host = args[i].Substring(args[i].IndexOf("=") + 1); } else if (args[i].Contains("--port=")) { port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1)); } else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered") { buffered = true; Console.WriteLine("Using buffered sockets"); } else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed") { framed = true; Console.WriteLine("Using framed transport"); } else if (args[i] == "-t") { numThreads = Convert.ToInt32(args[++i]); } else if (args[i] == "--compact" || args[i] == "--protocol=compact") { protocol = "compact"; Console.WriteLine("Using compact protocol"); } else if (args[i] == "--json" || args[i] == "--protocol=json") { protocol = "json"; Console.WriteLine("Using JSON protocol"); } else if (args[i] == "--ssl") { encrypted = true; Console.WriteLine("Using encrypted transport"); } } } catch (Exception e) { Console.WriteLine(e.StackTrace); } //issue tests on separate threads simultaneously Thread[] threads = new Thread[numThreads]; DateTime start = DateTime.Now; for (int test = 0; test < numThreads; test++) { Thread t = new Thread(new ParameterizedThreadStart(ClientThread)); threads[test] = t; if (url == null) { // endpoint transport TTransport trans = null; if (pipe != null) trans = new TNamedPipeClientTransport(pipe); else { if (encrypted) trans = new TTLSSocket(host, port, "../../../../../keys/client.pem"); else trans = new TSocket(host, port); } // layered transport if (buffered) trans = new TBufferedTransport(trans as TStreamTransport); if (framed) trans = new TFramedTransport(trans); //ensure proper open/close of transport trans.Open(); trans.Close(); t.Start(trans); } else { THttpClient http = new THttpClient(new Uri(url)); t.Start(http); } } for (int test = 0; test < numThreads; test++) { threads[test].Join(); } Console.Write("Total time: " + (DateTime.Now - start)); } catch (Exception outerEx) { Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace); } Console.WriteLine(); Console.WriteLine(); } public static void ClientThread(object obj) { TTransport transport = (TTransport)obj; for (int i = 0; i < numIterations; i++) { ClientTest(transport); } transport.Close(); } public static string BytesToHex(byte[] data) { return BitConverter.ToString(data).Replace("-", string.Empty); } public static byte[] PrepareTestData(bool randomDist) { byte[] retval = new byte[0x100]; int initLen = Math.Min(0x100,retval.Length); // linear distribution, unless random is requested if (!randomDist) { for (var i = 0; i < initLen; ++i) { retval[i] = (byte)i; } return retval; } // random distribution for (var i = 0; i < initLen; ++i) { retval[i] = (byte)0; } var rnd = new Random(); for (var i = 1; i < initLen; ++i) { while( true) { int nextPos = rnd.Next() % initLen; if (retval[nextPos] == 0) { retval[nextPos] = (byte)i; break; } } } return retval; } public static void ClientTest(TTransport transport) { TProtocol proto; if (protocol == "compact") proto = new TCompactProtocol(transport); else if (protocol == "json") proto = new TJSONProtocol(transport); else proto = new TBinaryProtocol(transport); ThriftTest.Client client = new ThriftTest.Client(proto); try { if (!transport.IsOpen) { transport.Open(); } } catch (TTransportException ttx) { Console.WriteLine("Connect failed: " + ttx.Message); return; } long start = DateTime.Now.ToFileTime(); Console.Write("testVoid()"); client.testVoid(); Console.WriteLine(" = void"); Console.Write("testString(\"Test\")"); string s = client.testString("Test"); Console.WriteLine(" = \"" + s + "\""); Console.Write("testByte(1)"); sbyte i8 = client.testByte((sbyte)1); Console.WriteLine(" = " + i8); Console.Write("testI32(-1)"); int i32 = client.testI32(-1); Console.WriteLine(" = " + i32); Console.Write("testI64(-34359738368)"); long i64 = client.testI64(-34359738368); Console.WriteLine(" = " + i64); Console.Write("testDouble(5.325098235)"); double dub = client.testDouble(5.325098235); Console.WriteLine(" = " + dub); byte[] binOut = PrepareTestData(true); Console.Write("testBinary(" + BytesToHex(binOut) + ")"); try { byte[] binIn = client.testBinary(binOut); Console.WriteLine(" = " + BytesToHex(binIn)); if (binIn.Length != binOut.Length) throw new Exception("testBinary: length mismatch"); for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs) if (binIn[ofs] != binOut[ofs]) throw new Exception("testBinary: content mismatch at offset " + ofs.ToString()); } catch (Thrift.TApplicationException e) { Console.Write("testBinary(" + BytesToHex(binOut) + "): "+e.Message); } // binary equals? only with hashcode option enabled ... if( typeof(CrazyNesting).GetMethod("Equals").DeclaringType == typeof(CrazyNesting)) { CrazyNesting one = new CrazyNesting(); CrazyNesting two = new CrazyNesting(); one.String_field = "crazy"; two.String_field = "crazy"; one.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; if (!one.Equals(two)) throw new Exception("CrazyNesting.Equals failed"); } Console.Write("testStruct({\"Zero\", 1, -3, -5})"); Xtruct o = new Xtruct(); o.String_thing = "Zero"; o.Byte_thing = (sbyte)1; o.I32_thing = -3; o.I64_thing = -5; Xtruct i = client.testStruct(o); Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}"); Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})"); Xtruct2 o2 = new Xtruct2(); o2.Byte_thing = (sbyte)1; o2.Struct_thing = o; o2.I32_thing = 5; Xtruct2 i2 = client.testNest(o2); i = i2.Struct_thing; Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}"); Dictionary<int, int> mapout = new Dictionary<int, int>(); for (int j = 0; j < 5; j++) { mapout[j] = j - 10; } Console.Write("testMap({"); bool first = true; foreach (int key in mapout.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapout[key]); } Console.Write("})"); Dictionary<int, int> mapin = client.testMap(mapout); Console.Write(" = {"); first = true; foreach (int key in mapin.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapin[key]); } Console.WriteLine("}"); List<int> listout = new List<int>(); for (int j = -2; j < 3; j++) { listout.Add(j); } Console.Write("testList({"); first = true; foreach (int j in listout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); List<int> listin = client.testList(listout); Console.Write(" = {"); first = true; foreach (int j in listin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); //set THashSet<int> setout = new THashSet<int>(); for (int j = -2; j < 3; j++) { setout.Add(j); } Console.Write("testSet({"); first = true; foreach (int j in setout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); THashSet<int> setin = client.testSet(setout); Console.Write(" = {"); first = true; foreach (int j in setin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); Console.Write("testEnum(ONE)"); Numberz ret = client.testEnum(Numberz.ONE); Console.WriteLine(" = " + ret); Console.Write("testEnum(TWO)"); ret = client.testEnum(Numberz.TWO); Console.WriteLine(" = " + ret); Console.Write("testEnum(THREE)"); ret = client.testEnum(Numberz.THREE); Console.WriteLine(" = " + ret); Console.Write("testEnum(FIVE)"); ret = client.testEnum(Numberz.FIVE); Console.WriteLine(" = " + ret); Console.Write("testEnum(EIGHT)"); ret = client.testEnum(Numberz.EIGHT); Console.WriteLine(" = " + ret); Console.Write("testTypedef(309858235082523)"); long uid = client.testTypedef(309858235082523L); Console.WriteLine(" = " + uid); Console.Write("testMapMap(1)"); Dictionary<int, Dictionary<int, int>> mm = client.testMapMap(1); Console.Write(" = {"); foreach (int key in mm.Keys) { Console.Write(key + " => {"); Dictionary<int, int> m2 = mm[key]; foreach (int k2 in m2.Keys) { Console.Write(k2 + " => " + m2[k2] + ", "); } Console.Write("}, "); } Console.WriteLine("}"); Insanity insane = new Insanity(); insane.UserMap = new Dictionary<Numberz, long>(); insane.UserMap[Numberz.FIVE] = 5000L; Xtruct truck = new Xtruct(); truck.String_thing = "Truck"; truck.Byte_thing = (sbyte)8; truck.I32_thing = 8; truck.I64_thing = 8; insane.Xtructs = new List<Xtruct>(); insane.Xtructs.Add(truck); Console.Write("testInsanity()"); Dictionary<long, Dictionary<Numberz, Insanity>> whoa = client.testInsanity(insane); Console.Write(" = {"); foreach (long key in whoa.Keys) { Dictionary<Numberz, Insanity> val = whoa[key]; Console.Write(key + " => {"); foreach (Numberz k2 in val.Keys) { Insanity v2 = val[k2]; Console.Write(k2 + " => {"); Dictionary<Numberz, long> userMap = v2.UserMap; Console.Write("{"); if (userMap != null) { foreach (Numberz k3 in userMap.Keys) { Console.Write(k3 + " => " + userMap[k3] + ", "); } } else { Console.Write("null"); } Console.Write("}, "); List<Xtruct> xtructs = v2.Xtructs; Console.Write("{"); if (xtructs != null) { foreach (Xtruct x in xtructs) { Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, "); } } else { Console.Write("null"); } Console.Write("}"); Console.Write("}, "); } Console.Write("}, "); } Console.WriteLine("}"); sbyte arg0 = 1; int arg1 = 2; long arg2 = long.MaxValue; Dictionary<short, string> multiDict = new Dictionary<short, string>(); multiDict[1] = "one"; Numberz arg4 = Numberz.FIVE; long arg5 = 5000000; Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + "," + multiDict + "," + arg4 + "," + arg5 + ")"); Xtruct multiResponse = client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5); Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing + ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n"); Console.WriteLine("Test Oneway(1)"); client.testOneway(1); Console.Write("Test Calltime()"); var startt = DateTime.UtcNow; for ( int k=0; k<1000; ++k ) client.testVoid(); Console.WriteLine(" = " + (DateTime.UtcNow - startt).TotalSeconds.ToString() + " ms a testVoid() call" ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System; using System.Diagnostics.Contracts; namespace System.Text { // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // [System.Runtime.InteropServices.ComVisible(true)] public abstract class Encoder { internal EncoderFallback m_fallback = null; internal EncoderFallbackBuffer m_fallbackBuffer = null; protected Encoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } [System.Runtime.InteropServices.ComVisible(false)] public EncoderFallback Fallback { get { return m_fallback; } set { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); // Can't change fallback if buffer is wrong if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, "value"); m_fallback = value; m_fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. [System.Runtime.InteropServices.ComVisible(false)] public EncoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { if (m_fallback != null) m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); else m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return m_fallbackBuffer; } } internal bool InternalHasFallbackBuffer { get { return m_fallbackBuffer != null; } } // Reset the Encoder // // Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset(). // // Virtual implimentation has to call GetBytes with flush and a big enough buffer to clear a 0 char string // We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big. [System.Runtime.InteropServices.ComVisible(false)] public virtual void Reset() { char[] charTemp = { }; byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)]; GetBytes(charTemp, 0, 0, byteTemp, 0, true); if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Returns the number of bytes the next call to GetBytes will // produce if presented with the given range of characters and the given // value of the flush parameter. The returned value takes into // account the state in which the encoder was left following the last call // to GetBytes. The state of the encoder is not affected by a call // to this method. // public abstract int GetByteCount(char[] chars, int index, int count, bool flush); // We expect this to be the workhorse for NLS encodings // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so avoid this method if you might be calling external encodings. [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); char[] arrChar = new char[count]; int index; for (index = 0; index < count; index++) arrChar[index] = chars[index]; return GetByteCount(arrChar, 0, count, flush); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. The method encodes charCount characters from // chars starting at index charIndex, storing the resulting // bytes in bytes starting at index byteIndex. The encoding // takes into account the state in which the encoder was left following the // last call to this method. The flush parameter indicates whether // the encoder should flush any shift-states and partial characters at the // end of the conversion. To ensure correct termination of a sequence of // blocks of encoded bytes, the last call to GetBytes should specify // a value of true for the flush parameter. // // An exception occurs if the byte array is not large enough to hold the // complete encoding of the characters. The GetByteCount method can // be used to determine the exact number of bytes that will be produced for // a given range of characters. Alternatively, the GetMaxByteCount // method of the Encoding that produced this encoder can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush); // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implimentation of an // external GetBytes() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the byte[] to our byte* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow byteCount either. [System.Security.SecurityCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(false)] internal virtual unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate input parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Get the char array to convert char[] arrChar = new char[charCount]; int index; for (index = 0; index < charCount; index++) arrChar[index] = chars[index]; // Get the byte array to fill byte[] arrByte = new byte[byteCount]; // Do the work int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush); Contract.Assert(result <= byteCount, "Returned more bytes than we have space for"); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't // rely on result because it could be a 3rd party implimentation. We need // to make sure we never copy more than byteCount bytes no matter the value // of result if (result < byteCount) byteCount = result; // Don't copy too many bytes! for (index = 0; index < byteCount; index++) bytes[index] = arrByte[index]; return byteCount; } // This method is used to avoid running out of output buffer space. // It will encode until it runs out of chars, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted chars and output bytes used. // It will only throw a buffer overflow exception if the entire lenght of bytes[] is // too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [System.Runtime.InteropServices.ComVisible(false)] public virtual void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); charsUsed = charCount; // Its easy to do if it won't overrun our buffer. // Note: We don't want to call unsafe version because that might be an untrusted version // which could be really unsafe and we don't want to mix it up. while (charsUsed > 0) { if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush); completed = (charsUsed == charCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; namespace Microsoft.Glee.Optimization { [Serializable] public class RevisedSimplexMethod : LinearProgramInterface { #region Object Invariant [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(nVars >= 0); Contract.Invariant(nSlacks >= 0); //Contract.Invariant(epsilon > 0.0f); Contract.Invariant(maxForConstraint > 0.0f); Contract.Invariant(this.constraints != null); } #endregion #region Fields readonly List<Constraint> constraints = new List<Constraint>(); double[] costs; readonly double epsilon = 10.0E-8; double epsilonForArtificials = 0.0001; double etaEpsilon = 1.0E-7; int[] forbiddenPairs; Dictionary<int, double> knownValues; bool lookForZeroColumns; bool[] lowBoundIsSet; double[] lowBounds; public RevisedSimplexMethod() { } /// <summary> /// each constraint is scaled into maxInterval /// </summary> readonly double maxForConstraint = 100; readonly double minForConstraint = 100; int nArtificials; int nSlacks; int nVars; [NonSerialized] RevisedSolver solver; Status status = Status.Unknown; bool[] upperBoundIsSet; double[] upperBounds; bool useScaling; double[] varScaleFactors; //we replace each variable x[i] by varScaleFactors[i]*x[i] public bool UseScaling { get { return useScaling; } set { useScaling = value; } } internal int NVars { get { Contract.Ensures(Contract.Result<int>() >= 0); return nVars; } set { Contract.Requires(value >= 0); nVars = value; lowBoundIsSet = new bool[nVars]; lowBounds = new double[nVars]; upperBoundIsSet = new bool[nVars]; upperBounds = new double[nVars]; } } public bool LookForZeroColumns { get { return lookForZeroColumns; } set { lookForZeroColumns = value; } } #endregion #region LinearProgramInterface Members public double GetMinimalValue() { if (Status == Status.Unknown || Status == Status.Feasible) { Minimize(); } if (Status == Status.Optimal) { double[] sol = MinimalSolution(); return -LP.DotProduct(sol, costs, costs.Length); //minus since we reversed the costs } return 0; } public int[] ForbiddenPairs { get { return forbiddenPairs; } set { forbiddenPairs = value; } } public double Epsilon { get { return epsilon; } //set { epsilon = value; } } [ContractVerification(false)] public double[] FeasibleSolution() { int reps = 0; Status stat = status; do { if (reps > 0) status = stat; reps++; if (status == Status.Optimal) return MinimalSolution(); StageOne(); etaEpsilon *= 10; if (reps > 5) throw new InvalidOperationException(); } while (solver.Status == Status.FloatingPointError); if (solver.Status != Status.Optimal || status == Status.Infeasible) { status = Status.Infeasible; return null; } status = Status.Feasible; var ret = new double[nVars]; for (int i = 0; i < nVars; i++) ret[i] = solver.XStar[i]; return ret; } public double[] MinimalSolution() { if (costs == null) throw new InvalidOperationException( #if DEBUG "costs are not set" #endif ); Minimize(); if (Status == Status.Optimal) { var ret = new double[NVars]; if (UseScaling) for (int i = 0; i < NVars; i++) { Contract.Assume(varScaleFactors[i] != 0); ret[i] = solver.XStar[i] / varScaleFactors[i]; } else for (int i = 0; i < NVars; i++) ret[i] = solver.XStar[i]; return ret; } return null; } /// <summary> /// Call this method only in case when the program is infeasible. /// The linear program will be transformed to the form Ax=b. /// The corresponding quadratic program is /// minimize||Ax-b||, x>=0 /// where ||.|| is the Euclidean norm. /// The solution always exists. /// Null is returned however if the matrix is too big /// </summary> /// <returns>approximation to solution</returns> public double[] LeastSquareSolution() { //calculate matrix A row length Contract.Assume(constraints.Count > 0); int l = constraints[0].coeffs.Length; int n = l; foreach (Constraint c in constraints) if (c.relation != Relation.Equal) n++; //this is code without any optimizations, well, almost any int m = constraints.Count; //number of rows in A var A = new double[m * n]; int offset = 0; int slackVarOffset = 0; for (int i = 0; i < m; i++) { double[] coeff = constraints[i].coeffs; //copy coefficients for (int j = 0; j < l; j++) A[offset + j] = coeff[j]; Relation r = constraints[i].relation; if (r == Relation.LessOrEqual) A[offset + l + slackVarOffset++] = 1; //c[i]*x+1*ui=b[i] else if (r == Relation.GreaterOrEqual) A[offset + l + slackVarOffset++] = -1; //c[i]*x-1*ui=b[i] offset += n; } var qp = new QP(); //setting Q for (int i = 0; i < n; i++) for (int j = i; j < n; j++) { double q = 0; for (offset = 0; offset < A.Length; offset += n) q += A[offset + i] * A[offset + j]; if (i == j) qp.SetQMember(i, j, q); else qp.SetQMember(i, j, q / 2); } var linearCost = new double[n]; for (int k = 0; k < n; k++) { double c = 0; offset = k; for (int j = 0; j < m; j++, offset += n) c += constraints[j].rightSide * A[offset]; linearCost[k] = c; } qp.SetLinearCosts(linearCost); //we have no constraints in qp except the default: solution has to be not negative double[] sol = qp.Solution; if (qp.Status != Status.Optimal) throw new InvalidOperationException(); var ret = new double[l]; for (int i = 0; i < l; i++) ret[i] = sol[i]; return ret; } public void InitCosts(double[] costsParam) { Contract.Assume(NVars == 0 || NVars == costsParam.Length); if (NVars == 0) NVars = costsParam.Length; if (costs == null) costs = new double[costsParam.Length]; //flip the costs signs since we are maximizing inside of the solver Contract.Assume(costs.Length >= NVars); for (int i = 0; i < NVars; i++) { Contract.Assert(i < costs.Length); Contract.Assume(i < costsParam.Length); costs[i] = -costsParam[i]; } if (solver != null) { if (solver.Costs != null) { for (int i = 0; i < costsParam.Length; i++) solver.Costs[i] = -costsParam[i]; } if (status == Status.Unbounded || status == Status.Optimal) { status = Status.Feasible; solver.Status = status; } } } public void SetVariable(int i, double val) { if (knownValues == null) knownValues = new Dictionary<int, double>(); knownValues[i] = val; } /// <summary> /// Adds a constraint to the linear program. /// </summary> /// <param name="coeff"></param> /// <param name="relation"></param> /// <param name="rightSide"></param> public void AddConstraint(double[] coeff, Relation relation, double rightSide) { Contract.Assume(NVars == 0 || NVars == coeff.Length); if (NVars == 0) NVars = coeff.Length; var c = new Constraint(coeff.Clone() as double[], relation, rightSide); Contract.Assume(c.coeffs != null); if (UseScaling) ScaleConstraint(c); constraints.Add(c); } public void Minimize() { int reps = 0; Status stat = Status; do { Status = stat; if (Status == Status.Infeasible || Status == Status.Optimal) return; if (Status != Status.Feasible) StageOne(); if (Status == Status.Feasible) StageTwo(); etaEpsilon *= 10; reps++; if (reps > 5) throw new InvalidOperationException(); } while (Status == Status.FloatingPointError); } public Status Status { get { return status; } set { status = value; } } public void LimitVariableFromBelow(int var, double l) { Contract.Assume(upperBoundIsSet[var] == false || upperBounds[var] >= l); lowBoundIsSet[var] = true; lowBounds[var] = l; } public void LimitVariableFromAbove(int var, double l) { Contract.Assume(lowBoundIsSet[var] == false || lowBounds[var] <= l); upperBoundIsSet[var] = true; upperBounds[var] = l; } public double EpsilonForArtificials { get { return epsilonForArtificials; } set { epsilonForArtificials = value; } } public double EpsilonForReducedCosts { get { return 0; } set { } } #endregion T[] DupArray<T>(T[] source) { if (source == null) return null; var result = new T[source.Length]; Array.Copy(source, result, source.Length); return result; } void StageOne() { #region Preparing the first stage solver if (UseScaling) IntroduceVariableScaleFactors(); var xStar = new double[NVars]; FillAcceptableValues(xStar); CountSlacksAndArtificials(xStar); int artificialsStart = NVars + nSlacks; int totalVars = NVars + nSlacks + nArtificials; Contract.Assume(totalVars > 0); // F: it seems to be some property of the implementation var nxstar = new double[totalVars]; xStar.CopyTo(nxstar, 0); xStar = nxstar; var basis = new int[constraints.Count]; var solverLowBoundIsSet = new bool[totalVars]; var solverLowBounds = new double[totalVars]; var solverUpperBoundIsSet = new bool[totalVars]; var solverUpperBounds = new double[totalVars]; var solverCosts = new double[totalVars]; lowBoundIsSet.CopyTo(solverLowBoundIsSet, 0); lowBounds.CopyTo(solverLowBounds, 0); upperBoundIsSet.CopyTo(solverUpperBoundIsSet, 0); upperBounds.CopyTo(solverUpperBounds, 0); Contract.Assume(nSlacks + nArtificials >= 0); // F: It seems to be some property of the implementation var AOfSolver = new ExtendedConstraintMatrix(constraints, nSlacks + nArtificials); FillFirstStageSolverAndCosts(solverLowBoundIsSet, solverLowBounds, solverUpperBoundIsSet, solverUpperBounds, solverCosts, AOfSolver, basis, xStar); solver = new RevisedSolver(basis, xStar, artificialsStart, AOfSolver, solverCosts, solverLowBoundIsSet, solverLowBounds, solverUpperBoundIsSet, solverUpperBounds, ForbiddenPairs, constraints, etaEpsilon ); #endregion ProcessKnownValues(); solver.Solve(); if (solver.Status == Status.FloatingPointError) return; HandleArtificialVariablesAndDecideOnStatus(artificialsStart, ref basis, AOfSolver as ExtendedConstraintMatrix); } void IntroduceVariableScaleFactors() { varScaleFactors = new double[nVars]; for (int i = 0; i < nVars; i++) IntroduceVariableScaleFactor(i); foreach (Constraint c in constraints) for (int i = 0; i < nVars; i++) { Contract.Assume(varScaleFactors[i] != 0); c.coeffs[i] /= varScaleFactors[i]; } } void IntroduceVariableScaleFactor(int i) { Contract.Requires(i >= 0); double max = 0; foreach (Constraint c in constraints) { double d = Math.Abs(c.coeffs[i]); if (d > max) max = d; } if (max > maxForConstraint) { //we need to find s such that max/s<=maxInterval => s>=max/ maxForConstraint int s = 2; double d = max / maxForConstraint; while (s < d) s *= 2; varScaleFactors[i] = s; } else if (max > epsilon && max < minForConstraint) { //max*s>=minForConstraint //s>=minForConstraint/max double d = minForConstraint / max; int s = 2; while (s < d) s *= 2; varScaleFactors[i] = 1.0 / s; } else if (max == 0) { varScaleFactors[i] = 1; SetVariable(i, GetAcceptableValue(i)); } else varScaleFactors[i] = 1; } void ProcessKnownValues() { if (knownValues != null) foreach (var kv in knownValues) { int var = kv.Key; double val = kv.Value; solver.index[var] = RevisedSolver.forgottenVar; solver.XStar[var] = val; } } void HandleArtificialVariablesAndDecideOnStatus(int artificialsStart, ref int[] basis, ExtendedConstraintMatrix AOfSolver) { Contract.Requires(AOfSolver != null); //check that there are no artificial variables having positive values //see box 8.2 on page 130 for (int k = 0; k < basis.Length; k++) { if (basis[k] >= artificialsStart) { if (Math.Abs(solver.XStar[basis[k]]) > EpsilonForArtificials) { status = Status.Infeasible; return; } var r = new double[basis.Length]; r[k] = 1; solver.Factorization.Solve_yBEquals_cB(r); var cloned = r.Clone() as double[]; Contract.Assume(cloned != null); var vr = new Vector(cloned); foreach (int j in solver.NBasis()) { if (j < artificialsStart) { Contract.Assume(j >= 0); // F: Need quantified invariants here Contract.Assume(j < AOfSolver.NumberOfColumns); var colVector = new ColumnVector(AOfSolver, j); Contract.Assume(vr.Length == colVector.NumberOfRows); if (Math.Abs(vr * colVector) > epsilon) { AOfSolver.FillColumn(j, r); solver.Factorization.Solve_BdEqualsa(r); solver.Factorization.AddEtaMatrix(new EtaMatrix(k, r)); solver.ReplaceInBasis(j, basis[k]); break; } } } } } //now remove the remaining artificial variables if any for (int k = 0; k < basis.Length; k++) { Contract.Assume(k < constraints.Count); // F: basis's length is < of the # of constraints if (basis[k] >= artificialsStart) { //cross out k-th constraint //shrink basis var nBas = new int[basis.Length - 1]; int j = 0; for (int i = 0; i < basis.Length; i++) { if (i != k) { Contract.Assume(j < nBas.Length); nBas[j++] = basis[i]; } } //taking care of the solver extended matrix constraints.RemoveAt(k); int[] sa = AOfSolver.slacksAndArtificials; for (int i = 0; i < sa.Length; i++) if (sa[i] > k) sa[i]--; else if (sa[i] == k) sa[i] = -1; //this will take put the column to zero solver.index[basis[k]] = RevisedSolver.forgottenVar; solver.basis = basis = nBas; for (int i = k; i < basis.Length; i++) solver.index[basis[i]] = i; k--; solver.Factorization = null; // to ensure the refactorization solver.A = new ExtendedConstraintMatrix(constraints, sa); solver.U = new UMatrix(nBas.Length); } } status = Status.Feasible; } void FillFirstStageSolverAndCosts( bool[] solverLowBoundIsSet, double[] solverLowBounds, bool[] solverUpperBoundIsSet, double[] solverUpperBounds, double[] solverCosts, Matrix A, int[] basis, double[] xStar) { Contract.Requires(solverUpperBounds != null); Contract.Requires(solverLowBounds != null); Contract.Requires(solverLowBoundIsSet != null); Contract.Requires(solverUpperBoundIsSet != null); Contract.Requires(solverCosts != null); Contract.Requires(A != null); Contract.Requires(xStar != null); int slackVar = NVars; int artificialVar = NVars + nSlacks; int row = 0; foreach (Constraint c in constraints) { Contract.Assume(row < basis.Length); //we need to bring the program to the form Ax=b double rs = c.rightSide - LP.DotProduct(xStar, c.coeffs, nVars); switch (c.relation) { case Relation.Equal: //no slack variable here if (rs >= 0) { SetZeroBound(solverLowBoundIsSet, solverLowBounds, artificialVar); Contract.Assume(artificialVar < solverCosts.Length); solverCosts[artificialVar] = -1; //we are maximizing, so the artificial, which is non-negatiive, will be pushed to zero } else { SetZeroBound(solverUpperBoundIsSet, solverUpperBounds, artificialVar); Contract.Assume(artificialVar < solverCosts.Length); solverCosts[artificialVar] = 1; } basis[row] = artificialVar; A[row, artificialVar++] = 1; break; case Relation.GreaterOrEqual: //introduce a non-positive slack variable, Contract.Assume(slackVar < solverUpperBoundIsSet.Length); Contract.Assume(slackVar < solverUpperBounds.Length); SetZeroBound(solverUpperBoundIsSet, solverUpperBounds, slackVar); A[row, slackVar] = 1; if (rs > 0) { //adding one artificial which is non-negative SetZeroBound(solverLowBoundIsSet, solverLowBounds, artificialVar); A[row, artificialVar] = 1; solverCosts[artificialVar] = -1; basis[row] = artificialVar++; } else { //we can put slackVar into basis, and avoid adding an artificial variable //We will have an equality c.coefficients*acceptableCosts+x[slackVar]=c.rightSide, or x[slackVar]=rs<=0. basis[row] = slackVar; } slackVar++; break; case Relation.LessOrEqual: //introduce a non-negative slack variable, Contract.Assume(slackVar < solverLowBoundIsSet.Length); Contract.Assume(slackVar < solverLowBounds.Length); SetZeroBound(solverLowBoundIsSet, solverLowBounds, slackVar); A[row, slackVar] = 1; if (rs < 0) { //adding one artificial which is non-positive SetZeroBound(solverUpperBoundIsSet, solverUpperBounds, artificialVar); A[row, artificialVar] = 1; Contract.Assume(artificialVar < solverCosts.Length); solverCosts[artificialVar] = 1; basis[row] = artificialVar++; } else { //we can put slackVar into basis, and avoid adding an artificial variable //We will have an equality c.coefficients*acceptableCosts+x[slackVar]=c.rightSide, or x[slackVar]=rs<=0. basis[row] = slackVar; } slackVar++; break; } xStar[basis[row]] = rs; row++; } } /// <summary> /// fill the original values with some values from their [lowBound, upperBound] intervals /// </summary> /// <returns></returns> void FillAcceptableValues(double[] xStar) { Contract.Assume(xStar.Length >= nVars); double val; for (int i = 0; i < nVars; i++) { if (knownValues == null || knownValues.TryGetValue(i, out val) == false) { xStar[i] = GetAcceptableValue(i); } else { xStar[i] = val; } } } /// <summary> /// return a number from the variable domain /// </summary> /// <param name="x"></param> /// <param name="i"></param> [Pure] double GetAcceptableValue(int i) { if (lowBoundIsSet[i]) return lowBounds[i]; if (upperBoundIsSet[i]) return upperBounds[i]; return 0; } static void SetZeroBound(bool[] boundIsSet, double[] bounds, int var) { Contract.Assume(var < boundIsSet.Length); Contract.Assume(var < bounds.Length); boundIsSet[var] = true; bounds[var] = 0; } void CountSlacksAndArtificials(double[] xStar) { foreach (Constraint constraint in constraints) CountSlacksAndArtificialsForConstraint(constraint, xStar); } void CountSlacksAndArtificialsForConstraint(Constraint constraint, double[] xStar) { double rightSide = constraint.rightSide - LP.DotProduct(constraint.coeffs, xStar); switch (constraint.relation) { case Relation.Equal: nArtificials++; break; case Relation.GreaterOrEqual: nSlacks++; if (rightSide > 0) nArtificials++; break; case Relation.LessOrEqual: nSlacks++; if (rightSide < 0) nArtificials++; break; } } //static int calls; void StageTwo() { PrepareStageTwo(); solver.Solve(); status = solver.Status; } void PrepareStageTwo() { int i; for (i = NVars + nSlacks; i < NVars + nSlacks + nArtificials; i++) solver.ForgetVariable(i); var solverMatrix = solver.A; Contract.Assume(solverMatrix != null); solverMatrix.NumberOfColumns = NVars + nSlacks; if (solver.y.Length != constraints.Count) solver.y = new double[constraints.Count]; //this should be refactored somehow, y is the variable for keeping solutions of the linear systems for (i = 0; i < costs.Length; i++) solver.Costs[i] = costs[i]; for (; i < solver.Costs.Length; i++) solver.Costs[i] = 0; solver.Status = Status.Feasible; } void ScaleConstraint(Constraint c) { Contract.Requires(c != null); double max = 0; for (int i = 0; i < c.coeffs.Length; i++) { double d = Math.Abs(c.coeffs[i]); if (d > max) max = d; } if (max > maxForConstraint) { //find first power of two k, such that max/k<=maxForConstraint, //that is k >= max / maxForConstraint; int k = 2; double d = max / maxForConstraint; while (k < d) k *= 2; for (int i = 0; i < c.coeffs.Length; i++) c.coeffs[i] /= k; c.rightSide /= k; } else if (max < minForConstraint && max > epsilon) { //find first power of two, k , such that max*k>=minForConstraint, // or k>=minForConstrant/max double d = minForConstraint / max; int k = 2; while (k < d) k *= 2; for (int i = 0; i < c.coeffs.Length; i++) c.coeffs[i] *= k; c.rightSide *= k; } } } }
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 Epi.MetadataAccessServiceAPI.Areas.HelpPage.ModelDescriptions; using Epi.MetadataAccessServiceAPI.Areas.HelpPage.Models; namespace Epi.MetadataAccessServiceAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections; using System.Collections.Generic; namespace Lex { public class Minimize { private Spec spec; private List<List<DTrans>> group; private int[] ingroup; public Minimize() { this.reset(); } private void reset() { this.spec = null; this.group = null; this.ingroup = null; } private void set(Spec s) { this.spec = s; this.group = null; this.ingroup = null; } public void min_dfa(Spec s) { this.set(s); this.minimize(); this.reduce(); this.reset(); } private void col_copy(int dest, int src) { int count = this.spec.dtrans_list.Count; for (int i = 0; i < count; i++) { DTrans dTrans = this.spec.dtrans_list[i]; dTrans.SetDTrans(dest, dTrans.GetDTrans(src)); } } private void row_copy(int dest, int src) { this.spec.dtrans_list[dest] = this.spec.dtrans_list[src]; } private bool col_equiv(int col1, int col2) { int count = this.spec.dtrans_list.Count; for (int i = 0; i < count; i++) { DTrans dTrans = this.spec.dtrans_list[i]; if (dTrans.GetDTrans(col1) != dTrans.GetDTrans(col2)) { return false; } } return true; } private bool row_equiv(int row1, int row2) { DTrans dTrans = this.spec.dtrans_list[row1]; DTrans dTrans2 = this.spec.dtrans_list[row2]; for (int i = 0; i < this.spec.dtrans_ncols; i++) { if (dTrans.GetDTrans(i) != dTrans2.GetDTrans(i)) { return false; } } return true; } private void reduce() { int count = this.spec.dtrans_list.Count; BitArray bitArray = new BitArray(count); this.spec.anchor_array = new int[count]; this.spec.accept_list = new List<Accept>(); for (int i = 0; i < count; i++) { DTrans dTrans = this.spec.dtrans_list[i]; this.spec.accept_list.Add(dTrans.GetAccept()); this.spec.anchor_array[i] = dTrans.GetAnchor(); dTrans.SetAccept(null); } this.spec.col_map = new int[this.spec.dtrans_ncols]; for (int i = 0; i < this.spec.dtrans_ncols; i++) { this.spec.col_map[i] = -1; } int num = 0; while (true) { int i; for (i = 0; i < num; i++) { } i = num; while (i < this.spec.dtrans_ncols && -1 != this.spec.col_map[i]) { i++; } if (i >= this.spec.dtrans_ncols) { break; } if (i >= bitArray.Length) { bitArray.Length = i + 1; } bitArray.Set(i, true); this.spec.col_map[i] = num; for (int j = i + 1; j < this.spec.dtrans_ncols; j++) { if (-1 == this.spec.col_map[j] && this.col_equiv(i, j)) { this.spec.col_map[j] = num; } } num++; } int num2 = 0; for (int i = 0; i < this.spec.dtrans_ncols; i++) { if (i >= bitArray.Length) { bitArray.Length = i + 1; } if (bitArray.Get(i)) { num2++; bitArray.Set(i, false); int j = this.spec.col_map[i]; if (j != i) { this.col_copy(j, i); } } } this.spec.dtrans_ncols = num; int count2 = this.spec.dtrans_list.Count; this.spec.row_map = new int[count2]; for (int i = 0; i < count2; i++) { this.spec.row_map[i] = -1; } int num3 = 0; while (true) { int i; for (i = 0; i < num3; i++) { } i = num3; while (i < count2 && -1 != this.spec.row_map[i]) { i++; } if (i >= count2) { break; } bitArray.Set(i, true); this.spec.row_map[i] = num3; for (int j = i + 1; j < count2; j++) { if (-1 == this.spec.row_map[j] && this.row_equiv(i, j)) { this.spec.row_map[j] = num3; } } num3++; } num2 = 0; for (int i = 0; i < count2; i++) { if (bitArray.Get(i)) { num2++; bitArray.Set(i, false); int j = this.spec.row_map[i]; if (j != i) { this.row_copy(j, i); } } } this.spec.dtrans_list.RemoveRange(num3, count - num3); } private void fix_dtrans() { List<DTrans> list = new List<DTrans>(); int num = this.spec.state_dtrans.Length; for (int i = 0; i < num; i++) { if (-1 != this.spec.state_dtrans[i]) { this.spec.state_dtrans[i] = this.ingroup[this.spec.state_dtrans[i]]; } } num = this.group.Count; for (int i = 0; i < num; i++) { List<DTrans> list2 = this.group[i]; DTrans dTrans = list2[0]; list.Add(dTrans); for (int j = 0; j < this.spec.dtrans_ncols; j++) { if (-1 != dTrans.GetDTrans(j)) { dTrans.SetDTrans(j, this.ingroup[dTrans.GetDTrans(j)]); } } } this.group = null; this.spec.dtrans_list = list; } private void minimize() { this.init_groups(); int num = this.group.Count; int num2 = num - 1; while (num2 != num) { num2 = num; for (int i = 0; i < num; i++) { List<DTrans> list = this.group[i]; int num3 = list.Count; if (num3 > 1) { List<DTrans> list2 = new List<DTrans>(); bool flag = false; DTrans dTrans = list[0]; for (int j = 1; j < num3; j++) { DTrans dTrans2 = list[j]; for (int k = 0; k < this.spec.dtrans_ncols; k++) { int dTrans3 = dTrans.GetDTrans(k); int dTrans4 = dTrans2.GetDTrans(k); if (dTrans3 != dTrans4 && (dTrans3 == -1 || dTrans4 == -1 || this.ingroup[dTrans4] != this.ingroup[dTrans3])) { list.RemoveAt(j); j--; num3--; list2.Add(dTrans2); if (!flag) { flag = true; num++; this.group.Add(list2); } this.ingroup[dTrans2.Label] = this.group.Count - 1; break; } } } } } } Console.WriteLine(this.group.Count + " states after removal of redundant states."); this.fix_dtrans(); } private void init_groups() { int num = 0; this.group = new List<List<DTrans>>(); int count = this.spec.dtrans_list.Count; this.ingroup = new int[count]; for (int i = 0; i < count; i++) { bool flag = false; DTrans dTrans = this.spec.dtrans_list[i]; for (int j = 0; j < num; j++) { List<DTrans> list = this.group[j]; DTrans dTrans2 = list[0]; for (int k = 1; k < list.Count; k++) { } if (dTrans2.GetAccept() == dTrans.GetAccept()) { list.Add(dTrans); this.ingroup[i] = j; flag = true; break; } } if (!flag) { List<DTrans> list2 = new List<DTrans>(); list2.Add(dTrans); this.ingroup[i] = this.group.Count; this.group.Add(list2); num++; } } } private void pset(List<DTrans> dtrans_group) { int count = dtrans_group.Count; for (int i = 0; i < count; i++) { DTrans dTrans = dtrans_group[i]; Console.Write(dTrans.Label + " "); } } private void pgroups() { int count = this.group.Count; for (int i = 0; i < count; i++) { Console.Write("\tGroup " + i + " {"); this.pset(this.group[i]); Console.WriteLine("}\n"); } Console.WriteLine(""); int count2 = this.spec.dtrans_list.Count; for (int j = 0; j < count2; j++) { Console.WriteLine(string.Concat(new object[] { "\tstate ", j, " is in group ", this.ingroup[j] })); } } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> Base class for Attributes that can be added to a /// <see cref="Lucene.Net.Util.AttributeSource" />. /// <para/> /// Attributes are used to add data in a dynamic, yet type-safe way to a source /// of usually streamed objects, e. g. a <see cref="Lucene.Net.Analysis.TokenStream" />. /// </summary> public abstract class Attribute : IAttribute #if FEATURE_CLONEABLE : System.ICloneable #endif { /// <summary> Clears the values in this <see cref="Attribute"/> and resets it to its /// default value. If this implementation implements more than one <see cref="Attribute"/> interface /// it clears all. /// </summary> public abstract void Clear(); /// <summary> /// This is equivalent to the anonymous class in the Java version of ReflectAsString /// </summary> private class StringBuilderAttributeReflector : IAttributeReflector { private readonly StringBuilder buffer; private readonly bool prependAttClass; public StringBuilderAttributeReflector(StringBuilder buffer, bool prependAttClass) { this.buffer = buffer; this.prependAttClass = prependAttClass; } public void Reflect<T>(string key, object value) where T : IAttribute { Reflect(typeof(T), key, value); } public void Reflect(Type type, string key, object value) { if (buffer.Length > 0) { buffer.Append(','); } if (prependAttClass) { buffer.Append(type.Name).Append('#'); } buffer.Append(key).Append('=').Append(object.ReferenceEquals(value, null) ? (object)"null" : value); } } /// <summary> /// This method returns the current attribute values as a string in the following format /// by calling the <see cref="ReflectWith(IAttributeReflector)"/> method: /// <list type="bullet"> /// <item><term>if <paramref name="prependAttClass"/>=true:</term> <description> <c>"AttributeClass.Key=value,AttributeClass.Key=value"</c> </description></item> /// <item><term>if <paramref name="prependAttClass"/>=false:</term> <description> <c>"key=value,key=value"</c> </description></item> /// </list> /// </summary> /// <seealso cref="ReflectWith(IAttributeReflector)"/> public string ReflectAsString(bool prependAttClass) { StringBuilder buffer = new StringBuilder(); ReflectWith(new StringBuilderAttributeReflector(buffer, prependAttClass)); return buffer.ToString(); } /// <summary> /// This method is for introspection of attributes, it should simply /// add the key/values this attribute holds to the given <see cref="IAttributeReflector"/>. /// /// <para/>The default implementation calls <see cref="IAttributeReflector.Reflect(Type, string, object)"/> for all /// non-static fields from the implementing class, using the field name as key /// and the field value as value. The <see cref="IAttribute"/> class is also determined by Reflection. /// Please note that the default implementation can only handle single-Attribute /// implementations. /// /// <para/>Custom implementations look like this (e.g. for a combined attribute implementation): /// <code> /// public void ReflectWith(IAttributeReflector reflector) /// { /// reflector.Reflect(typeof(ICharTermAttribute), "term", GetTerm()); /// reflector.Reflect(typeof(IPositionIncrementAttribute), "positionIncrement", GetPositionIncrement()); /// } /// </code> /// /// <para/>If you implement this method, make sure that for each invocation, the same set of <see cref="IAttribute"/> /// interfaces and keys are passed to <see cref="IAttributeReflector.Reflect(Type, string, object)"/> in the same order, but possibly /// different values. So don't automatically exclude e.g. <c>null</c> properties! /// </summary> /// <seealso cref="ReflectAsString(bool)"/> public virtual void ReflectWith(IAttributeReflector reflector) // LUCENENET NOTE: This method was abstract in Lucene { Type clazz = this.GetType(); LinkedList<WeakReference<Type>> interfaces = AttributeSource.GetAttributeInterfaces(clazz); if (interfaces.Count != 1) { throw new NotSupportedException(clazz.Name + " implements more than one Attribute interface, the default ReflectWith() implementation cannot handle this."); } interfaces.First.Value.TryGetTarget(out Type interf); //problem: the interfaces list has weak references that could have expired already FieldInfo[] fields = clazz.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); try { for (int i = 0; i < fields.Length; i++) { FieldInfo f = fields[i]; if (f.IsStatic) continue; reflector.Reflect(interf, f.Name, f.GetValue(this)); } } catch (MemberAccessException e) { throw new Exception(e.ToString(), e); } } /// <summary> The default implementation of this method accesses all declared /// fields of this object and prints the values in the following syntax: /// /// <code> /// public String ToString() /// { /// return "start=" + startOffset + ",end=" + endOffset; /// } /// </code> /// /// This method may be overridden by subclasses. /// </summary> public override string ToString() // LUCENENET NOTE: This method didn't exist in Lucene { StringBuilder buffer = new StringBuilder(); Type clazz = this.GetType(); FieldInfo[] fields = clazz.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static); for (int i = 0; i < fields.Length; i++) { FieldInfo f = fields[i]; if (f.IsStatic) continue; //f.setAccessible(true); // {{Aroush-2.9}} java.lang.reflect.AccessibleObject.setAccessible object value = f.GetValue(this); if (buffer.Length > 0) { buffer.Append(','); } if (value == null) { buffer.Append(f.Name + "=null"); } else { buffer.Append(f.Name + "=" + value); } } return buffer.ToString(); } /// <summary> Copies the values from this <see cref="Attribute"/> into the passed-in /// <paramref name="target"/> attribute. The <paramref name="target"/> implementation must support all the /// <see cref="IAttribute"/>s this implementation supports. /// </summary> public abstract void CopyTo(IAttribute target); /// <summary> Shallow clone. Subclasses must override this if they /// need to clone any members deeply, /// </summary> public virtual object Clone() { return base.MemberwiseClone(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using JetBrains.Annotations; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; using Microsoft.Extensions.Logging; namespace JsonApiDotNetCore.Configuration { /// <summary> /// Builds and configures the <see cref="ResourceGraph" />. /// </summary> [PublicAPI] public class ResourceGraphBuilder { private readonly IJsonApiOptions _options; private readonly ILogger<ResourceGraphBuilder> _logger; private readonly HashSet<ResourceContext> _resourceContexts = new(); private readonly TypeLocator _typeLocator = new(); public ResourceGraphBuilder(IJsonApiOptions options, ILoggerFactory loggerFactory) { ArgumentGuard.NotNull(options, nameof(options)); ArgumentGuard.NotNull(loggerFactory, nameof(loggerFactory)); _options = options; _logger = loggerFactory.CreateLogger<ResourceGraphBuilder>(); } /// <summary> /// Constructs the <see cref="ResourceGraph" />. /// </summary> public IResourceGraph Build() { return new ResourceGraph(_resourceContexts); } /// <summary> /// Adds a JSON:API resource with <code>int</code> as the identifier type. /// </summary> /// <typeparam name="TResource"> /// The resource model type. /// </typeparam> /// <param name="publicName"> /// The name under which the resource is publicly exposed by the API. If nothing is specified, the configured naming convention formatter will be /// applied. /// </param> public ResourceGraphBuilder Add<TResource>(string publicName = null) where TResource : class, IIdentifiable<int> { return Add<TResource, int>(publicName); } /// <summary> /// Adds a JSON:API resource. /// </summary> /// <typeparam name="TResource"> /// The resource model type. /// </typeparam> /// <typeparam name="TId"> /// The resource model identifier type. /// </typeparam> /// <param name="publicName"> /// The name under which the resource is publicly exposed by the API. If nothing is specified, the configured naming convention formatter will be /// applied. /// </param> public ResourceGraphBuilder Add<TResource, TId>(string publicName = null) where TResource : class, IIdentifiable<TId> { return Add(typeof(TResource), typeof(TId), publicName); } /// <summary> /// Adds a JSON:API resource. /// </summary> /// <param name="resourceType"> /// The resource model type. /// </param> /// <param name="idType"> /// The resource model identifier type. /// </param> /// <param name="publicName"> /// The name under which the resource is publicly exposed by the API. If nothing is specified, the configured naming convention formatter will be /// applied. /// </param> public ResourceGraphBuilder Add(Type resourceType, Type idType = null, string publicName = null) { ArgumentGuard.NotNull(resourceType, nameof(resourceType)); if (_resourceContexts.Any(resourceContext => resourceContext.ResourceType == resourceType)) { return this; } if (resourceType.IsOrImplementsInterface(typeof(IIdentifiable))) { string effectivePublicName = publicName ?? FormatResourceName(resourceType); Type effectiveIdType = idType ?? _typeLocator.TryGetIdType(resourceType); ResourceContext resourceContext = CreateResourceContext(effectivePublicName, resourceType, effectiveIdType); _resourceContexts.Add(resourceContext); } else { _logger.LogWarning($"Entity '{resourceType}' does not implement '{nameof(IIdentifiable)}'."); } return this; } private ResourceContext CreateResourceContext(string publicName, Type resourceType, Type idType) { IReadOnlyCollection<AttrAttribute> attributes = GetAttributes(resourceType); IReadOnlyCollection<RelationshipAttribute> relationships = GetRelationships(resourceType); IReadOnlyCollection<EagerLoadAttribute> eagerLoads = GetEagerLoads(resourceType); var linksAttribute = (ResourceLinksAttribute)resourceType.GetCustomAttribute(typeof(ResourceLinksAttribute)); return linksAttribute == null ? new ResourceContext(publicName, resourceType, idType, attributes, relationships, eagerLoads) : new ResourceContext(publicName, resourceType, idType, attributes, relationships, eagerLoads, linksAttribute.TopLevelLinks, linksAttribute.ResourceLinks, linksAttribute.RelationshipLinks); } private IReadOnlyCollection<AttrAttribute> GetAttributes(Type resourceType) { var attributes = new List<AttrAttribute>(); foreach (PropertyInfo property in resourceType.GetProperties()) { var attribute = (AttrAttribute)property.GetCustomAttribute(typeof(AttrAttribute)); // Although strictly not correct, 'id' is added to the list of attributes for convenience. // For example, it enables to filter on ID, without the need to special-case existing logic. // And when using sparse fields, it silently adds 'id' to the set of attributes to retrieve. if (property.Name == nameof(Identifiable.Id) && attribute == null) { var idAttr = new AttrAttribute { PublicName = FormatPropertyName(property), Property = property, Capabilities = _options.DefaultAttrCapabilities }; attributes.Add(idAttr); continue; } if (attribute == null) { continue; } attribute.PublicName ??= FormatPropertyName(property); attribute.Property = property; if (!attribute.HasExplicitCapabilities) { attribute.Capabilities = _options.DefaultAttrCapabilities; } attributes.Add(attribute); } return attributes; } private IReadOnlyCollection<RelationshipAttribute> GetRelationships(Type resourceType) { var attributes = new List<RelationshipAttribute>(); PropertyInfo[] properties = resourceType.GetProperties(); foreach (PropertyInfo property in properties) { var attribute = (RelationshipAttribute)property.GetCustomAttribute(typeof(RelationshipAttribute)); if (attribute != null) { attribute.Property = property; attribute.PublicName ??= FormatPropertyName(property); attribute.LeftType = resourceType; attribute.RightType = GetRelationshipType(attribute, property); attributes.Add(attribute); } } return attributes; } private Type GetRelationshipType(RelationshipAttribute relationship, PropertyInfo property) { ArgumentGuard.NotNull(relationship, nameof(relationship)); ArgumentGuard.NotNull(property, nameof(property)); return relationship is HasOneAttribute ? property.PropertyType : property.PropertyType.GetGenericArguments()[0]; } private IReadOnlyCollection<EagerLoadAttribute> GetEagerLoads(Type resourceType, int recursionDepth = 0) { AssertNoInfiniteRecursion(recursionDepth); var attributes = new List<EagerLoadAttribute>(); PropertyInfo[] properties = resourceType.GetProperties(); foreach (PropertyInfo property in properties) { var attribute = (EagerLoadAttribute)property.GetCustomAttribute(typeof(EagerLoadAttribute)); if (attribute == null) { continue; } Type innerType = TypeOrElementType(property.PropertyType); attribute.Children = GetEagerLoads(innerType, recursionDepth + 1); attribute.Property = property; attributes.Add(attribute); } return attributes; } [AssertionMethod] private static void AssertNoInfiniteRecursion(int recursionDepth) { if (recursionDepth >= 500) { throw new InvalidOperationException("Infinite recursion detected in eager-load chain."); } } private Type TypeOrElementType(Type type) { Type[] interfaces = type.GetInterfaces() .Where(@interface => @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IEnumerable<>)).ToArray(); return interfaces.Length == 1 ? interfaces.Single().GenericTypeArguments[0] : type; } private string FormatResourceName(Type resourceType) { var formatter = new ResourceNameFormatter(_options.SerializerOptions.PropertyNamingPolicy); return formatter.FormatResourceName(resourceType); } private string FormatPropertyName(PropertyInfo resourceProperty) { return _options.SerializerOptions.PropertyNamingPolicy == null ? resourceProperty.Name : _options.SerializerOptions.PropertyNamingPolicy.ConvertName(resourceProperty.Name); } } }
//! \file ArcDAT.cs //! \date Tue Nov 03 07:05:36 2015 //! \brief ACTGS engine resource archive. // // Copyright (C) 2015-2019 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.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using GameRes.Utility; using GameRes.Compression; namespace GameRes.Formats.Actgs { [Serializable] public class ActressScheme : ResourceScheme { public byte[][] KnownKeys; } internal class ActressArchive : ArcFile { public readonly byte[] Key; public ActressArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, byte[] key) : base (arc, impl, dir) { Key = key; } } [Export(typeof(ArchiveFormat))] public class DatOpener : ArchiveFormat { public override string Tag { get { return "DAT/ACTGS"; } } public override string Description { get { return "ACTGS engine resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public DatOpener () { Extensions = new string[] { "dat" }; } internal static byte[][] KnownKeys { get { return DefaultScheme.KnownKeys; } } static ActressScheme DefaultScheme = new ActressScheme { KnownKeys = Array.Empty<byte[]>() }; public override ArcFile TryOpen (ArcView file) { int count = file.View.ReadInt32 (0); if (!IsSaneCount (count)) return null; if (0 != (file.View.ReadInt32 (4) | file.View.ReadInt32 (8) | file.View.ReadInt32 (12))) return null; const int entry_size = 0x20; uint index_length = (uint)(count * entry_size); IBinaryStream input = file.CreateStream (0x10, index_length); try { uint first_offset = 0x10u + index_length; uint actual_offset = input.Signature; byte[] key = null; if (actual_offset != first_offset) { key = FindKey (first_offset, actual_offset); if (null == key) return null; var decrypted = new ByteStringEncryptedStream (input.AsStream, key); input = new BinaryStream (decrypted, file.Name); } var reader = new IndexReader (file.MaxOffset); var dir = reader.Read (input, count); if (null == dir) return null; if (null == key) return new ArcFile (file, this, dir); else return new ActressArchive (file, this, dir, key); } finally { input.Dispose(); } } public override Stream OpenEntry (ArcFile arc, Entry entry) { var actarc = arc as ActressArchive; if (null == actarc || null == actarc.Key) return base.OpenEntry (arc, entry); if (entry.Name.HasExtension (".scr")) { if ('X' != arc.File.View.ReadByte (entry.Offset)) return base.OpenEntry (arc, entry); var data = new byte[entry.Size]; arc.File.View.Read (entry.Offset, data, 0, entry.Size); Decrypt (data, 1, data.Length-1, actarc.Key); data[0] = (byte)'N'; return new BinMemoryStream (data, entry.Name); } if (arc.File.View.AsciiEqual (entry.Offset, "PAK ")) { uint packed_size = arc.File.View.ReadUInt32 (entry.Offset+4); var input = arc.File.CreateStream (entry.Offset+12, packed_size); return new LzssStream (input); } if (entry.Name.HasExtension (".wav") && arc.File.View.AsciiEqual (entry.Offset, "RIFF")) { return arc.File.CreateStream (entry.Offset, entry.Size); } var header = ReadEntryHeader (actarc, entry); if (entry.Size <= 0x20) return new BinMemoryStream (header, entry.Name); var rest = arc.File.CreateStream (entry.Offset+0x20, entry.Size-0x20); return new PrefixStream (header, rest); } byte[] FindKey (uint first_offset, uint actual_offset) { var pattern = new byte[4]; LittleEndian.Pack (first_offset ^ actual_offset, pattern, 0); return Array.Find (KnownKeys, k => k.Take (4).SequenceEqual (pattern)); } internal static void Decrypt (byte[] data, int index, int length, byte[] key) { for (int i = 0; i < length; ++i) { data[index+i] ^= key[i % key.Length]; } } internal byte[] ReadEntryHeader (ActressArchive arc, Entry entry) { uint length = Math.Min (entry.Size, 0x20u); var header = arc.File.View.ReadBytes (entry.Offset, length); Decrypt (header, 0, header.Length, arc.Key); return header; } public override ResourceScheme Scheme { get { return DefaultScheme; } set { DefaultScheme = (ActressScheme)value; } } } internal sealed class IndexReader { long m_arc_length; List<Entry> m_dir = new List<Entry>(); public IndexReader (long arc_length) { m_arc_length = arc_length; } public List<Entry> Read (IBinaryStream input, int count) { m_dir.Clear(); if (m_dir.Capacity < count) m_dir.Capacity = count; try { for (int i = 0; i < count; ++i) { uint offset = input.ReadUInt32(); uint size = input.ReadUInt32(); var name = input.ReadCString (0x18); var entry = FormatCatalog.Instance.Create<Entry> (name); entry.Offset = offset; entry.Size = size; if (!entry.CheckPlacement (m_arc_length)) return null; m_dir.Add (entry); } return m_dir; } catch { return null; } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERLevel { /// <summary> /// A05Level111Child (editable child object).<br/> /// This is a generated base class of <see cref="A05Level111Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="A04Level11"/> collection. /// </remarks> [Serializable] public partial class A05Level111Child : BusinessBase<A05Level111Child> { #region State Fields [NotUndoable] private byte[] _rowVersion = new byte[] {}; [NotUndoable] [NonSerialized] internal int cMarentID1 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_Child_Name, "Level_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1 Child Name.</value> public string Level_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_Child_NameProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CMarentID1"/> property. /// </summary> public static readonly PropertyInfo<int> CMarentID1Property = RegisterProperty<int>(p => p.CMarentID1, "CMarent ID1"); /// <summary> /// Gets or sets the CMarent ID1. /// </summary> /// <value>The CMarent ID1.</value> public int CMarentID1 { get { return GetProperty(CMarentID1Property); } set { SetProperty(CMarentID1Property, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="A05Level111Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="A05Level111Child"/> object.</returns> internal static A05Level111Child NewA05Level111Child() { return DataPortal.CreateChild<A05Level111Child>(); } /// <summary> /// Factory method. Loads a <see cref="A05Level111Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="A05Level111Child"/> object.</returns> internal static A05Level111Child GetA05Level111Child(SafeDataReader dr) { A05Level111Child obj = new A05Level111Child(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="A05Level111Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private A05Level111Child() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="A05Level111Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="A05Level111Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_Child_Name")); LoadProperty(CMarentID1Property, dr.GetInt32("CMarentID1")); _rowVersion = (dr.GetValue("RowVersion")) as byte[]; cMarentID1 = dr.GetInt32("CMarentID1"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="A05Level111Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(A04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddA05Level111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; } } } /// <summary> /// Updates in the database all changes made to the <see cref="A05Level111Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(A04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateA05Level111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@CMarentID1", ReadProperty(CMarentID1Property)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RowVersion", _rowVersion).DbType = DbType.Binary; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; } } } /// <summary> /// Self deletes the <see cref="A05Level111Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(A04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteA05Level111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// *********************************************************************** // Copyright (c) 2008-2015 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// TestCaseAttribute is used to mark parameterized test cases /// and provide them with their arguments. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited=false)] public class TestCaseAttribute : NUnitAttribute, ITestBuilder, ITestCaseData, IImplyFixture { #region Constructors /// <summary> /// Construct a TestCaseAttribute with a list of arguments. /// This constructor is not CLS-Compliant /// </summary> /// <param name="arguments"></param> public TestCaseAttribute(params object[] arguments) { RunState = RunState.Runnable; if (arguments == null) Arguments = new object[] { null }; else Arguments = arguments; Properties = new PropertyBag(); } /// <summary> /// Construct a TestCaseAttribute with a single argument /// </summary> /// <param name="arg"></param> public TestCaseAttribute(object arg) { RunState = RunState.Runnable; Arguments = new object[] { arg }; Properties = new PropertyBag(); } /// <summary> /// Construct a TestCaseAttribute with a two arguments /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> public TestCaseAttribute(object arg1, object arg2) { RunState = RunState.Runnable; Arguments = new object[] { arg1, arg2 }; Properties = new PropertyBag(); } /// <summary> /// Construct a TestCaseAttribute with a three arguments /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> /// <param name="arg3"></param> public TestCaseAttribute(object arg1, object arg2, object arg3) { RunState = RunState.Runnable; Arguments = new object[] { arg1, arg2, arg3 }; Properties = new PropertyBag(); } #endregion #region ITestData Members /// <summary> /// Gets or sets the name of the test. /// </summary> /// <value>The name of the test.</value> public string TestName { get; set; } /// <summary> /// Gets or sets the RunState of this test case. /// </summary> public RunState RunState { get; private set; } /// <summary> /// Gets the list of arguments to a test case /// </summary> public object[] Arguments { get; private set; } /// <summary> /// Gets the properties of the test case /// </summary> public IPropertyBag Properties { get; private set; } #endregion #region ITestCaseData Members /// <summary> /// Gets or sets the expected result. /// </summary> /// <value>The result.</value> public object ExpectedResult { get { return _expectedResult; } set { _expectedResult = value; HasExpectedResult = true; } } private object _expectedResult; /// <summary> /// Returns true if the expected result has been set /// </summary> public bool HasExpectedResult { get; private set; } #endregion #region Other Properties /// <summary> /// Gets or sets the description. /// </summary> /// <value>The description.</value> public string Description { get { return Properties.Get(PropertyNames.Description) as string; } set { Properties.Set(PropertyNames.Description, value); } } /// <summary> /// The author of this test /// </summary> public string Author { get { return Properties.Get(PropertyNames.Author) as string; } set { Properties.Set(PropertyNames.Author, value); } } /// <summary> /// The type that this test is testing /// </summary> public Type TestOf { get { return _testOf; } set { _testOf = value; Properties.Set(PropertyNames.TestOf, value.FullName); } } private Type _testOf; /// <summary> /// Gets or sets the reason for ignoring the test /// </summary> public string Ignore { get { return IgnoreReason; } set { IgnoreReason = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestCaseAttribute"/> is explicit. /// </summary> /// <value> /// <c>true</c> if explicit; otherwise, <c>false</c>. /// </value> public bool Explicit { get { return RunState == RunState.Explicit; } set { RunState = value ? RunState.Explicit : RunState.Runnable; } } /// <summary> /// Gets or sets the reason for not running the test. /// </summary> /// <value>The reason.</value> public string Reason { get { return Properties.Get(PropertyNames.SkipReason) as string; } set { Properties.Set(PropertyNames.SkipReason, value); } } /// <summary> /// Gets or sets the ignore reason. When set to a non-null /// non-empty value, the test is marked as ignored. /// </summary> /// <value>The ignore reason.</value> public string IgnoreReason { get { return Reason; } set { RunState = RunState.Ignored; Reason = value; } } #if !NETSTANDARD1_3 && !NETSTANDARD1_6 /// <summary> /// Comma-delimited list of platforms to run the test for /// </summary> public string IncludePlatform { get; set; } /// <summary> /// Comma-delimited list of platforms to not run the test for /// </summary> public string ExcludePlatform { get; set; } #endif /// <summary> /// Gets and sets the category for this test case. /// May be a comma-separated list of categories. /// </summary> public string Category { get { return Properties.Get(PropertyNames.Category) as string; } set { foreach (string cat in value.Split(new char[] { ',' }) ) Properties.Add(PropertyNames.Category, cat); } } #endregion #region Helper Methods private TestCaseParameters GetParametersForTestCase(IMethodInfo method) { TestCaseParameters parms; try { IParameterInfo[] parameters = method.GetParameters(); int argsNeeded = parameters.Length; int argsProvided = Arguments.Length; parms = new TestCaseParameters(this); // Special handling for params arguments if (argsNeeded > 0 && argsProvided >= argsNeeded - 1) { IParameterInfo lastParameter = parameters[argsNeeded - 1]; Type lastParameterType = lastParameter.ParameterType; Type elementType = lastParameterType.GetElementType(); if (lastParameterType.IsArray && lastParameter.IsDefined<ParamArrayAttribute>(false)) { if (argsProvided == argsNeeded) { Type lastArgumentType = parms.Arguments[argsProvided - 1].GetType(); if (!lastParameterType.GetTypeInfo().IsAssignableFrom(lastArgumentType.GetTypeInfo())) { Array array = Array.CreateInstance(elementType, 1); array.SetValue(parms.Arguments[argsProvided - 1], 0); parms.Arguments[argsProvided - 1] = array; } } else { object[] newArglist = new object[argsNeeded]; for (int i = 0; i < argsNeeded && i < argsProvided; i++) newArglist[i] = parms.Arguments[i]; int length = argsProvided - argsNeeded + 1; Array array = Array.CreateInstance(elementType, length); for (int i = 0; i < length; i++) array.SetValue(parms.Arguments[argsNeeded + i - 1], i); newArglist[argsNeeded - 1] = array; parms.Arguments = newArglist; argsProvided = argsNeeded; } } } //Special handling for optional parameters if (parms.Arguments.Length < argsNeeded) { object[] newArgList = new object[parameters.Length]; Array.Copy(parms.Arguments, newArgList, parms.Arguments.Length); //Fill with Type.Missing for remaining required parameters where optional for (var i = parms.Arguments.Length; i < parameters.Length; i++) { if (parameters[i].IsOptional) newArgList[i] = Type.Missing; else { if (i < parms.Arguments.Length) newArgList[i] = parms.Arguments[i]; else throw new TargetParameterCountException(string.Format( "Method requires {0} arguments but TestCaseAttribute only supplied {1}", argsNeeded, argsProvided)); } } parms.Arguments = newArgList; } //if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) // parms.Arguments = new object[]{parms.Arguments}; // Special handling when sole argument is an object[] if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) { if (argsProvided > 1 || argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[])) { parms.Arguments = new object[] { parms.Arguments }; } } if (argsProvided == argsNeeded) PerformSpecialConversions(parms.Arguments, parameters); } catch (Exception ex) { parms = new TestCaseParameters(ex); } return parms; } /// <summary> /// Performs several special conversions allowed by NUnit in order to /// permit arguments with types that cannot be used in the constructor /// of an Attribute such as TestCaseAttribute or to simplify their use. /// </summary> /// <param name="arglist">The arguments to be converted</param> /// <param name="parameters">The ParameterInfo array for the method</param> private static void PerformSpecialConversions(object[] arglist, IParameterInfo[] parameters) { for (int i = 0; i < arglist.Length; i++) { object arg = arglist[i]; Type targetType = parameters[i].ParameterType; if (arg == null) continue; if (targetType.IsAssignableFrom(arg.GetType())) continue; #if !NETSTANDARD1_3 && !NETSTANDARD1_6 if (arg is DBNull) { arglist[i] = null; continue; } #endif bool convert = false; if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte) || targetType == typeof(long?) || targetType == typeof(short?) || targetType == typeof(byte?) || targetType == typeof(sbyte?) || targetType == typeof(double?)) { convert = arg is int; } else if (targetType == typeof(decimal) || targetType == typeof(decimal?)) { convert = arg is double || arg is string || arg is int; } else if (targetType == typeof(DateTime) || targetType == typeof(DateTime?)) { convert = arg is string; } if (convert) { Type convertTo = targetType.GetTypeInfo().IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>) ? targetType.GetGenericArguments()[0] : targetType; arglist[i] = Convert.ChangeType(arg, convertTo, System.Globalization.CultureInfo.InvariantCulture); } else // Convert.ChangeType doesn't work for TimeSpan from string if ((targetType == typeof(TimeSpan) || targetType == typeof(TimeSpan?)) && arg is string) { arglist[i] = TimeSpan.Parse((string)arg); } } } #endregion #region ITestBuilder Members /// <summary> /// Construct one or more TestMethods from a given MethodInfo, /// using available parameter data. /// </summary> /// <param name="method">The MethodInfo for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> /// <returns>One or more TestMethods</returns> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite) { TestMethod test = new NUnitTestCaseBuilder().BuildTestMethod(method, suite, GetParametersForTestCase(method)); #if !NETSTANDARD1_3 && !NETSTANDARD1_6 if (test.RunState != RunState.NotRunnable && test.RunState != RunState.Ignored) { PlatformHelper platformHelper = new PlatformHelper(); if (!platformHelper.IsPlatformSupported(this)) { test.RunState = RunState.Skipped; test.Properties.Add(PropertyNames.SkipReason, platformHelper.Reason); } } #endif yield return test; } #endregion } }
using Htc.Vita.Core.Config; using Htc.Vita.Core.Log; using Xunit; namespace Htc.Vita.Core.Tests { public static class ConfigTest { private static bool IsPredefinedGlobalDataReady => false; [Fact] public static void Default_0_GetInstance() { var config = Config.Config.GetInstance(); Assert.NotNull(config); } [Fact] public static void Default_1_Get() { var config = Config.Config.GetInstance(); Assert.NotNull(config); var value = config.Get("intKey"); Assert.Equal("1", value); } [Fact] public static void Default_1_Get_WithDefault() { var config = Config.Config.GetInstance(); Assert.NotNull(config); var value = config.Get("intKey2", "2"); Assert.Equal("2", value); } [Fact] public static void Default_2_GetBool() { var config = Config.Config.GetInstance(); Assert.NotNull(config); var value = config.Get("boolKey"); Assert.Equal("true", value); var value2 = config.GetBool("boolKey"); Assert.True(value2); } [Fact] public static void Default_2_GetBool_WithDefault() { var config = Config.Config.GetInstance(); Assert.NotNull(config); var value = config.Get("boolKey2"); Assert.Null(value); var value2 = config.GetBool("boolKey2"); Assert.False(value2); var value3 = config.GetBool("boolKey2", true); Assert.True(value3); } [Fact] public static void Default_3_GetDouble() { var config = Config.Config.GetInstance(); Assert.NotNull(config); var value = config.Get("doubleKey"); Assert.Equal("3.3", value); var value2 = config.GetDouble("doubleKey"); Assert.Equal(3.3D, value2); } [Fact] public static void Default_3_GetDouble_WithDefault() { var config = Config.Config.GetInstance(); Assert.NotNull(config); var value = config.Get("doubleKey2"); Assert.Null(value); var value2 = config.GetDouble("doubleKey2"); Assert.Equal(0.0D, value2); var value3 = config.GetDouble("doubleKey2", 13.3D); Assert.Equal(13.3D, value3); } [Fact] public static void Default_4_GetInt() { var config = Config.Config.GetInstance(); Assert.NotNull(config); var value = config.Get("intKey"); Assert.Equal("1", value); var value2 = config.GetInt("intKey"); Assert.Equal(1, value2); } [Fact] public static void Default_4_GetInt_WithDefault() { var config = Config.Config.GetInstance(); Assert.NotNull(config); var value = config.Get("intKey2"); Assert.Null(value); var value2 = config.GetInt("intKey2"); Assert.Equal(0, value2); var value3 = config.GetInt("intKey2", 10); Assert.Equal(10, value3); } [Fact] public static void Default_5_GetLong() { var config = Config.Config.GetInstance(); Assert.NotNull(config); var value = config.Get("longKey"); Assert.Equal("100000000000", value); var value2 = config.GetLong("longKey"); Assert.Equal(100000000000L, value2); } [Fact] public static void Default_5_GetLong_WithDefault() { var config = Config.Config.GetInstance(); Assert.NotNull(config); var value = config.Get("longKey2"); Assert.Null(value); var value2 = config.GetLong("longKey2"); Assert.Equal(0L, value2); var value3 = config.GetLong("longKey2", 200000000000L); Assert.Equal(200000000000L, value3); } [Fact] public static void AppSettings_0_GetInstance() { var config = Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); } [Fact] public static void AppSettings_1_Get() { var config = Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); var value = config.Get("intKey"); Assert.Equal("1", value); } [Fact] public static void AppSettings_1_Get_WithDefault() { var config = Core.Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); var value = config.Get("intKey2", "2"); Assert.Equal("2", value); } [Fact] public static void AppSettings_2_GetBool() { var config = Core.Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); var value = config.Get("boolKey"); Assert.Equal("true", value); var value2 = config.GetBool("boolKey"); Assert.True(value2); } [Fact] public static void AppSettings_2_GetBool_WithDefault() { var config = Core.Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); var value = config.Get("boolKey2"); Assert.Null(value); var value2 = config.GetBool("boolKey2"); Assert.False(value2); var value3 = config.GetBool("boolKey2", true); Assert.True(value3); } [Fact] public static void AppSettings_3_GetDouble() { var config = Core.Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); var value = config.Get("doubleKey"); Assert.Equal("3.3", value); var value2 = config.GetDouble("doubleKey"); Assert.Equal(3.3D, value2); } [Fact] public static void AppSettings_3_GetDouble_WithDefault() { var config = Core.Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); var value = config.Get("doubleKey2"); Assert.Null(value); var value2 = config.GetDouble("doubleKey2"); Assert.Equal(0.0D, value2); var value3 = config.GetDouble("doubleKey2", 13.3D); Assert.Equal(13.3D, value3); } [Fact] public static void AppSettings_4_GetInt() { var config = Core.Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); var value = config.Get("intKey"); Assert.Equal("1", value); var value2 = config.GetInt("intKey"); Assert.Equal(1, value2); } [Fact] public static void AppSettings_4_GetInt_WithDefault() { var config = Core.Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); var value = config.Get("intKey2"); Assert.Null(value); var value2 = config.GetInt("intKey2"); Assert.Equal(0, value2); var value3 = config.GetInt("intKey2", 10); Assert.Equal(10, value3); } [Fact] public static void AppSettings_5_GetLong() { var config = Core.Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); var value = config.Get("longKey"); Assert.Equal("100000000000", value); var value2 = config.GetLong("longKey"); Assert.Equal(100000000000L, value2); } [Fact] public static void AppSettings_5_GetLong_WithDefault() { var config = Core.Config.Config.GetInstance<AppSettingsConfig>(); Assert.NotNull(config); var value = config.Get("longKey2"); Assert.Null(value); var value2 = config.GetLong("longKey2"); Assert.Equal(0L, value2); var value3 = config.GetLong("longKey2", 200000000000L); Assert.Equal(200000000000L, value3); } [Fact] public static void Registry_0_GetInstance() { var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); } [Fact] public static void Registry_1_Get() { if (!IsPredefinedGlobalDataReady) { Logger.GetInstance(typeof(ConfigTest)).Warn("This API should be invoked with predefined global data"); return; } var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); var value = config.Get("intKey"); Assert.Equal("1", value); } [Fact] public static void Registry_1_Get_WithDefault() { var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); var value = config.Get("intKey2", "2"); Assert.Equal("2", value); } [Fact] public static void Registry_2_GetBool() { if (!IsPredefinedGlobalDataReady) { Logger.GetInstance(typeof(ConfigTest)).Warn("This API should be invoked with predefined global data"); return; } var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); var value = config.Get("boolKey"); Assert.Equal("true", value); var value2 = config.GetBool("boolKey"); Assert.True(value2); } [Fact] public static void Registry_2_GetBool_WithDefault() { var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); var value = config.Get("boolKey2"); Assert.Null(value); var value2 = config.GetBool("boolKey2"); Assert.False(value2); var value3 = config.GetBool("boolKey2", true); Assert.True(value3); } [Fact] public static void Registry_3_GetDouble() { if (!IsPredefinedGlobalDataReady) { Logger.GetInstance(typeof(ConfigTest)).Warn("This API should be invoked with predefined global data"); return; } var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); var value = config.Get("doubleKey"); Assert.Equal("3.3", value); var value2 = config.GetDouble("doubleKey"); Assert.Equal(3.3D, value2); } [Fact] public static void Registry_3_GetDouble_WithDefault() { var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); var value = config.Get("doubleKey2"); Assert.Null(value); var value2 = config.GetDouble("doubleKey2"); Assert.Equal(0.0D, value2); var value3 = config.GetDouble("doubleKey2", 13.3D); Assert.Equal(13.3D, value3); } [Fact] public static void Registry_4_GetInt() { if (!IsPredefinedGlobalDataReady) { Logger.GetInstance(typeof(ConfigTest)).Warn("This API should be invoked with predefined global data"); return; } var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); var value = config.Get("intKey"); Assert.Equal("1", value); var value2 = config.GetInt("intKey"); Assert.Equal(1, value2); } [Fact] public static void Registry_4_GetInt_WithDefault() { var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); var value = config.Get("intKey2"); Assert.Null(value); var value2 = config.GetInt("intKey2"); Assert.Equal(0, value2); var value3 = config.GetInt("intKey2", 10); Assert.Equal(10, value3); } [Fact] public static void Registry_5_GetLong() { if (!IsPredefinedGlobalDataReady) { Logger.GetInstance(typeof(ConfigTest)).Warn("This API should be invoked with predefined global data"); return; } var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); var value = config.Get("longKey"); Assert.Equal("100000000000", value); var value2 = config.GetLong("longKey"); Assert.Equal(100000000000L, value2); } [Fact] public static void Registry_5_GetLong_WithDefault() { var config = Core.Config.Config.GetInstance<RegistryConfig>(); Assert.NotNull(config); var value = config.Get("longKey2"); Assert.Null(value); var value2 = config.GetLong("longKey2"); Assert.Equal(0L, value2); var value3 = config.GetLong("longKey2", 200000000000L); Assert.Equal(200000000000L, value3); } } }
/* * 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 ZooKeeperNet.Tests { using System; using NUnit.Framework; using Org.Apache.Zookeeper.Data; using System.Threading; [TestFixture] public class StatTests : AbstractZooKeeperTests { private ZooKeeper zk; [SetUp] public void SetUp() { zk = CreateClient(); } [TearDown] public void TearDown() { zk.Dispose(); } /** * Create a new Stat, fill in dummy values trying to catch Assert.failure * to copy in client or server code. * * @return a new stat with dummy values */ private Stat newStat() { Stat stat = new Stat(); stat.Aversion = 100; stat.Ctime = 100; stat.Cversion = 100; stat.Czxid = 100; stat.DataLength = 100; stat.EphemeralOwner = 100; stat.Mtime = 100; stat.Mzxid = 100; stat.NumChildren = 100; stat.Pzxid = 100; stat.Version = 100; return stat; } [Test] public void testBasic() { string name = "/" + Guid.NewGuid() + "foo"; zk.Create(name, name.GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent); Stat stat; stat = newStat(); zk.GetData(name, false, stat); Assert.AreEqual(stat.Czxid, stat.Mzxid); Assert.AreEqual(stat.Czxid, stat.Pzxid); Assert.AreEqual(stat.Ctime, stat.Mtime); Assert.AreEqual(0, stat.Cversion); Assert.AreEqual(0, stat.Version); Assert.AreEqual(0, stat.Aversion); Assert.AreEqual(0, stat.EphemeralOwner); Assert.AreEqual(name.Length, stat.DataLength); Assert.AreEqual(0, stat.NumChildren); } [Test] public void testChild() { string name = "/" + Guid.NewGuid() + "foo"; zk.Create(name, name.GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent); string childname = name + "/bar"; zk.Create(childname, childname.GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Ephemeral); Stat stat; stat = newStat(); zk.GetData(name, false, stat); Assert.AreEqual(stat.Czxid, stat.Mzxid); Assert.AreEqual(stat.Czxid + 1, stat.Pzxid); Assert.AreEqual(stat.Ctime, stat.Mtime); Assert.AreEqual(1, stat.Cversion); Assert.AreEqual(0, stat.Version); Assert.AreEqual(0, stat.Aversion); Assert.AreEqual(0, stat.EphemeralOwner); Assert.AreEqual(name.Length, stat.DataLength); Assert.AreEqual(1, stat.NumChildren); stat = newStat(); zk.GetData(childname, false, stat); Assert.AreEqual(stat.Czxid, stat.Mzxid); Assert.AreEqual(stat.Czxid, stat.Pzxid); Assert.AreEqual(stat.Ctime, stat.Mtime); Assert.AreEqual(0, stat.Cversion); Assert.AreEqual(0, stat.Version); Assert.AreEqual(0, stat.Aversion); Assert.AreEqual(zk.SessionId, stat.EphemeralOwner); Assert.AreEqual(childname.Length, stat.DataLength); Assert.AreEqual(0, stat.NumChildren); } [Test] public void testChildren() { string name = "/" + Guid.NewGuid() + "foo"; zk.Create(name, name.GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent); for (int i = 0; i < 10; i++) { string childname = name + "/bar" + i; zk.Create(childname, childname.GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EphemeralSequential); Stat stat; stat = newStat(); zk.GetData(name, false, stat); Assert.AreEqual(stat.Czxid, stat.Mzxid); Assert.AreEqual(stat.Czxid + i + 1, stat.Pzxid); Assert.AreEqual(stat.Ctime, stat.Mtime); Assert.AreEqual(i + 1, stat.Cversion); Assert.AreEqual(0, stat.Version); Assert.AreEqual(0, stat.Aversion); Assert.AreEqual(0, stat.EphemeralOwner); Assert.AreEqual(name.Length, stat.DataLength); Assert.AreEqual(i + 1, stat.NumChildren); } } [Test] public void testDataSizeChange() { string name = "/" + Guid.NewGuid() + "foo"; zk.Create(name, name.GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent); Stat stat; stat = newStat(); zk.GetData(name, false, stat); Assert.AreEqual(stat.Czxid, stat.Mzxid); Assert.AreEqual(stat.Czxid, stat.Pzxid); Assert.AreEqual(stat.Ctime, stat.Mtime); Assert.AreEqual(0, stat.Cversion); Assert.AreEqual(0, stat.Version); Assert.AreEqual(0, stat.Aversion); Assert.AreEqual(0, stat.EphemeralOwner); Assert.AreEqual(name.Length, stat.DataLength); Assert.AreEqual(0, stat.NumChildren); zk.SetData(name, (name + name).GetBytes(), -1); stat = newStat(); zk.GetData(name, false, stat); Assert.AreNotSame(stat.Czxid, stat.Mzxid); Assert.AreEqual(stat.Czxid, stat.Pzxid); Assert.AreNotSame(stat.Ctime, stat.Mtime); Assert.AreEqual(0, stat.Cversion); Assert.AreEqual(1, stat.Version); Assert.AreEqual(0, stat.Aversion); Assert.AreEqual(0, stat.EphemeralOwner); Assert.AreEqual(name.Length * 2, stat.DataLength); Assert.AreEqual(0, stat.NumChildren); } [Test] public void testDeleteAllNodeExceptPraweda() { DeleteChild(zk, "/"); } private void DeleteChild(ZooKeeper zk, string path) { if (!string.IsNullOrEmpty(path) && !path.Contains("praweda") && !path.Contains("zookeeper")) { var lstChild = zk.GetChildren(path, false); foreach (var child in lstChild) { if (path != "/") DeleteChild(zk, path + "/" + child); else DeleteChild(zk, "/" + child); } if (path != "/") { try { zk.Delete(path, -1); } catch { } } } } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using ESRI.ArcLogistics.DomainObjects; using ESRI.ArcLogistics.Routing; using System.ServiceModel; namespace ESRI.ArcLogistics { /// <summary> /// Class contains helper method for application simplifying routine. /// </summary> internal sealed class CommonHelpers { #region Public definitions /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public const string XML_SETTINGS_INDENT_CHARS = " "; // // custom serialization conts (into the project database). // /// <summary> /// Storage culture name. /// </summary> public const string STORAGE_CULTURE = "en-US"; /// <summary> /// Application separator. /// </summary> public const char SEPARATOR = ','; /// Old version of separator (NOTE: is obsolete - now need use SEPARATOR). /// </summary> public const char SEPARATOR_OLD = ';'; /// <summary> /// Application separator for data with ',' (double or composite). /// </summary> public const string SEPARATOR_ALIAS = "&comma"; /// <summary> /// Part separator (used wiht versionen info). /// </summary> public const char SEPARATOR_OF_PART = '\\'; #endregion // Public definitions #region Public helpers /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Gets solver settings. /// </summary> /// <param name="solver">The reference to the VRP solver.</param> /// <returns>Solver settings or NULL.</returns> internal static SolverSettings GetSolverSettings(IVrpSolver solver) { Debug.Assert(solver != null); SolverSettings settings = null; try { settings = solver.SolverSettings; } catch (Exception e) { if (e is InvalidOperationException || e is AuthenticationException || e is CommunicationException || e is FaultException) { Logger.Info(e); } else { throw; // exception } } return settings; } /// <summary> /// Get list of assembly file in directory. /// </summary> /// <param name="directoryPath">Directory full path</param> /// <returns>List of assembly file in directory</returns> /// <remarks>Not supported subfolder.</remarks> public static ICollection<string> GetAssembliesFiles(string directoryPath) { Debug.Assert(!string.IsNullOrEmpty(directoryPath)); List<string> list = new List<string>(); if (!Directory.Exists(directoryPath)) return list; try { //do through all the files in the plugin directory foreach (string filePath in Directory.GetFiles(directoryPath)) { FileInfo file = new FileInfo(filePath); if (!file.Extension.Equals(".dll")) continue; // NOTE: preliminary check, must be ".dll" try { Assembly pluginAssembly = Assembly.LoadFrom(filePath); list.Add(filePath); } catch { } } } catch (Exception e) { Logger.Error(e); } return list.AsReadOnly(); } /// <summary> /// Normalizes text. /// </summary> /// <param name="text">Input text.</param> /// <returns>Text in normalized state.</returns> public static string NormalizeText(string text) { Debug.Assert(!string.IsNullOrEmpty(text.Trim())); string normText = text.Trim().ToLower(); return normText.Replace(SPACE, ""); // remove spaces } /// <summary> /// Checks is string value present in list. /// </summary> /// <param name="value">Value to cheking.</param> /// <param name="values">Value list.</param> /// <returns>TRUE if input value present in supported list.</returns> public static bool IsValuePresentInList(string value, string[] values) { Debug.Assert(!string.IsNullOrEmpty(value.Trim())); bool result = false; if (null != values) { for (int index = 0; index < values.Length; ++index) { string curValue = NormalizeText(values[index]); if (value == curValue) { result = true; break; // NOTE: result founded } } } return result; } /// <summary> /// Sorts Stop objects respecting sequence number. /// </summary> /// <param name="stops">Stops to sorting.</param> public static void SortBySequence(List<Stop> stops) { stops.Sort(delegate(Stop s1, Stop s2) { return s1.SequenceNumber.CompareTo(s2.SequenceNumber); }); } /// <summary> /// Gets route stops sorted by sequence number. /// </summary> /// <param name="route">Route.</param> /// <returns>Route stops sorted by sequence number.</returns> public static IList<Stop> GetSortedStops(Route route) { var routeStops = new List<Stop>(route.Stops); SortBySequence(routeStops); return routeStops; } #endregion // Public helpers /// <summary> /// Symbol SPACE (as string). /// </summary> private const string SPACE = " "; } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; namespace TMPro { [DisallowMultipleComponent] [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(MeshFilter))] [AddComponentMenu("Mesh/TextMeshPro - Text")] [ExecuteAlways] public partial class TextMeshPro : TMP_Text, ILayoutElement { // Public Properties and Serializable Properties /// <summary> /// Sets the Renderer's sorting Layer ID /// </summary> public int sortingLayerID { get { return m_renderer.sortingLayerID; } set { m_renderer.sortingLayerID = value; } } /// <summary> /// Sets the Renderer's sorting order within the assigned layer. /// </summary> public int sortingOrder { get { return m_renderer.sortingOrder; } set { m_renderer.sortingOrder = value; } } /// <summary> /// Determines if the size of the text container will be adjusted to fit the text object when it is first created. /// </summary> public override bool autoSizeTextContainer { get { return m_autoSizeTextContainer; } set { if (m_autoSizeTextContainer == value) return; m_autoSizeTextContainer = value; if (m_autoSizeTextContainer) { TMP_UpdateManager.RegisterTextElementForLayoutRebuild(this); SetLayoutDirty(); } } } /// <summary> /// Returns a reference to the Text Container /// </summary> [Obsolete("The TextContainer is now obsolete. Use the RectTransform instead.")] public TextContainer textContainer { get { return null; } } /// <summary> /// Returns a reference to the Transform /// </summary> public new Transform transform { get { if (m_transform == null) m_transform = GetComponent<Transform>(); return m_transform; } } #pragma warning disable 0108 /// <summary> /// Returns the rendered assigned to the text object. /// </summary> public Renderer renderer { get { if (m_renderer == null) m_renderer = GetComponent<Renderer>(); return m_renderer; } } /// <summary> /// Returns the mesh assigned to the text object. /// </summary> public override Mesh mesh { get { if (m_mesh == null) { m_mesh = new Mesh(); m_mesh.hideFlags = HideFlags.HideAndDontSave; this.meshFilter.mesh = m_mesh; } return m_mesh; } } /// <summary> /// Returns the Mesh Filter of the text object. /// </summary> public MeshFilter meshFilter { get { if (m_meshFilter == null) m_meshFilter = GetComponent<MeshFilter>(); return m_meshFilter; } } // MASKING RELATED PROPERTIES /// <summary> /// Sets the mask type /// </summary> public MaskingTypes maskType { get { return m_maskType; } set { m_maskType = value; SetMask(m_maskType); } } /// <summary> /// Function used to set the mask type and coordinates in World Space /// </summary> /// <param name="type"></param> /// <param name="maskCoords"></param> public void SetMask(MaskingTypes type, Vector4 maskCoords) { SetMask(type); SetMaskCoordinates(maskCoords); } /// <summary> /// Function used to set the mask type, coordinates and softness /// </summary> /// <param name="type"></param> /// <param name="maskCoords"></param> /// <param name="softnessX"></param> /// <param name="softnessY"></param> public void SetMask(MaskingTypes type, Vector4 maskCoords, float softnessX, float softnessY) { SetMask(type); SetMaskCoordinates(maskCoords, softnessX, softnessY); } /// <summary> /// Schedule rebuilding of the text geometry. /// </summary> public override void SetVerticesDirty() { //Debug.Log("SetVerticesDirty()"); if (m_verticesAlreadyDirty || this == null || !this.IsActive()) return; TMP_UpdateManager.RegisterTextElementForGraphicRebuild(this); m_verticesAlreadyDirty = true; } /// <summary> /// /// </summary> public override void SetLayoutDirty() { m_isPreferredWidthDirty = true; m_isPreferredHeightDirty = true; if (m_layoutAlreadyDirty || this == null || !this.IsActive()) return; //TMP_UpdateManager.RegisterTextElementForLayoutRebuild(this); m_layoutAlreadyDirty = true; //LayoutRebuilder.MarkLayoutForRebuild(this.rectTransform); m_isLayoutDirty = true; } /// <summary> /// Schedule updating of the material used by the text object. /// </summary> public override void SetMaterialDirty() { //Debug.Log("SetMaterialDirty()"); //if (!this.IsActive()) // return; //m_isMaterialDirty = true; UpdateMaterial(); //TMP_UpdateManager.RegisterTextElementForGraphicRebuild(this); } /// <summary> /// /// </summary> public override void SetAllDirty() { m_isInputParsingRequired = true; SetLayoutDirty(); SetVerticesDirty(); SetMaterialDirty(); } /// <summary> /// /// </summary> /// <param name="update"></param> public override void Rebuild(CanvasUpdate update) { if (this == null) return; if (update == CanvasUpdate.Prelayout) { if (m_autoSizeTextContainer) { m_rectTransform.sizeDelta = GetPreferredValues(Mathf.Infinity, Mathf.Infinity); } } else if (update == CanvasUpdate.PreRender) { this.OnPreRenderObject(); m_verticesAlreadyDirty = false; m_layoutAlreadyDirty = false; if (!m_isMaterialDirty) return; UpdateMaterial(); m_isMaterialDirty = false; } } /// <summary> /// /// </summary> protected override void UpdateMaterial() { //Debug.Log("*** UpdateMaterial() ***"); //if (!this.IsActive()) // return; if (m_sharedMaterial == null) return; if (m_renderer == null) m_renderer = this.renderer; // Only update the material if it has changed. if (m_renderer.sharedMaterial.GetInstanceID() != m_sharedMaterial.GetInstanceID()) m_renderer.sharedMaterial = m_sharedMaterial; } /// <summary> /// Function to be used to force recomputing of character padding when Shader / Material properties have been changed via script. /// </summary> public override void UpdateMeshPadding() { m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_enableExtraPadding, m_isUsingBold); m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial); m_havePropertiesChanged = true; checkPaddingRequired = false; // Return if text object is not awake yet. if (m_textInfo == null) return; // Update sub text objects for (int i = 1; i < m_textInfo.materialCount; i++) m_subTextObjects[i].UpdateMeshPadding(m_enableExtraPadding, m_isUsingBold); } /// <summary> /// Function to force regeneration of the mesh before its normal process time. This is useful when changes to the text object properties need to be applied immediately. /// </summary> public override void ForceMeshUpdate() { //Debug.Log("ForceMeshUpdate() called."); m_havePropertiesChanged = true; OnPreRenderObject(); } /// <summary> /// Function to force regeneration of the mesh before its normal process time. This is useful when changes to the text object properties need to be applied immediately. /// </summary> /// <param name="ignoreInactive">If set to true, the text object will be regenerated regardless of is active state.</param> public override void ForceMeshUpdate(bool ignoreInactive) { m_havePropertiesChanged = true; m_ignoreActiveState = true; OnPreRenderObject(); } /// <summary> /// Function used to evaluate the length of a text string. /// </summary> /// <param name="text"></param> /// <returns></returns> public override TMP_TextInfo GetTextInfo(string text) { StringToCharArray(text, ref m_TextParsingBuffer); SetArraySizes(m_TextParsingBuffer); m_renderMode = TextRenderFlags.DontRender; ComputeMarginSize(); GenerateTextMesh(); m_renderMode = TextRenderFlags.Render; return this.textInfo; } /// <summary> /// Function to clear the geometry of the Primary and Sub Text objects. /// </summary> public override void ClearMesh(bool updateMesh) { if (m_textInfo.meshInfo[0].mesh == null) m_textInfo.meshInfo[0].mesh = m_mesh; m_textInfo.ClearMeshInfo(updateMesh); } /// <summary> /// Function to force the regeneration of the text object. /// </summary> /// <param name="flags"> Flags to control which portions of the geometry gets uploaded.</param> //public override void ForceMeshUpdate(TMP_VertexDataUpdateFlags flags) { } /// <summary> /// Function to update the geometry of the main and sub text objects. /// </summary> /// <param name="mesh"></param> /// <param name="index"></param> public override void UpdateGeometry(Mesh mesh, int index) { mesh.RecalculateBounds(); } /// <summary> /// Function to upload the updated vertex data and renderer. /// </summary> public override void UpdateVertexData(TMP_VertexDataUpdateFlags flags) { int materialCount = m_textInfo.materialCount; for (int i = 0; i < materialCount; i++) { Mesh mesh; if (i == 0) mesh = m_mesh; else { // Clear unused vertices // TODO: Causes issues when sorting geometry as last vertex data attribute get wiped out. //m_textInfo.meshInfo[i].ClearUnusedVertices(); mesh = m_subTextObjects[i].mesh; } //mesh.MarkDynamic(); if ((flags & TMP_VertexDataUpdateFlags.Vertices) == TMP_VertexDataUpdateFlags.Vertices) mesh.vertices = m_textInfo.meshInfo[i].vertices; if ((flags & TMP_VertexDataUpdateFlags.Uv0) == TMP_VertexDataUpdateFlags.Uv0) mesh.uv = m_textInfo.meshInfo[i].uvs0; if ((flags & TMP_VertexDataUpdateFlags.Uv2) == TMP_VertexDataUpdateFlags.Uv2) mesh.uv2 = m_textInfo.meshInfo[i].uvs2; //if ((flags & TMP_VertexDataUpdateFlags.Uv4) == TMP_VertexDataUpdateFlags.Uv4) // mesh.uv4 = m_textInfo.meshInfo[i].uvs4; if ((flags & TMP_VertexDataUpdateFlags.Colors32) == TMP_VertexDataUpdateFlags.Colors32) mesh.colors32 = m_textInfo.meshInfo[i].colors32; mesh.RecalculateBounds(); } } /// <summary> /// Function to upload the updated vertex data and renderer. /// </summary> public override void UpdateVertexData() { int materialCount = m_textInfo.materialCount; for (int i = 0; i < materialCount; i++) { Mesh mesh; if (i == 0) mesh = m_mesh; else { // Clear unused vertices m_textInfo.meshInfo[i].ClearUnusedVertices(); mesh = m_subTextObjects[i].mesh; } //mesh.MarkDynamic(); mesh.vertices = m_textInfo.meshInfo[i].vertices; mesh.uv = m_textInfo.meshInfo[i].uvs0; mesh.uv2 = m_textInfo.meshInfo[i].uvs2; //mesh.uv4 = m_textInfo.meshInfo[i].uvs4; mesh.colors32 = m_textInfo.meshInfo[i].colors32; mesh.RecalculateBounds(); } } public void UpdateFontAsset() { LoadFontAsset(); } private bool m_currentAutoSizeMode; public void CalculateLayoutInputHorizontal() { //Debug.Log("*** CalculateLayoutInputHorizontal() ***"); if (!this.gameObject.activeInHierarchy) return; //IsRectTransformDriven = true; m_currentAutoSizeMode = m_enableAutoSizing; if (m_isCalculateSizeRequired || m_rectTransform.hasChanged) { //Debug.Log("Calculating Layout Horizontal"); //m_LayoutPhase = AutoLayoutPhase.Horizontal; //m_isRebuildingLayout = true; m_minWidth = 0; m_flexibleWidth = 0; //m_renderMode = TextRenderFlags.GetPreferredSizes; // Set Text to not Render and exit early once we have new width values. if (m_enableAutoSizing) { m_fontSize = m_fontSizeMax; } // Set Margins to Infinity m_marginWidth = k_LargePositiveFloat; m_marginHeight = k_LargePositiveFloat; if (m_isInputParsingRequired || m_isTextTruncated) ParseInputText(); GenerateTextMesh(); m_renderMode = TextRenderFlags.Render; //m_preferredWidth = (int)m_preferredWidth + 1f; ComputeMarginSize(); //Debug.Log("Preferred Width: " + m_preferredWidth + " Margin Width: " + m_marginWidth + " Preferred Height: " + m_preferredHeight + " Margin Height: " + m_marginHeight + " Rendered Width: " + m_renderedWidth + " Height: " + m_renderedHeight + " RectTransform Width: " + m_rectTransform.rect); m_isLayoutDirty = true; } } public void CalculateLayoutInputVertical() { //Debug.Log("*** CalculateLayoutInputVertical() ***"); // Check if object is active if (!this.gameObject.activeInHierarchy) // || IsRectTransformDriven == false) return; //IsRectTransformDriven = true; if (m_isCalculateSizeRequired || m_rectTransform.hasChanged) { //Debug.Log("Calculating Layout InputVertical"); //m_LayoutPhase = AutoLayoutPhase.Vertical; //m_isRebuildingLayout = true; m_minHeight = 0; m_flexibleHeight = 0; //m_renderMode = TextRenderFlags.GetPreferredSizes; if (m_enableAutoSizing) { m_currentAutoSizeMode = true; m_enableAutoSizing = false; } m_marginHeight = k_LargePositiveFloat; GenerateTextMesh(); m_enableAutoSizing = m_currentAutoSizeMode; m_renderMode = TextRenderFlags.Render; //m_preferredHeight = (int)m_preferredHeight + 1f; ComputeMarginSize(); //Debug.Log("Preferred Height: " + m_preferredHeight + " Margin Height: " + m_marginHeight + " Preferred Width: " + m_preferredWidth + " Margin Width: " + m_marginWidth + " Rendered Width: " + m_renderedWidth + " Height: " + m_renderedHeight + " RectTransform Width: " + m_rectTransform.rect); m_isLayoutDirty = true; } m_isCalculateSizeRequired = false; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Australian Postcodes Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KAPDataSet : EduHubDataSet<KAP> { /// <inheritdoc /> public override string Name { get { return "KAP"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KAPDataSet(EduHubContext Context) : base(Context) { Index_KAPKEY = new Lazy<Dictionary<string, KAP>>(() => this.ToDictionary(i => i.KAPKEY)); Index_PLACE_NAME = new Lazy<NullDictionary<string, IReadOnlyList<KAP>>>(() => this.ToGroupedNullDictionary(i => i.PLACE_NAME)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KAP" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KAP" /> fields for each CSV column header</returns> internal override Action<KAP, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KAP, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KAPKEY": mapper[i] = (e, v) => e.KAPKEY = v; break; case "POSTCODE": mapper[i] = (e, v) => e.POSTCODE = v; break; case "PLACE_NAME": mapper[i] = (e, v) => e.PLACE_NAME = v; break; case "STATE": mapper[i] = (e, v) => e.STATE = v; break; case "DISCRIMINATOR": mapper[i] = (e, v) => e.DISCRIMINATOR = v; break; case "STREET_ADD": mapper[i] = (e, v) => e.STREET_ADD = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KAP" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KAP" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KAP" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KAP}"/> of entities</returns> internal override IEnumerable<KAP> ApplyDeltaEntities(IEnumerable<KAP> Entities, List<KAP> DeltaEntities) { HashSet<string> Index_KAPKEY = new HashSet<string>(DeltaEntities.Select(i => i.KAPKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KAPKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KAPKEY.Remove(entity.KAPKEY); if (entity.KAPKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, KAP>> Index_KAPKEY; private Lazy<NullDictionary<string, IReadOnlyList<KAP>>> Index_PLACE_NAME; #endregion #region Index Methods /// <summary> /// Find KAP by KAPKEY field /// </summary> /// <param name="KAPKEY">KAPKEY value used to find KAP</param> /// <returns>Related KAP entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KAP FindByKAPKEY(string KAPKEY) { return Index_KAPKEY.Value[KAPKEY]; } /// <summary> /// Attempt to find KAP by KAPKEY field /// </summary> /// <param name="KAPKEY">KAPKEY value used to find KAP</param> /// <param name="Value">Related KAP entity</param> /// <returns>True if the related KAP entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKAPKEY(string KAPKEY, out KAP Value) { return Index_KAPKEY.Value.TryGetValue(KAPKEY, out Value); } /// <summary> /// Attempt to find KAP by KAPKEY field /// </summary> /// <param name="KAPKEY">KAPKEY value used to find KAP</param> /// <returns>Related KAP entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KAP TryFindByKAPKEY(string KAPKEY) { KAP value; if (Index_KAPKEY.Value.TryGetValue(KAPKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find KAP by PLACE_NAME field /// </summary> /// <param name="PLACE_NAME">PLACE_NAME value used to find KAP</param> /// <returns>List of related KAP entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KAP> FindByPLACE_NAME(string PLACE_NAME) { return Index_PLACE_NAME.Value[PLACE_NAME]; } /// <summary> /// Attempt to find KAP by PLACE_NAME field /// </summary> /// <param name="PLACE_NAME">PLACE_NAME value used to find KAP</param> /// <param name="Value">List of related KAP entities</param> /// <returns>True if the list of related KAP entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByPLACE_NAME(string PLACE_NAME, out IReadOnlyList<KAP> Value) { return Index_PLACE_NAME.Value.TryGetValue(PLACE_NAME, out Value); } /// <summary> /// Attempt to find KAP by PLACE_NAME field /// </summary> /// <param name="PLACE_NAME">PLACE_NAME value used to find KAP</param> /// <returns>List of related KAP entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KAP> TryFindByPLACE_NAME(string PLACE_NAME) { IReadOnlyList<KAP> value; if (Index_PLACE_NAME.Value.TryGetValue(PLACE_NAME, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KAP table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KAP]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KAP]( [KAPKEY] varchar(34) NOT NULL, [POSTCODE] varchar(4) NULL, [PLACE_NAME] varchar(30) NULL, [STATE] varchar(3) NULL, [DISCRIMINATOR] varchar(30) NULL, [STREET_ADD] varchar(1) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KAP_Index_KAPKEY] PRIMARY KEY CLUSTERED ( [KAPKEY] ASC ) ); CREATE NONCLUSTERED INDEX [KAP_Index_PLACE_NAME] ON [dbo].[KAP] ( [PLACE_NAME] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KAP]') AND name = N'KAP_Index_PLACE_NAME') ALTER INDEX [KAP_Index_PLACE_NAME] ON [dbo].[KAP] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KAP]') AND name = N'KAP_Index_PLACE_NAME') ALTER INDEX [KAP_Index_PLACE_NAME] ON [dbo].[KAP] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KAP"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KAP"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KAP> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_KAPKEY = new List<string>(); foreach (var entity in Entities) { Index_KAPKEY.Add(entity.KAPKEY); } builder.AppendLine("DELETE [dbo].[KAP] WHERE"); // Index_KAPKEY builder.Append("[KAPKEY] IN ("); for (int index = 0; index < Index_KAPKEY.Count; index++) { if (index != 0) builder.Append(", "); // KAPKEY var parameterKAPKEY = $"@p{parameterIndex++}"; builder.Append(parameterKAPKEY); command.Parameters.Add(parameterKAPKEY, SqlDbType.VarChar, 34).Value = Index_KAPKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KAP data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KAP data set</returns> public override EduHubDataSetDataReader<KAP> GetDataSetDataReader() { return new KAPDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KAP data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KAP data set</returns> public override EduHubDataSetDataReader<KAP> GetDataSetDataReader(List<KAP> Entities) { return new KAPDataReader(new EduHubDataSetLoadedReader<KAP>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KAPDataReader : EduHubDataSetDataReader<KAP> { public KAPDataReader(IEduHubDataSetReader<KAP> Reader) : base (Reader) { } public override int FieldCount { get { return 9; } } public override object GetValue(int i) { switch (i) { case 0: // KAPKEY return Current.KAPKEY; case 1: // POSTCODE return Current.POSTCODE; case 2: // PLACE_NAME return Current.PLACE_NAME; case 3: // STATE return Current.STATE; case 4: // DISCRIMINATOR return Current.DISCRIMINATOR; case 5: // STREET_ADD return Current.STREET_ADD; case 6: // LW_DATE return Current.LW_DATE; case 7: // LW_TIME return Current.LW_TIME; case 8: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // POSTCODE return Current.POSTCODE == null; case 2: // PLACE_NAME return Current.PLACE_NAME == null; case 3: // STATE return Current.STATE == null; case 4: // DISCRIMINATOR return Current.DISCRIMINATOR == null; case 5: // STREET_ADD return Current.STREET_ADD == null; case 6: // LW_DATE return Current.LW_DATE == null; case 7: // LW_TIME return Current.LW_TIME == null; case 8: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KAPKEY return "KAPKEY"; case 1: // POSTCODE return "POSTCODE"; case 2: // PLACE_NAME return "PLACE_NAME"; case 3: // STATE return "STATE"; case 4: // DISCRIMINATOR return "DISCRIMINATOR"; case 5: // STREET_ADD return "STREET_ADD"; case 6: // LW_DATE return "LW_DATE"; case 7: // LW_TIME return "LW_TIME"; case 8: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KAPKEY": return 0; case "POSTCODE": return 1; case "PLACE_NAME": return 2; case "STATE": return 3; case "DISCRIMINATOR": return 4; case "STREET_ADD": return 5; case "LW_DATE": return 6; case "LW_TIME": return 7; case "LW_USER": return 8; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. 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. #endregion using System; using System.Collections.Generic; using Google.ProtocolBuffers.Descriptors; //Disable warning CS3010: CLS-compliant interfaces must have only CLS-compliant members #pragma warning disable 3010 namespace Google.ProtocolBuffers { public interface ICodedInputStream { /// <summary> /// Reads any message initialization data expected from the input stream /// </summary> /// <remarks> /// This is primarily used by text formats and unnecessary for protobuffers' own /// binary format. The API for MessageStart/End was added for consistent handling /// of output streams regardless of the actual writer implementation. /// </remarks> void ReadMessageStart(); /// <summary> /// Reads any message finalization data expected from the input stream /// </summary> /// <remarks> /// This is primarily used by text formats and unnecessary for protobuffers' own /// binary format. The API for MessageStart/End was added for consistent handling /// of output streams regardless of the actual writer implementation. /// </remarks> void ReadMessageEnd(); /// <summary> /// Attempt to read a field tag, returning false if we have reached the end /// of the input data. /// </summary> /// <remarks> /// <para> /// If fieldTag is non-zero and ReadTag returns true then the value in fieldName /// may or may not be populated. However, if fieldTag is zero and ReadTag returns /// true, then fieldName should be populated with a non-null field name. /// </para><para> /// In other words if ReadTag returns true then either fieldTag will be non-zero OR /// fieldName will be non-zero. In some cases both may be populated, however the /// builders will always prefer the fieldTag over fieldName. /// </para> /// </remarks> [CLSCompliant(false)] bool ReadTag(out uint fieldTag, out string fieldName); /// <summary> /// Read a double field from the stream. /// </summary> bool ReadDouble(ref double value); /// <summary> /// Read a float field from the stream. /// </summary> bool ReadFloat(ref float value); /// <summary> /// Read a uint64 field from the stream. /// </summary> [CLSCompliant(false)] bool ReadUInt64(ref ulong value); /// <summary> /// Read an int64 field from the stream. /// </summary> bool ReadInt64(ref long value); /// <summary> /// Read an int32 field from the stream. /// </summary> bool ReadInt32(ref int value); /// <summary> /// Read a fixed64 field from the stream. /// </summary> [CLSCompliant(false)] bool ReadFixed64(ref ulong value); /// <summary> /// Read a fixed32 field from the stream. /// </summary> [CLSCompliant(false)] bool ReadFixed32(ref uint value); /// <summary> /// Read a bool field from the stream. /// </summary> bool ReadBool(ref bool value); /// <summary> /// Reads a string field from the stream. /// </summary> bool ReadString(ref string value); /// <summary> /// Reads a group field value from the stream. /// </summary> void ReadGroup(int fieldNumber, IBuilderLite builder, ExtensionRegistry extensionRegistry); /// <summary> /// Reads a group field value from the stream and merges it into the given /// UnknownFieldSet. /// </summary> [Obsolete] void ReadUnknownGroup(int fieldNumber, IBuilderLite builder); /// <summary> /// Reads an embedded message field value from the stream. /// </summary> void ReadMessage(IBuilderLite builder, ExtensionRegistry extensionRegistry); /// <summary> /// Reads a bytes field value from the stream. /// </summary> bool ReadBytes(ref ByteString value); /// <summary> /// Reads a uint32 field value from the stream. /// </summary> [CLSCompliant(false)] bool ReadUInt32(ref uint value); /// <summary> /// Reads an enum field value from the stream. The caller is responsible /// for converting the numeric value to an actual enum. /// </summary> bool ReadEnum(ref IEnumLite value, out object unknown, IEnumLiteMap mapping); /// <summary> /// Reads an enum field value from the stream. If the enum is valid for type T, /// then the ref value is set and it returns true. Otherwise the unkown output /// value is set and this method returns false. /// </summary> [CLSCompliant(false)] bool ReadEnum<T>(ref T value, out object unknown) where T : struct, IComparable, IFormattable; /// <summary> /// Reads an sfixed32 field value from the stream. /// </summary> bool ReadSFixed32(ref int value); /// <summary> /// Reads an sfixed64 field value from the stream. /// </summary> bool ReadSFixed64(ref long value); /// <summary> /// Reads an sint32 field value from the stream. /// </summary> bool ReadSInt32(ref int value); /// <summary> /// Reads an sint64 field value from the stream. /// </summary> bool ReadSInt64(ref long value); /// <summary> /// Reads an array of primitive values into the list, if the wire-type of fieldTag is length-prefixed and the /// type is numeric, it will read a packed array. /// </summary> [CLSCompliant(false)] void ReadPrimitiveArray(FieldType fieldType, uint fieldTag, string fieldName, ICollection<object> list); /// <summary> /// Reads an array of primitive values into the list, if the wire-type of fieldTag is length-prefixed, it will /// read a packed array. /// </summary> [CLSCompliant(false)] void ReadEnumArray(uint fieldTag, string fieldName, ICollection<IEnumLite> list, out ICollection<object> unknown, IEnumLiteMap mapping); /// <summary> /// Reads an array of primitive values into the list, if the wire-type of fieldTag is length-prefixed, it will /// read a packed array. /// </summary> [CLSCompliant(false)] void ReadEnumArray<T>(uint fieldTag, string fieldName, ICollection<T> list, out ICollection<object> unknown) where T : struct, IComparable, IFormattable; /// <summary> /// Reads a set of messages using the <paramref name="messageType"/> as a template. T is not guaranteed to be /// the most derived type, it is only the type specifier for the collection. /// </summary> [CLSCompliant(false)] void ReadMessageArray<T>(uint fieldTag, string fieldName, ICollection<T> list, T messageType, ExtensionRegistry registry) where T : IMessageLite; /// <summary> /// Reads a set of messages using the <paramref name="messageType"/> as a template. /// </summary> [CLSCompliant(false)] void ReadGroupArray<T>(uint fieldTag, string fieldName, ICollection<T> list, T messageType, ExtensionRegistry registry) where T : IMessageLite; /// <summary> /// Reads a field of any primitive type. Enums, groups and embedded /// messages are not handled by this method. /// </summary> bool ReadPrimitiveField(FieldType fieldType, ref object value); /// <summary> /// Returns true if the stream has reached the end of the input. This is the /// case if either the end of the underlying input source has been reached or /// the stream has reached a limit created using PushLimit. /// </summary> bool IsAtEnd { get; } /// <summary> /// Reads and discards a single field, given its tag value. /// </summary> /// <returns>false if the tag is an end-group tag, in which case /// nothing is skipped. Otherwise, returns true.</returns> [CLSCompliant(false)] bool SkipField(); /// <summary> /// Reads one or more repeated string field values from the stream. /// </summary> [CLSCompliant(false)] void ReadStringArray(uint fieldTag, string fieldName, ICollection<string> list); /// <summary> /// Reads one or more repeated ByteString field values from the stream. /// </summary> [CLSCompliant(false)] void ReadBytesArray(uint fieldTag, string fieldName, ICollection<ByteString> list); /// <summary> /// Reads one or more repeated boolean field values from the stream. /// </summary> [CLSCompliant(false)] void ReadBoolArray(uint fieldTag, string fieldName, ICollection<bool> list); /// <summary> /// Reads one or more repeated Int32 field values from the stream. /// </summary> [CLSCompliant(false)] void ReadInt32Array(uint fieldTag, string fieldName, ICollection<int> list); /// <summary> /// Reads one or more repeated SInt32 field values from the stream. /// </summary> [CLSCompliant(false)] void ReadSInt32Array(uint fieldTag, string fieldName, ICollection<int> list); /// <summary> /// Reads one or more repeated UInt32 field values from the stream. /// </summary> [CLSCompliant(false)] void ReadUInt32Array(uint fieldTag, string fieldName, ICollection<uint> list); /// <summary> /// Reads one or more repeated Fixed32 field values from the stream. /// </summary> [CLSCompliant(false)] void ReadFixed32Array(uint fieldTag, string fieldName, ICollection<uint> list); /// <summary> /// Reads one or more repeated SFixed32 field values from the stream. /// </summary> [CLSCompliant(false)] void ReadSFixed32Array(uint fieldTag, string fieldName, ICollection<int> list); /// <summary> /// Reads one or more repeated Int64 field values from the stream. /// </summary> [CLSCompliant(false)] void ReadInt64Array(uint fieldTag, string fieldName, ICollection<long> list); /// <summary> /// Reads one or more repeated SInt64 field values from the stream. /// </summary> [CLSCompliant(false)] void ReadSInt64Array(uint fieldTag, string fieldName, ICollection<long> list); /// <summary> /// Reads one or more repeated UInt64 field values from the stream. /// </summary> [CLSCompliant(false)] void ReadUInt64Array(uint fieldTag, string fieldName, ICollection<ulong> list); /// <summary> /// Reads one or more repeated Fixed64 field values from the stream. /// </summary> [CLSCompliant(false)] void ReadFixed64Array(uint fieldTag, string fieldName, ICollection<ulong> list); /// <summary> /// Reads one or more repeated SFixed64 field values from the stream. /// </summary> [CLSCompliant(false)] void ReadSFixed64Array(uint fieldTag, string fieldName, ICollection<long> list); /// <summary> /// Reads one or more repeated Double field values from the stream. /// </summary> [CLSCompliant(false)] void ReadDoubleArray(uint fieldTag, string fieldName, ICollection<double> list); /// <summary> /// Reads one or more repeated Float field values from the stream. /// </summary> [CLSCompliant(false)] void ReadFloatArray(uint fieldTag, string fieldName, ICollection<float> list); } }
// Copyright (c) .NET Foundation. 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.IO; using System.Text; using JetBrains.Annotations; namespace Microsoft.EntityFrameworkCore.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public class IndentedStringBuilder { private const byte IndentSize = 4; private byte _indent; private bool _indentPending = true; private readonly StringBuilder _stringBuilder = new StringBuilder(); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public IndentedStringBuilder() { } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public IndentedStringBuilder([NotNull] IndentedStringBuilder from) { _indent = from._indent; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual int Length => _stringBuilder.Length; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IndentedStringBuilder Append([NotNull] object o) { DoIndent(); _stringBuilder.Append(o); return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IndentedStringBuilder AppendLine() { AppendLine(string.Empty); return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IndentedStringBuilder AppendLine([NotNull] object o) { var value = o.ToString(); if (value.Length != 0) { DoIndent(); } _stringBuilder.AppendLine(value); _indentPending = true; return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IndentedStringBuilder AppendLines([NotNull] object o, bool skipFinalNewline = false) { using (var reader = new StringReader(o.ToString())) { var first = true; string line; while ((line = reader.ReadLine()) != null) { if (first) { first = false; } else { AppendLine(); } if (line.Length != 0) { Append(line); } } } if (!skipFinalNewline) { AppendLine(); } return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IndentedStringBuilder Clear() { _stringBuilder.Clear(); return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IndentedStringBuilder IncrementIndent() { _indent++; return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IndentedStringBuilder DecrementIndent() { if (_indent > 0) { _indent--; } return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IDisposable Indent() => new Indenter(this); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public override string ToString() => _stringBuilder.ToString(); private void DoIndent() { if (_indentPending && (_indent > 0)) { _stringBuilder.Append(new string(' ', _indent * IndentSize)); } _indentPending = false; } private sealed class Indenter : IDisposable { private readonly IndentedStringBuilder _stringBuilder; public Indenter(IndentedStringBuilder stringBuilder) { _stringBuilder = stringBuilder; _stringBuilder.IncrementIndent(); } public void Dispose() => _stringBuilder.DecrementIndent(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using k8s.Models; using Xunit; namespace k8s.Tests { public class YamlTests { [Fact] public void LoadAllFromString() { var content = @"apiVersion: v1 kind: Pod metadata: name: foo --- apiVersion: v1 kind: Namespace metadata: name: ns"; var objs = Yaml.LoadAllFromString(content); Assert.Equal(2, objs.Count); Assert.IsType<V1Pod>(objs[0]); Assert.IsType<V1Namespace>(objs[1]); Assert.Equal("foo", ((V1Pod)objs[0]).Metadata.Name); Assert.Equal("ns", ((V1Namespace)objs[1]).Metadata.Name); } #pragma warning disable CA1812 // Class is used for YAML deserialization tests private class MyPod : V1Pod { } #pragma warning restore CA1812 [Fact] public void LoadAllFromStringWithTypes() { var types = new Dictionary<string, Type>(); types.Add("v1/Pod", typeof(MyPod)); var content = @"apiVersion: v1 kind: Pod metadata: name: foo --- apiVersion: v1 kind: Namespace metadata: name: ns"; var objs = Yaml.LoadAllFromString(content, types); Assert.Equal(2, objs.Count); Assert.IsType<MyPod>(objs[0]); Assert.IsType<V1Namespace>(objs[1]); Assert.Equal("foo", ((MyPod)objs[0]).Metadata.Name); Assert.Equal("ns", ((V1Namespace)objs[1]).Metadata.Name); } [Fact] public void LoadAllFromStringWithAdditionalProperties() { var content = @"apiVersion: v1 kind: Pod metadata: name: foo namespace: ns youDontKnow: Me --- apiVersion: v1 kind: Namespace metadata: name: ns youDontKnow: Me"; var objs = Yaml.LoadAllFromString(content); Assert.Equal(2, objs.Count); Assert.IsType<V1Pod>(objs[0]); Assert.IsType<V1Namespace>(objs[1]); Assert.Equal("foo", ((V1Pod)objs[0]).Metadata.Name); Assert.Equal("ns", ((V1Pod)objs[0]).Metadata.NamespaceProperty); Assert.Equal("ns", ((V1Namespace)objs[1]).Metadata.Name); } [Fact] public void LoadAllFromStringWithAdditionalPropertiesAndTypes() { var types = new Dictionary<string, Type>(); types.Add("v1/Pod", typeof(MyPod)); var content = @"apiVersion: v1 kind: Pod metadata: name: foo namespace: ns youDontKnow: Me --- apiVersion: v1 kind: Namespace metadata: name: ns youDontKnow: Me"; var objs = Yaml.LoadAllFromString(content, types); Assert.Equal(2, objs.Count); Assert.IsType<MyPod>(objs[0]); Assert.IsType<V1Namespace>(objs[1]); Assert.Equal("foo", ((MyPod)objs[0]).Metadata.Name); Assert.Equal("ns", ((MyPod)objs[0]).Metadata.NamespaceProperty); Assert.Equal("ns", ((V1Namespace)objs[1]).Metadata.Name); } [Fact] public async Task LoadAllFromFile() { var content = @"apiVersion: v1 kind: Pod metadata: name: foo --- apiVersion: v1 kind: Namespace metadata: name: ns"; var tempFileName = Path.GetTempFileName(); try { await File.WriteAllTextAsync(tempFileName, content).ConfigureAwait(false); var objs = await Yaml.LoadAllFromFileAsync(tempFileName).ConfigureAwait(false); Assert.Equal(2, objs.Count); Assert.IsType<V1Pod>(objs[0]); Assert.IsType<V1Namespace>(objs[1]); Assert.Equal("foo", ((V1Pod)objs[0]).Metadata.Name); Assert.Equal("ns", ((V1Namespace)objs[1]).Metadata.Name); } finally { if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } } [Fact] public async Task LoadAllFromFileWithTypes() { var types = new Dictionary<string, Type>(); types.Add("v1/Pod", typeof(MyPod)); var content = @"apiVersion: v1 kind: Pod metadata: name: foo --- apiVersion: v1 kind: Namespace metadata: name: ns"; var tempFileName = Path.GetTempFileName(); try { await File.WriteAllTextAsync(tempFileName, content).ConfigureAwait(false); var objs = await Yaml.LoadAllFromFileAsync(tempFileName, types).ConfigureAwait(false); Assert.Equal(2, objs.Count); Assert.IsType<MyPod>(objs[0]); Assert.IsType<V1Namespace>(objs[1]); Assert.Equal("foo", ((MyPod)objs[0]).Metadata.Name); Assert.Equal("ns", ((V1Namespace)objs[1]).Metadata.Name); } finally { if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } } [Fact] public void LoadFromString() { var content = @"apiVersion: v1 kind: Pod metadata: name: foo "; var obj = Yaml.LoadFromString<V1Pod>(content); Assert.Equal("foo", obj.Metadata.Name); } [Fact] public void LoadFromStringWithAdditionalProperties() { var content = @"apiVersion: v1 kind: Pod metadata: name: foo youDontKnow: Me "; var obj = Yaml.LoadFromString<V1Pod>(content); Assert.Equal("foo", obj.Metadata.Name); } [Fact] public void LoadFromStringWithAdditionalPropertiesAndCustomType() { var content = @"apiVersion: v1 kind: Pod metadata: name: foo youDontKnow: Me "; var obj = Yaml.LoadFromString<V1Pod>(content); Assert.Equal("foo", obj.Metadata.Name); } [Fact] public void LoadNamespacedFromString() { var content = @"apiVersion: v1 kind: Pod metadata: namespace: bar name: foo "; var obj = Yaml.LoadFromString<V1Pod>(content); Assert.Equal("foo", obj.Metadata.Name); Assert.Equal("bar", obj.Metadata.NamespaceProperty); } [Fact] public void LoadPropertyNamedReadOnlyFromString() { var content = @"apiVersion: v1 kind: Pod metadata: namespace: bar name: foo spec: containers: - image: nginx volumeMounts: - name: vm1 mountPath: /vm1 readOnly: true - name: vm2 mountPath: /vm2 readOnly: false "; var obj = Yaml.LoadFromString<V1Pod>(content); Assert.True(obj.Spec.Containers[0].VolumeMounts[0].ReadOnlyProperty); Assert.False(obj.Spec.Containers[0].VolumeMounts[1].ReadOnlyProperty); } [Fact] public void LoadFromStream() { var content = @"apiVersion: v1 kind: Pod metadata: name: foo "; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content))) { var obj = Yaml.LoadFromStreamAsync<V1Pod>(stream).Result; Assert.Equal("foo", obj.Metadata.Name); } } [Fact] public async Task LoadFromFile() { var content = @"apiVersion: v1 kind: Pod metadata: name: foo "; var tempFileName = Path.GetTempFileName(); try { await File.WriteAllTextAsync(tempFileName, content).ConfigureAwait(false); var obj = await Yaml.LoadFromFileAsync<V1Pod>(tempFileName).ConfigureAwait(false); Assert.Equal("foo", obj.Metadata.Name); } finally { if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } } [Fact] public void RoundtripTypeWithMismatchedPropertyName() { var content = @"namespace: foo"; var deserialized = Yaml.LoadFromString<V1ObjectMeta>(content); Assert.Equal("foo", deserialized.NamespaceProperty); var serialized = Yaml.SaveToString(deserialized); Assert.Equal(content, serialized); } [Fact] public void WriteToString() { var pod = new V1Pod() { ApiVersion = "v1", Kind = "Pod", Metadata = new V1ObjectMeta() { Name = "foo" } }; var yaml = Yaml.SaveToString(pod); Assert.Equal( ToLines(@"apiVersion: v1 kind: Pod metadata: name: foo"), ToLines(yaml)); } [Fact] public void WriteNamespacedToString() { var pod = new V1Pod() { ApiVersion = "v1", Kind = "Pod", Metadata = new V1ObjectMeta() { Name = "foo", NamespaceProperty = "bar" }, }; var yaml = Yaml.SaveToString(pod); Assert.Equal( ToLines(@"apiVersion: v1 kind: Pod metadata: name: foo namespace: bar"), ToLines(yaml)); } [Fact] public void WritePropertyNamedReadOnlyToString() { var pod = new V1Pod() { ApiVersion = "v1", Kind = "Pod", Metadata = new V1ObjectMeta() { Name = "foo", NamespaceProperty = "bar" }, Spec = new V1PodSpec() { Containers = new[] { new V1Container() { Image = "nginx", VolumeMounts = new[] { new V1VolumeMount { Name = "vm1", MountPath = "/vm1", ReadOnlyProperty = true, }, new V1VolumeMount { Name = "vm2", MountPath = "/vm2", ReadOnlyProperty = false, }, }, }, }, }, }; var yaml = Yaml.SaveToString(pod); Assert.Equal( ToLines(@"apiVersion: v1 kind: Pod metadata: name: foo namespace: bar spec: containers: - image: nginx volumeMounts: - mountPath: /vm1 name: vm1 readOnly: true - mountPath: /vm2 name: vm2 readOnly: false"), ToLines(yaml)); } private static IEnumerable<string> ToLines(string s) { using (var reader = new StringReader(s)) { for (; ; ) { var line = reader.ReadLine(); if (line == null) { yield break; } yield return line; } } } [Fact] public void CpuRequestAndLimitFromString() { // Taken from https://raw.githubusercontent.com/kubernetes/website/master/docs/tasks/configure-pod-container/cpu-request-limit.yaml, although // the 'namespace' property on 'metadata' was removed since it was rejected by the C# client. var content = @"apiVersion: v1 kind: Pod metadata: name: cpu-demo spec: containers: - name: cpu-demo-ctr image: vish/stress resources: limits: cpu: ""1"" requests: cpu: ""0.5"" args: - -cpus - ""2"""; var obj = Yaml.LoadFromString<V1Pod>(content); Assert.NotNull(obj?.Spec?.Containers); var container = Assert.Single(obj.Spec.Containers); Assert.NotNull(container.Resources); Assert.NotNull(container.Resources.Limits); Assert.NotNull(container.Resources.Requests); var cpuLimit = Assert.Single(container.Resources.Limits); var cpuRequest = Assert.Single(container.Resources.Requests); Assert.Equal("cpu", cpuLimit.Key); Assert.Equal("1", cpuLimit.Value.ToString()); Assert.Equal("cpu", cpuRequest.Key); Assert.Equal("500m", cpuRequest.Value.ToString()); } [Fact] public void LoadIntOrString() { var content = @"apiVersion: v1 kind: Service spec: ports: - port: 3000 targetPort: 3000 "; var obj = Yaml.LoadFromString<V1Service>(content); Assert.Equal(3000, obj.Spec.Ports[0].Port); Assert.Equal(3000, int.Parse(obj.Spec.Ports[0].TargetPort)); } [Fact] public void SerializeIntOrString() { var content = @"apiVersion: v1 kind: Service metadata: labels: app: test name: test-svc spec: ports: - port: 3000 targetPort: 3000"; var labels = new Dictionary<string, string> { { "app", "test" } }; var obj = new V1Service { Kind = "Service", Metadata = new V1ObjectMeta(labels: labels, name: "test-svc"), ApiVersion = "v1", Spec = new V1ServiceSpec { Ports = new List<V1ServicePort> { new V1ServicePort { Port = 3000, TargetPort = 3000 } }, }, }; var output = Yaml.SaveToString(obj); Assert.Equal(ToLines(output), ToLines(content)); } [Fact] public void QuotedValuesShouldRemainQuotedAfterSerialization() { var content = @"apiVersion: v1 kind: Pod metadata: annotations: custom.annotation: ""null"" name: cpu-demo spec: containers: - env: - name: PORT value: ""3000"" - name: NUM_RETRIES value: ""3"" - name: ENABLE_CACHE value: ""true"" - name: ENABLE_OTHER value: ""false"" image: vish/stress name: cpu-demo-ctr"; var obj = Yaml.LoadFromString<V1Pod>(content); Assert.NotNull(obj?.Spec?.Containers); var container = Assert.Single(obj.Spec.Containers); Assert.NotNull(container.Env); var objStr = Yaml.SaveToString(obj); Assert.Equal(content.Replace("\r\n", "\n"), objStr.Replace("\r\n", "\n")); } [Fact] public void LoadSecret() { var kManifest = @" apiVersion: v1 kind: Secret metadata: name: test-secret data: username: bXktYXBw password: Mzk1MjgkdmRnN0pi "; var result = Yaml.LoadFromString<V1Secret>(kManifest); Assert.Equal("bXktYXBw", Encoding.UTF8.GetString(result.Data["username"])); Assert.Equal("Mzk1MjgkdmRnN0pi", Encoding.UTF8.GetString(result.Data["password"])); } [Fact] public void DeserializeWithJsonPropertyName() { var kManifest = @" apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: test-crd spec: group: test.crd names: kind: Crd listKind: CrdList plural: crds singular: crd scope: Namespaced versions: - name: v1alpha1 schema: openAPIV3Schema: description: This is a test crd. x-kubernetes-int-or-string: true required: - metadata - spec type: object served: true storage: true "; var result = Yaml.LoadFromString<V1CustomResourceDefinition>(kManifest); Assert.Single(result?.Spec?.Versions); var ver = result.Spec.Versions[0]; Assert.Equal(true, ver?.Schema?.OpenAPIV3Schema?.XKubernetesIntOrString); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace iskkonekb.kuvera.app.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
#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 Ctrip.Log4.Util; using Ctrip.Log4.Layout; using Ctrip.Log4.Core; namespace Ctrip.Log4.Appender { /// <summary> /// This appender forwards logging events to attached appenders. /// </summary> /// <remarks> /// <para> /// The forwarding appender can be used to specify different thresholds /// and filters for the same appender at different locations within the hierarchy. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class ForwardingAppender : AppenderSkeleton, IAppenderAttachable { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="ForwardingAppender" /> class. /// </summary> /// <remarks> /// <para> /// Default constructor. /// </para> /// </remarks> public ForwardingAppender() { } #endregion Public Instance Constructors #region Override implementation of AppenderSkeleton /// <summary> /// Closes the appender and releases resources. /// </summary> /// <remarks> /// <para> /// Releases any resources allocated within the appender such as file handles, /// network connections, etc. /// </para> /// <para> /// It is a programming error to append to a closed appender. /// </para> /// </remarks> override protected void OnClose() { // Remove all the attached appenders lock(this) { if (m_appenderAttachedImpl != null) { m_appenderAttachedImpl.RemoveAllAppenders(); } } } /// <summary> /// Forward the logging event to the attached appenders /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Delivers the logging event to all the attached appenders. /// </para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { // Pass the logging event on the the attached appenders if (m_appenderAttachedImpl != null) { m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent); } } /// <summary> /// Forward the logging events to the attached appenders /// </summary> /// <param name="loggingEvents">The array of events to log.</param> /// <remarks> /// <para> /// Delivers the logging events to all the attached appenders. /// </para> /// </remarks> override protected void Append(LoggingEvent[] loggingEvents) { // Pass the logging event on the the attached appenders if (m_appenderAttachedImpl != null) { m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvents); } } #endregion Override implementation of AppenderSkeleton #region Implementation of IAppenderAttachable /// <summary> /// Adds an <see cref="IAppender" /> to the list of appenders of this /// instance. /// </summary> /// <param name="newAppender">The <see cref="IAppender" /> to add to this appender.</param> /// <remarks> /// <para> /// If the specified <see cref="IAppender" /> is already in the list of /// appenders, then it won't be added again. /// </para> /// </remarks> virtual public void AddAppender(IAppender newAppender) { if (newAppender == null) { throw new ArgumentNullException("newAppender"); } lock(this) { if (m_appenderAttachedImpl == null) { m_appenderAttachedImpl = new Ctrip.Log4.Util.AppenderAttachedImpl(); } m_appenderAttachedImpl.AddAppender(newAppender); } } /// <summary> /// Gets the appenders contained in this appender as an /// <see cref="System.Collections.ICollection"/>. /// </summary> /// <remarks> /// If no appenders can be found, then an <see cref="EmptyCollection"/> /// is returned. /// </remarks> /// <returns> /// A collection of the appenders in this appender. /// </returns> virtual public AppenderCollection Appenders { get { lock(this) { if (m_appenderAttachedImpl == null) { return AppenderCollection.EmptyCollection; } else { return m_appenderAttachedImpl.Appenders; } } } } /// <summary> /// Looks for the appender with the specified name. /// </summary> /// <param name="name">The name of the appender to lookup.</param> /// <returns> /// The appender with the specified name, or <c>null</c>. /// </returns> /// <remarks> /// <para> /// Get the named appender attached to this appender. /// </para> /// </remarks> virtual public IAppender GetAppender(string name) { lock(this) { if (m_appenderAttachedImpl == null || name == null) { return null; } return m_appenderAttachedImpl.GetAppender(name); } } /// <summary> /// Removes all previously added appenders from this appender. /// </summary> /// <remarks> /// <para> /// This is useful when re-reading configuration information. /// </para> /// </remarks> virtual public void RemoveAllAppenders() { lock(this) { if (m_appenderAttachedImpl != null) { m_appenderAttachedImpl.RemoveAllAppenders(); m_appenderAttachedImpl = null; } } } /// <summary> /// Removes the specified appender from the list of appenders. /// </summary> /// <param name="appender">The appender to remove.</param> /// <returns>The appender removed from the list</returns> /// <remarks> /// The appender removed is not closed. /// If you are discarding the appender you must call /// <see cref="IAppender.Close"/> on the appender removed. /// </remarks> virtual public IAppender RemoveAppender(IAppender appender) { lock(this) { if (appender != null && m_appenderAttachedImpl != null) { return m_appenderAttachedImpl.RemoveAppender(appender); } } return null; } /// <summary> /// Removes the appender with the specified name from the list of appenders. /// </summary> /// <param name="name">The name of the appender to remove.</param> /// <returns>The appender removed from the list</returns> /// <remarks> /// The appender removed is not closed. /// If you are discarding the appender you must call /// <see cref="IAppender.Close"/> on the appender removed. /// </remarks> virtual public IAppender RemoveAppender(string name) { lock(this) { if (name != null && m_appenderAttachedImpl != null) { return m_appenderAttachedImpl.RemoveAppender(name); } } return null; } #endregion Implementation of IAppenderAttachable #region Private Instance Fields /// <summary> /// Implementation of the <see cref="IAppenderAttachable"/> interface /// </summary> private AppenderAttachedImpl m_appenderAttachedImpl; #endregion Private Instance Fields } }
// 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 Roslyn.Utilities; using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.Cci { /// <summary> /// Represents a .NET assembly. /// </summary> internal interface IAssembly : IModule, IAssemblyReference { /// <summary> /// A list of the files that constitute the assembly. These are not the source language files that may have been /// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well /// as any external resources. It corresponds to the File table of the .NET assembly file format. /// </summary> IEnumerable<IFileReference> GetFiles(EmitContext context); /// <summary> /// A set of bits and bit ranges representing properties of the assembly. The value of <see cref="Flags"/> can be set /// from source code via the AssemblyFlags assembly custom attribute. The interpretation of the property depends on the target platform. /// </summary> AssemblyFlags Flags { get; } /// <summary> /// The public part of the key used to encrypt the SHA1 hash over the persisted form of this assembly. Empty or null if not specified. /// This value is used by the loader to decrypt an encrypted hash value stored in the assembly, which it then compares with a freshly computed hash value /// in order to verify the integrity of the assembly. /// </summary> ImmutableArray<byte> PublicKey { get; } /// <summary> /// The contents of the AssemblySignatureKeyAttribute /// </summary> string SignatureKey { get; } AssemblyHashAlgorithm HashAlgorithm { get; } } /// <summary> /// A reference to a .NET assembly. /// </summary> internal interface IAssemblyReference : IModuleReference { AssemblyIdentity Identity { get; } Version AssemblyVersionPattern { get; } } /// <summary> /// An object that represents a .NET module. /// </summary> internal interface IModule : IUnit, IModuleReference { ModulePropertiesForSerialization Properties { get; } /// <summary> /// Used to distinguish which style to pick while writing native PDB information. /// </summary> /// <remarks> /// The PDB content for custom debug information is different between Visual Basic and CSharp. /// E.g. C# always includes a CustomMetadata Header (MD2) that contains the namespace scope counts, where /// as VB only outputs namespace imports into the namespace scopes. /// C# defines forwards in that header, VB includes them into the scopes list. /// /// Currently the compiler doesn't allow mixing C# and VB method bodies. Thus this flag can be per module. /// It is possible to move this flag to per-method basis but native PDB CDI forwarding would need to be adjusted accordingly. /// </remarks> bool GenerateVisualBasicStylePdb { get; } /// <summary> /// Public types defined in other modules making up this assembly and to which other assemblies may refer to via this assembly /// followed by types forwarded to another assembly. /// </summary> ImmutableArray<ExportedType> GetExportedTypes(DiagnosticBag diagnostics); /// <summary> /// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata /// with this assembly. /// </summary> IEnumerable<ICustomAttribute> AssemblyAttributes { get; } /// <summary> /// A list of objects representing persisted instances of pairs of security actions and sets of security permissions. /// These apply by default to every method reachable from the module. /// </summary> IEnumerable<SecurityAttribute> AssemblySecurityAttributes { get; } /// <summary> /// A list of the assemblies that are referenced by this module. /// </summary> IEnumerable<IAssemblyReference> GetAssemblyReferences(EmitContext context); /// <summary> /// A list of named byte sequences persisted with the assembly and used during execution, typically via .NET Framework helper classes. /// </summary> ImmutableArray<ManagedResource> GetResources(EmitContext context); /// <summary> /// CorLibrary assembly referenced by this module. /// </summary> IAssemblyReference GetCorLibrary(EmitContext context); /// <summary> /// The Assembly that contains this module. If this module is main module then this returns this. /// </summary> new IAssembly GetContainingAssembly(EmitContext context); /// <summary> /// The method that will be called to start execution of this executable module. /// </summary> IMethodReference PEEntryPoint { get; } IMethodReference DebugEntryPoint { get; } /// <summary> /// Returns zero or more strings used in the module. If the module is produced by reading in a CLR PE file, then this will be the contents /// of the user string heap. If the module is produced some other way, the method may return an empty enumeration or an enumeration that is a /// subset of the strings actually used in the module. The main purpose of this method is to provide a way to control the order of strings in a /// prefix of the user string heap when writing out a module as a PE file. /// </summary> IEnumerable<string> GetStrings(); /// <summary> /// Returns all top-level (not nested) types defined in the current module. /// </summary> IEnumerable<INamespaceTypeDefinition> GetTopLevelTypes(EmitContext context); /// <summary> /// The kind of metadata stored in this module. For example whether this module is an executable or a manifest resource file. /// </summary> OutputKind Kind { get; } /// <summary> /// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata /// with this module. /// </summary> IEnumerable<ICustomAttribute> ModuleAttributes { get; } /// <summary> /// The name of the module. /// </summary> string ModuleName { get; } /// <summary> /// A list of the modules that are referenced by this module. /// </summary> IEnumerable<IModuleReference> ModuleReferences { get; } /// <summary> /// A list of named byte sequences persisted with the module and used during execution, typically via the Win32 API. /// A module will define Win32 resources rather than "managed" resources mainly to present metadata to legacy tools /// and not typically use the data in its own code. /// </summary> IEnumerable<IWin32Resource> Win32Resources { get; } /// <summary> /// An alternate form the Win32 resources may take. These represent the rsrc$01 and rsrc$02 section data and relocs /// from a COFF object file. /// </summary> ResourceSection Win32ResourceSection { get; } IAssembly AsAssembly { get; } ITypeReference GetPlatformType(PlatformType t, EmitContext context); bool IsPlatformType(ITypeReference typeRef, PlatformType t); IEnumerable<IReference> ReferencesInIL(out int count); /// <summary> /// Builds symbol definition to location map used for emitting token -> location info /// into PDB to be consumed by WinMdExp.exe tool (only applicable for /t:winmdobj) /// </summary> MultiDictionary<DebugSourceDocument, DefinitionWithLocation> GetSymbolToLocationMap(); /// <summary> /// Assembly reference aliases (C# only). /// </summary> ImmutableArray<AssemblyReferenceAlias> GetAssemblyReferenceAliases(EmitContext context); /// <summary> /// Linked assembly names to be stored to native PDB (VB only). /// </summary> IEnumerable<string> LinkedAssembliesDebugInfo { get; } /// <summary> /// Project level imports (VB only, TODO: C# scripts). /// </summary> ImmutableArray<UsedNamespaceOrType> GetImports(); /// <summary> /// Default namespace (VB only). /// </summary> string DefaultNamespace { get; } // An approximate number of method definitions that can // provide a basis for approximating the capacities of // various databases used during Emit. int HintNumberOfMethodDefinitions { get; } /// <summary> /// Number of debug documents in the module. /// Used to determine capacities of lists and indices when emitting debug info. /// </summary> int DebugDocumentCount { get; } } internal struct DefinitionWithLocation { public readonly IDefinition Definition; public readonly uint StartLine; public readonly uint StartColumn; public readonly uint EndLine; public readonly uint EndColumn; public DefinitionWithLocation(IDefinition definition, int startLine, int startColumn, int endLine, int endColumn) { Debug.Assert(startLine >= 0); Debug.Assert(startColumn >= 0); Debug.Assert(endLine >= 0); Debug.Assert(endColumn >= 0); this.Definition = definition; this.StartLine = (uint)startLine; this.StartColumn = (uint)startColumn; this.EndLine = (uint)endLine; this.EndColumn = (uint)endColumn; } public override string ToString() { return string.Format( "{0} => start:{1}/{2}, end:{3}/{4}", this.Definition.ToString(), this.StartLine.ToString(), this.StartColumn.ToString(), this.EndLine.ToString(), this.EndColumn.ToString()); } } /// <summary> /// A reference to a .NET module. /// </summary> internal interface IModuleReference : IUnitReference { /// <summary> /// The Assembly that contains this module. May be null if the module is not part of an assembly. /// </summary> IAssemblyReference GetContainingAssembly(EmitContext context); } /// <summary> /// A unit of metadata stored as a single artifact and potentially produced and revised independently from other units. /// Examples of units include .NET assemblies and modules, as well C++ object files and compiled headers. /// </summary> internal interface IUnit : IUnitReference, IDefinition { } /// <summary> /// A reference to a instance of <see cref="IUnit"/>. /// </summary> internal interface IUnitReference : IReference, INamedEntity { } }
#region PDFsharp Charting - A .NET charting library based on PDFsharp // // Authors: // Niklas Schneider (mailto:Niklas.Schneider@pdfsharp.com) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using PdfSharp; using PdfSharp.Pdf; using PdfSharp.Drawing; using PdfSharp.Forms; namespace PdfSharp.Charting.Demo { /// <summary> /// MainForm. /// </summary> public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.Panel pnlMain; private System.Windows.Forms.Panel pnlLeft; private System.Windows.Forms.Panel pnlRight; private System.Windows.Forms.Splitter splitter; private System.Windows.Forms.TreeView tvNavigation; private PdfSharp.Forms.PagePreview pagePreview; private System.Windows.Forms.Button btnPdf; private System.ComponentModel.Container components = null; private System.Windows.Forms.Panel pnlPreview; private System.Windows.Forms.Button btnOriginalSize; private System.Windows.Forms.Button btnFullPage; private System.Windows.Forms.Button btnBestFit; private System.Windows.Forms.Button btnMinus; private System.Windows.Forms.Button btnPlus; private ChartFrame chartFrame; public MainForm() { InitializeComponent(); this.tvNavigation.SelectedNode = this.tvNavigation.Nodes[0]; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } int GetNewZoom(int currentZoom, bool larger) { int[] values = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 140, 160, 180, 200, 250, 300, 350, 400, 450, 500, 600, 700, 800 }; if (currentZoom <= (int)Zoom.Mininum && !larger) return (int)Zoom.Mininum; else if (currentZoom >= (int)Zoom.Maximum && larger) return (int)Zoom.Maximum; if (larger) { for (int i = 0; i < values.Length; i++) { if (currentZoom < values[i]) return values[i]; } } else { for (int i = values.Length - 1; i >= 0 ; i--) { if (currentZoom > values[i]) return values[i]; } } return (int)Zoom.Percent100; } #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(MainForm)); this.pnlMain = new System.Windows.Forms.Panel(); this.pnlRight = new System.Windows.Forms.Panel(); this.pnlPreview = new System.Windows.Forms.Panel(); this.pagePreview = new PdfSharp.Forms.PagePreview(); this.splitter = new System.Windows.Forms.Splitter(); this.pnlLeft = new System.Windows.Forms.Panel(); this.tvNavigation = new System.Windows.Forms.TreeView(); this.btnPdf = new System.Windows.Forms.Button(); this.btnOriginalSize = new System.Windows.Forms.Button(); this.btnFullPage = new System.Windows.Forms.Button(); this.btnBestFit = new System.Windows.Forms.Button(); this.btnMinus = new System.Windows.Forms.Button(); this.btnPlus = new System.Windows.Forms.Button(); this.pnlMain.SuspendLayout(); this.pnlRight.SuspendLayout(); this.pnlPreview.SuspendLayout(); this.pnlLeft.SuspendLayout(); this.SuspendLayout(); // // pnlMain // this.pnlMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pnlMain.BackColor = System.Drawing.SystemColors.Control; this.pnlMain.Controls.Add(this.pnlRight); this.pnlMain.Controls.Add(this.splitter); this.pnlMain.Controls.Add(this.pnlLeft); this.pnlMain.Location = new System.Drawing.Point(0, 80); this.pnlMain.Name = "pnlMain"; this.pnlMain.Size = new System.Drawing.Size(792, 486); this.pnlMain.TabIndex = 0; // // pnlRight // this.pnlRight.BackColor = System.Drawing.SystemColors.Control; this.pnlRight.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pnlRight.Controls.Add(this.pnlPreview); this.pnlRight.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlRight.Location = new System.Drawing.Point(205, 0); this.pnlRight.Name = "pnlRight"; this.pnlRight.Size = new System.Drawing.Size(587, 486); this.pnlRight.TabIndex = 2; // // pnlPreview // this.pnlPreview.Controls.Add(this.pagePreview); this.pnlPreview.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlPreview.Location = new System.Drawing.Point(0, 0); this.pnlPreview.Name = "pnlPreview"; this.pnlPreview.Size = new System.Drawing.Size(583, 482); this.pnlPreview.TabIndex = 0; // // pagePreview // this.pagePreview.BackColor = System.Drawing.SystemColors.Control; this.pagePreview.BorderStyle = System.Windows.Forms.BorderStyle.None; this.pagePreview.DesktopColor = System.Drawing.SystemColors.ControlDark; this.pagePreview.Dock = System.Windows.Forms.DockStyle.Fill; this.pagePreview.Location = new System.Drawing.Point(0, 0); this.pagePreview.Name = "pagePreview"; this.pagePreview.PageColor = System.Drawing.Color.GhostWhite; this.pagePreview.PageSize = new System.Drawing.Size(595, 842); this.pagePreview.Size = new System.Drawing.Size(583, 482); this.pagePreview.TabIndex = 4; this.pagePreview.Zoom = PdfSharp.Forms.Zoom.BestFit; this.pagePreview.ZoomPercent = 70; // // splitter // this.splitter.BackColor = System.Drawing.SystemColors.Control; this.splitter.Location = new System.Drawing.Point(200, 0); this.splitter.Name = "splitter"; this.splitter.Size = new System.Drawing.Size(5, 486); this.splitter.TabIndex = 1; this.splitter.TabStop = false; // // pnlLeft // this.pnlLeft.BackColor = System.Drawing.SystemColors.Control; this.pnlLeft.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pnlLeft.Controls.Add(this.tvNavigation); this.pnlLeft.Dock = System.Windows.Forms.DockStyle.Left; this.pnlLeft.Location = new System.Drawing.Point(0, 0); this.pnlLeft.Name = "pnlLeft"; this.pnlLeft.Size = new System.Drawing.Size(200, 486); this.pnlLeft.TabIndex = 0; // // tvNavigation // this.tvNavigation.BorderStyle = System.Windows.Forms.BorderStyle.None; this.tvNavigation.Dock = System.Windows.Forms.DockStyle.Fill; this.tvNavigation.ImageIndex = -1; this.tvNavigation.Location = new System.Drawing.Point(0, 0); this.tvNavigation.Name = "tvNavigation"; this.tvNavigation.Nodes.AddRange(new System.Windows.Forms.TreeNode[] { new System.Windows.Forms.TreeNode("Line Chart"), new System.Windows.Forms.TreeNode("Column Chart"), new System.Windows.Forms.TreeNode("Stacked Column Chart"), new System.Windows.Forms.TreeNode("Bar Chart"), new System.Windows.Forms.TreeNode("Stacked Bar Chart"), new System.Windows.Forms.TreeNode("Area Chart"), new System.Windows.Forms.TreeNode("Pie Chart"), new System.Windows.Forms.TreeNode("Pie Exploded Chart"), new System.Windows.Forms.TreeNode("Combination Chart")}); this.tvNavigation.SelectedImageIndex = -1; this.tvNavigation.Size = new System.Drawing.Size(196, 482); this.tvNavigation.TabIndex = 0; this.tvNavigation.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvNavigation_AfterSelect); // // btnPdf // this.btnPdf.BackColor = System.Drawing.Color.Transparent; this.btnPdf.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnPdf.Image = ((System.Drawing.Image)(resources.GetObject("btnPdf.Image"))); this.btnPdf.Location = new System.Drawing.Point(464, 16); this.btnPdf.Name = "btnPdf"; this.btnPdf.Size = new System.Drawing.Size(44, 44); this.btnPdf.TabIndex = 1; this.btnPdf.Click += new System.EventHandler(this.btnPdf_Click); // // btnOriginalSize // this.btnOriginalSize.BackColor = System.Drawing.Color.Transparent; this.btnOriginalSize.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnOriginalSize.Image = ((System.Drawing.Image)(resources.GetObject("btnOriginalSize.Image"))); this.btnOriginalSize.Location = new System.Drawing.Point(204, 16); this.btnOriginalSize.Name = "btnOriginalSize"; this.btnOriginalSize.Size = new System.Drawing.Size(44, 44); this.btnOriginalSize.TabIndex = 2; this.btnOriginalSize.Click += new System.EventHandler(this.btnOriginalSize_Click); // // btnFullPage // this.btnFullPage.BackColor = System.Drawing.Color.Transparent; this.btnFullPage.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnFullPage.Image = ((System.Drawing.Image)(resources.GetObject("btnFullPage.Image"))); this.btnFullPage.Location = new System.Drawing.Point(256, 16); this.btnFullPage.Name = "btnFullPage"; this.btnFullPage.Size = new System.Drawing.Size(44, 44); this.btnFullPage.TabIndex = 2; this.btnFullPage.Click += new System.EventHandler(this.btnFullPage_Click); // // btnBestFit // this.btnBestFit.BackColor = System.Drawing.Color.Transparent; this.btnBestFit.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnBestFit.Image = ((System.Drawing.Image)(resources.GetObject("btnBestFit.Image"))); this.btnBestFit.Location = new System.Drawing.Point(308, 16); this.btnBestFit.Name = "btnBestFit"; this.btnBestFit.Size = new System.Drawing.Size(44, 44); this.btnBestFit.TabIndex = 2; this.btnBestFit.Click += new System.EventHandler(this.btnBestFit_Click); // // btnMinus // this.btnMinus.BackColor = System.Drawing.Color.Transparent; this.btnMinus.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnMinus.Image = ((System.Drawing.Image)(resources.GetObject("btnMinus.Image"))); this.btnMinus.Location = new System.Drawing.Point(360, 16); this.btnMinus.Name = "btnMinus"; this.btnMinus.Size = new System.Drawing.Size(44, 44); this.btnMinus.TabIndex = 2; this.btnMinus.Click += new System.EventHandler(this.btnMinus_Click); // // btnPlus // this.btnPlus.BackColor = System.Drawing.Color.Transparent; this.btnPlus.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnPlus.Image = ((System.Drawing.Image)(resources.GetObject("btnPlus.Image"))); this.btnPlus.Location = new System.Drawing.Point(412, 16); this.btnPlus.Name = "btnPlus"; this.btnPlus.Size = new System.Drawing.Size(44, 44); this.btnPlus.TabIndex = 2; this.btnPlus.Click += new System.EventHandler(this.btnPlus_Click); // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.Color.WhiteSmoke; this.ClientSize = new System.Drawing.Size(792, 566); this.Controls.Add(this.btnOriginalSize); this.Controls.Add(this.btnPdf); this.Controls.Add(this.pnlMain); this.Controls.Add(this.btnFullPage); this.Controls.Add(this.btnBestFit); this.Controls.Add(this.btnMinus); this.Controls.Add(this.btnPlus); this.DockPadding.Bottom = -2; this.Name = "MainForm"; this.Text = "PDFsharp Charting Demo"; this.pnlMain.ResumeLayout(false); this.pnlRight.ResumeLayout(false); this.pnlPreview.ResumeLayout(false); this.pnlLeft.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void tvNavigation_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { this.chartFrame = new ChartFrame(); this.chartFrame.Location = new XPoint(30, 30); this.chartFrame.Size = new XSize(500, 600); Chart chart = null; switch (e.Node.Text.ToLower()) { case "line chart": chart = ChartSamples.LineChart(); break; case "column chart": chart = ChartSamples.ColumnChart(); break; case "stacked column chart": chart = ChartSamples.ColumnStackedChart(); break; case "bar chart": chart = ChartSamples.BarChart(); break; case "stacked bar chart": chart = ChartSamples.BarStackedChart(); break; case "area chart": chart = ChartSamples.AreaChart(); break; case "pie chart": chart = ChartSamples.PieChart(); break; case "pie exploded chart": chart = ChartSamples.PieExplodedChart(); break; case "combination chart": chart = ChartSamples.CombinationChart(); break; } this.chartFrame.Add(chart); this.pagePreview.SetRenderEvent(new PagePreview.RenderEvent(chartFrame.Draw)); } private void btnOriginalSize_Click(object sender, System.EventArgs e) { this.pagePreview.Zoom = Zoom.Percent100; } private void btnFullPage_Click(object sender, System.EventArgs e) { this.pagePreview.Zoom = Zoom.FullPage; } private void btnBestFit_Click(object sender, System.EventArgs e) { this.pagePreview.Zoom = Zoom.BestFit; } private void btnMinus_Click(object sender, System.EventArgs e) { this.pagePreview.ZoomPercent = GetNewZoom((int)this.pagePreview.ZoomPercent, false); } private void btnPlus_Click(object sender, System.EventArgs e) { this.pagePreview.ZoomPercent = GetNewZoom((int)this.pagePreview.ZoomPercent, true); } private void btnPdf_Click(object sender, System.EventArgs e) { string filename = Guid.NewGuid().ToString().ToUpper() + ".pdf"; PdfDocument document = new PdfDocument(filename); PdfPage page = document.AddPage(); page.Size = PageSize.A4; XGraphics gfx = XGraphics.FromPdfPage(page); this.chartFrame.Draw(gfx); document.Close(); Process.Start(filename); } } }
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; // <auto-generated /> namespace SAEON.Observations.Data{ /// <summary> /// Strongly-typed collection for the VDataLog class. /// </summary> [Serializable] public partial class VDataLogCollection : ReadOnlyList<VDataLog, VDataLogCollection> { public VDataLogCollection() {} } /// <summary> /// This is Read-only wrapper class for the vDataLog view. /// </summary> [Serializable] public partial class VDataLog : ReadOnlyRecord<VDataLog>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor 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("vDataLog", TableType.View, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = false; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarImportDate = new TableSchema.TableColumn(schema); colvarImportDate.ColumnName = "ImportDate"; colvarImportDate.DataType = DbType.DateTime; colvarImportDate.MaxLength = 0; colvarImportDate.AutoIncrement = false; colvarImportDate.IsNullable = false; colvarImportDate.IsPrimaryKey = false; colvarImportDate.IsForeignKey = false; colvarImportDate.IsReadOnly = false; schema.Columns.Add(colvarImportDate); TableSchema.TableColumn colvarSiteName = new TableSchema.TableColumn(schema); colvarSiteName.ColumnName = "SiteName"; colvarSiteName.DataType = DbType.AnsiString; colvarSiteName.MaxLength = 150; colvarSiteName.AutoIncrement = false; colvarSiteName.IsNullable = true; colvarSiteName.IsPrimaryKey = false; colvarSiteName.IsForeignKey = false; colvarSiteName.IsReadOnly = false; schema.Columns.Add(colvarSiteName); TableSchema.TableColumn colvarStationName = new TableSchema.TableColumn(schema); colvarStationName.ColumnName = "StationName"; colvarStationName.DataType = DbType.AnsiString; colvarStationName.MaxLength = 150; colvarStationName.AutoIncrement = false; colvarStationName.IsNullable = true; colvarStationName.IsPrimaryKey = false; colvarStationName.IsForeignKey = false; colvarStationName.IsReadOnly = false; schema.Columns.Add(colvarStationName); TableSchema.TableColumn colvarInstrumentName = new TableSchema.TableColumn(schema); colvarInstrumentName.ColumnName = "InstrumentName"; colvarInstrumentName.DataType = DbType.AnsiString; colvarInstrumentName.MaxLength = 150; colvarInstrumentName.AutoIncrement = false; colvarInstrumentName.IsNullable = true; colvarInstrumentName.IsPrimaryKey = false; colvarInstrumentName.IsForeignKey = false; colvarInstrumentName.IsReadOnly = false; schema.Columns.Add(colvarInstrumentName); TableSchema.TableColumn colvarSensorID = new TableSchema.TableColumn(schema); colvarSensorID.ColumnName = "SensorID"; colvarSensorID.DataType = DbType.Guid; colvarSensorID.MaxLength = 0; colvarSensorID.AutoIncrement = false; colvarSensorID.IsNullable = true; colvarSensorID.IsPrimaryKey = false; colvarSensorID.IsForeignKey = false; colvarSensorID.IsReadOnly = false; schema.Columns.Add(colvarSensorID); TableSchema.TableColumn colvarSensorName = new TableSchema.TableColumn(schema); colvarSensorName.ColumnName = "SensorName"; colvarSensorName.DataType = DbType.AnsiString; colvarSensorName.MaxLength = 150; colvarSensorName.AutoIncrement = false; colvarSensorName.IsNullable = true; colvarSensorName.IsPrimaryKey = false; colvarSensorName.IsForeignKey = false; colvarSensorName.IsReadOnly = false; schema.Columns.Add(colvarSensorName); TableSchema.TableColumn colvarSensorInvalid = new TableSchema.TableColumn(schema); colvarSensorInvalid.ColumnName = "SensorInvalid"; colvarSensorInvalid.DataType = DbType.Int32; colvarSensorInvalid.MaxLength = 0; colvarSensorInvalid.AutoIncrement = false; colvarSensorInvalid.IsNullable = false; colvarSensorInvalid.IsPrimaryKey = false; colvarSensorInvalid.IsForeignKey = false; colvarSensorInvalid.IsReadOnly = false; schema.Columns.Add(colvarSensorInvalid); TableSchema.TableColumn colvarValueDate = new TableSchema.TableColumn(schema); colvarValueDate.ColumnName = "ValueDate"; colvarValueDate.DataType = DbType.DateTime; colvarValueDate.MaxLength = 0; colvarValueDate.AutoIncrement = false; colvarValueDate.IsNullable = true; colvarValueDate.IsPrimaryKey = false; colvarValueDate.IsForeignKey = false; colvarValueDate.IsReadOnly = false; schema.Columns.Add(colvarValueDate); TableSchema.TableColumn colvarInvalidDateValue = new TableSchema.TableColumn(schema); colvarInvalidDateValue.ColumnName = "InvalidDateValue"; colvarInvalidDateValue.DataType = DbType.AnsiString; colvarInvalidDateValue.MaxLength = 50; colvarInvalidDateValue.AutoIncrement = false; colvarInvalidDateValue.IsNullable = true; colvarInvalidDateValue.IsPrimaryKey = false; colvarInvalidDateValue.IsForeignKey = false; colvarInvalidDateValue.IsReadOnly = false; schema.Columns.Add(colvarInvalidDateValue); TableSchema.TableColumn colvarDateValueInvalid = new TableSchema.TableColumn(schema); colvarDateValueInvalid.ColumnName = "DateValueInvalid"; colvarDateValueInvalid.DataType = DbType.Int32; colvarDateValueInvalid.MaxLength = 0; colvarDateValueInvalid.AutoIncrement = false; colvarDateValueInvalid.IsNullable = false; colvarDateValueInvalid.IsPrimaryKey = false; colvarDateValueInvalid.IsForeignKey = false; colvarDateValueInvalid.IsReadOnly = false; schema.Columns.Add(colvarDateValueInvalid); TableSchema.TableColumn colvarInvalidTimeValue = new TableSchema.TableColumn(schema); colvarInvalidTimeValue.ColumnName = "InvalidTimeValue"; colvarInvalidTimeValue.DataType = DbType.AnsiString; colvarInvalidTimeValue.MaxLength = 50; colvarInvalidTimeValue.AutoIncrement = false; colvarInvalidTimeValue.IsNullable = true; colvarInvalidTimeValue.IsPrimaryKey = false; colvarInvalidTimeValue.IsForeignKey = false; colvarInvalidTimeValue.IsReadOnly = false; schema.Columns.Add(colvarInvalidTimeValue); TableSchema.TableColumn colvarTimeValueInvalid = new TableSchema.TableColumn(schema); colvarTimeValueInvalid.ColumnName = "TimeValueInvalid"; colvarTimeValueInvalid.DataType = DbType.Int32; colvarTimeValueInvalid.MaxLength = 0; colvarTimeValueInvalid.AutoIncrement = false; colvarTimeValueInvalid.IsNullable = false; colvarTimeValueInvalid.IsPrimaryKey = false; colvarTimeValueInvalid.IsForeignKey = false; colvarTimeValueInvalid.IsReadOnly = false; schema.Columns.Add(colvarTimeValueInvalid); TableSchema.TableColumn colvarValueTime = new TableSchema.TableColumn(schema); colvarValueTime.ColumnName = "ValueTime"; colvarValueTime.DataType = DbType.DateTime; colvarValueTime.MaxLength = 0; colvarValueTime.AutoIncrement = false; colvarValueTime.IsNullable = true; colvarValueTime.IsPrimaryKey = false; colvarValueTime.IsForeignKey = false; colvarValueTime.IsReadOnly = false; schema.Columns.Add(colvarValueTime); TableSchema.TableColumn colvarRawValue = new TableSchema.TableColumn(schema); colvarRawValue.ColumnName = "RawValue"; colvarRawValue.DataType = DbType.Double; colvarRawValue.MaxLength = 0; colvarRawValue.AutoIncrement = false; colvarRawValue.IsNullable = true; colvarRawValue.IsPrimaryKey = false; colvarRawValue.IsForeignKey = false; colvarRawValue.IsReadOnly = false; schema.Columns.Add(colvarRawValue); TableSchema.TableColumn colvarValueText = new TableSchema.TableColumn(schema); colvarValueText.ColumnName = "ValueText"; colvarValueText.DataType = DbType.AnsiString; colvarValueText.MaxLength = 50; colvarValueText.AutoIncrement = false; colvarValueText.IsNullable = false; colvarValueText.IsPrimaryKey = false; colvarValueText.IsForeignKey = false; colvarValueText.IsReadOnly = false; schema.Columns.Add(colvarValueText); TableSchema.TableColumn colvarRawValueInvalid = new TableSchema.TableColumn(schema); colvarRawValueInvalid.ColumnName = "RawValueInvalid"; colvarRawValueInvalid.DataType = DbType.Int32; colvarRawValueInvalid.MaxLength = 0; colvarRawValueInvalid.AutoIncrement = false; colvarRawValueInvalid.IsNullable = false; colvarRawValueInvalid.IsPrimaryKey = false; colvarRawValueInvalid.IsForeignKey = false; colvarRawValueInvalid.IsReadOnly = false; schema.Columns.Add(colvarRawValueInvalid); TableSchema.TableColumn colvarDataValue = new TableSchema.TableColumn(schema); colvarDataValue.ColumnName = "DataValue"; colvarDataValue.DataType = DbType.Double; colvarDataValue.MaxLength = 0; colvarDataValue.AutoIncrement = false; colvarDataValue.IsNullable = true; colvarDataValue.IsPrimaryKey = false; colvarDataValue.IsForeignKey = false; colvarDataValue.IsReadOnly = false; schema.Columns.Add(colvarDataValue); TableSchema.TableColumn colvarTransformValueText = new TableSchema.TableColumn(schema); colvarTransformValueText.ColumnName = "TransformValueText"; colvarTransformValueText.DataType = DbType.AnsiString; colvarTransformValueText.MaxLength = 50; colvarTransformValueText.AutoIncrement = false; colvarTransformValueText.IsNullable = true; colvarTransformValueText.IsPrimaryKey = false; colvarTransformValueText.IsForeignKey = false; colvarTransformValueText.IsReadOnly = false; schema.Columns.Add(colvarTransformValueText); TableSchema.TableColumn colvarDataValueInvalid = new TableSchema.TableColumn(schema); colvarDataValueInvalid.ColumnName = "DataValueInvalid"; colvarDataValueInvalid.DataType = DbType.Int32; colvarDataValueInvalid.MaxLength = 0; colvarDataValueInvalid.AutoIncrement = false; colvarDataValueInvalid.IsNullable = false; colvarDataValueInvalid.IsPrimaryKey = false; colvarDataValueInvalid.IsForeignKey = false; colvarDataValueInvalid.IsReadOnly = false; schema.Columns.Add(colvarDataValueInvalid); TableSchema.TableColumn colvarPhenomenonOfferingID = new TableSchema.TableColumn(schema); colvarPhenomenonOfferingID.ColumnName = "PhenomenonOfferingID"; colvarPhenomenonOfferingID.DataType = DbType.Guid; colvarPhenomenonOfferingID.MaxLength = 0; colvarPhenomenonOfferingID.AutoIncrement = false; colvarPhenomenonOfferingID.IsNullable = true; colvarPhenomenonOfferingID.IsPrimaryKey = false; colvarPhenomenonOfferingID.IsForeignKey = false; colvarPhenomenonOfferingID.IsReadOnly = false; schema.Columns.Add(colvarPhenomenonOfferingID); TableSchema.TableColumn colvarOfferingInvalid = new TableSchema.TableColumn(schema); colvarOfferingInvalid.ColumnName = "OfferingInvalid"; colvarOfferingInvalid.DataType = DbType.Int32; colvarOfferingInvalid.MaxLength = 0; colvarOfferingInvalid.AutoIncrement = false; colvarOfferingInvalid.IsNullable = false; colvarOfferingInvalid.IsPrimaryKey = false; colvarOfferingInvalid.IsForeignKey = false; colvarOfferingInvalid.IsReadOnly = false; schema.Columns.Add(colvarOfferingInvalid); TableSchema.TableColumn colvarPhenomenonUOMID = new TableSchema.TableColumn(schema); colvarPhenomenonUOMID.ColumnName = "PhenomenonUOMID"; colvarPhenomenonUOMID.DataType = DbType.Guid; colvarPhenomenonUOMID.MaxLength = 0; colvarPhenomenonUOMID.AutoIncrement = false; colvarPhenomenonUOMID.IsNullable = true; colvarPhenomenonUOMID.IsPrimaryKey = false; colvarPhenomenonUOMID.IsForeignKey = false; colvarPhenomenonUOMID.IsReadOnly = false; schema.Columns.Add(colvarPhenomenonUOMID); TableSchema.TableColumn colvarUOMInvalid = new TableSchema.TableColumn(schema); colvarUOMInvalid.ColumnName = "UOMInvalid"; colvarUOMInvalid.DataType = DbType.Int32; colvarUOMInvalid.MaxLength = 0; colvarUOMInvalid.AutoIncrement = false; colvarUOMInvalid.IsNullable = false; colvarUOMInvalid.IsPrimaryKey = false; colvarUOMInvalid.IsForeignKey = false; colvarUOMInvalid.IsReadOnly = false; schema.Columns.Add(colvarUOMInvalid); TableSchema.TableColumn colvarPhenomenonName = new TableSchema.TableColumn(schema); colvarPhenomenonName.ColumnName = "PhenomenonName"; colvarPhenomenonName.DataType = DbType.AnsiString; colvarPhenomenonName.MaxLength = 150; colvarPhenomenonName.AutoIncrement = false; colvarPhenomenonName.IsNullable = true; colvarPhenomenonName.IsPrimaryKey = false; colvarPhenomenonName.IsForeignKey = false; colvarPhenomenonName.IsReadOnly = false; schema.Columns.Add(colvarPhenomenonName); TableSchema.TableColumn colvarOfferingName = new TableSchema.TableColumn(schema); colvarOfferingName.ColumnName = "OfferingName"; colvarOfferingName.DataType = DbType.AnsiString; colvarOfferingName.MaxLength = 150; colvarOfferingName.AutoIncrement = false; colvarOfferingName.IsNullable = true; colvarOfferingName.IsPrimaryKey = false; colvarOfferingName.IsForeignKey = false; colvarOfferingName.IsReadOnly = false; schema.Columns.Add(colvarOfferingName); TableSchema.TableColumn colvarUnit = new TableSchema.TableColumn(schema); colvarUnit.ColumnName = "Unit"; colvarUnit.DataType = DbType.AnsiString; colvarUnit.MaxLength = 100; colvarUnit.AutoIncrement = false; colvarUnit.IsNullable = true; colvarUnit.IsPrimaryKey = false; colvarUnit.IsForeignKey = false; colvarUnit.IsReadOnly = false; schema.Columns.Add(colvarUnit); TableSchema.TableColumn colvarDataSourceTransformationID = new TableSchema.TableColumn(schema); colvarDataSourceTransformationID.ColumnName = "DataSourceTransformationID"; colvarDataSourceTransformationID.DataType = DbType.Guid; colvarDataSourceTransformationID.MaxLength = 0; colvarDataSourceTransformationID.AutoIncrement = false; colvarDataSourceTransformationID.IsNullable = true; colvarDataSourceTransformationID.IsPrimaryKey = false; colvarDataSourceTransformationID.IsForeignKey = false; colvarDataSourceTransformationID.IsReadOnly = false; schema.Columns.Add(colvarDataSourceTransformationID); TableSchema.TableColumn colvarTransformation = new TableSchema.TableColumn(schema); colvarTransformation.ColumnName = "Transformation"; colvarTransformation.DataType = DbType.AnsiString; colvarTransformation.MaxLength = 150; colvarTransformation.AutoIncrement = false; colvarTransformation.IsNullable = true; colvarTransformation.IsPrimaryKey = false; colvarTransformation.IsForeignKey = false; colvarTransformation.IsReadOnly = false; schema.Columns.Add(colvarTransformation); TableSchema.TableColumn colvarStatusID = new TableSchema.TableColumn(schema); colvarStatusID.ColumnName = "StatusID"; colvarStatusID.DataType = DbType.Guid; colvarStatusID.MaxLength = 0; colvarStatusID.AutoIncrement = false; colvarStatusID.IsNullable = false; colvarStatusID.IsPrimaryKey = false; colvarStatusID.IsForeignKey = false; colvarStatusID.IsReadOnly = false; schema.Columns.Add(colvarStatusID); TableSchema.TableColumn colvarStatus = new TableSchema.TableColumn(schema); colvarStatus.ColumnName = "Status"; colvarStatus.DataType = DbType.AnsiString; colvarStatus.MaxLength = 150; colvarStatus.AutoIncrement = false; colvarStatus.IsNullable = false; colvarStatus.IsPrimaryKey = false; colvarStatus.IsForeignKey = false; colvarStatus.IsReadOnly = false; schema.Columns.Add(colvarStatus); TableSchema.TableColumn colvarImportBatchID = new TableSchema.TableColumn(schema); colvarImportBatchID.ColumnName = "ImportBatchID"; colvarImportBatchID.DataType = DbType.Guid; colvarImportBatchID.MaxLength = 0; colvarImportBatchID.AutoIncrement = false; colvarImportBatchID.IsNullable = false; colvarImportBatchID.IsPrimaryKey = false; colvarImportBatchID.IsForeignKey = false; colvarImportBatchID.IsReadOnly = false; schema.Columns.Add(colvarImportBatchID); TableSchema.TableColumn colvarRawFieldValue = new TableSchema.TableColumn(schema); colvarRawFieldValue.ColumnName = "RawFieldValue"; colvarRawFieldValue.DataType = DbType.AnsiString; colvarRawFieldValue.MaxLength = 50; colvarRawFieldValue.AutoIncrement = false; colvarRawFieldValue.IsNullable = false; colvarRawFieldValue.IsPrimaryKey = false; colvarRawFieldValue.IsForeignKey = false; colvarRawFieldValue.IsReadOnly = false; schema.Columns.Add(colvarRawFieldValue); TableSchema.TableColumn colvarComment = new TableSchema.TableColumn(schema); colvarComment.ColumnName = "Comment"; colvarComment.DataType = DbType.AnsiString; colvarComment.MaxLength = 250; colvarComment.AutoIncrement = false; colvarComment.IsNullable = true; colvarComment.IsPrimaryKey = false; colvarComment.IsForeignKey = false; colvarComment.IsReadOnly = false; schema.Columns.Add(colvarComment); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("vDataLog",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public VDataLog() { SetSQLProps(); SetDefaults(); MarkNew(); } public VDataLog(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public VDataLog(object keyID) { SetSQLProps(); LoadByKey(keyID); } public VDataLog(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>("ID"); } set { SetColumnValue("ID", value); } } [XmlAttribute("ImportDate")] [Bindable(true)] public DateTime ImportDate { get { return GetColumnValue<DateTime>("ImportDate"); } set { SetColumnValue("ImportDate", value); } } [XmlAttribute("SiteName")] [Bindable(true)] public string SiteName { get { return GetColumnValue<string>("SiteName"); } set { SetColumnValue("SiteName", value); } } [XmlAttribute("StationName")] [Bindable(true)] public string StationName { get { return GetColumnValue<string>("StationName"); } set { SetColumnValue("StationName", value); } } [XmlAttribute("InstrumentName")] [Bindable(true)] public string InstrumentName { get { return GetColumnValue<string>("InstrumentName"); } set { SetColumnValue("InstrumentName", value); } } [XmlAttribute("SensorID")] [Bindable(true)] public Guid? SensorID { get { return GetColumnValue<Guid?>("SensorID"); } set { SetColumnValue("SensorID", value); } } [XmlAttribute("SensorName")] [Bindable(true)] public string SensorName { get { return GetColumnValue<string>("SensorName"); } set { SetColumnValue("SensorName", value); } } [XmlAttribute("SensorInvalid")] [Bindable(true)] public int SensorInvalid { get { return GetColumnValue<int>("SensorInvalid"); } set { SetColumnValue("SensorInvalid", value); } } [XmlAttribute("ValueDate")] [Bindable(true)] public DateTime? ValueDate { get { return GetColumnValue<DateTime?>("ValueDate"); } set { SetColumnValue("ValueDate", value); } } [XmlAttribute("InvalidDateValue")] [Bindable(true)] public string InvalidDateValue { get { return GetColumnValue<string>("InvalidDateValue"); } set { SetColumnValue("InvalidDateValue", value); } } [XmlAttribute("DateValueInvalid")] [Bindable(true)] public int DateValueInvalid { get { return GetColumnValue<int>("DateValueInvalid"); } set { SetColumnValue("DateValueInvalid", value); } } [XmlAttribute("InvalidTimeValue")] [Bindable(true)] public string InvalidTimeValue { get { return GetColumnValue<string>("InvalidTimeValue"); } set { SetColumnValue("InvalidTimeValue", value); } } [XmlAttribute("TimeValueInvalid")] [Bindable(true)] public int TimeValueInvalid { get { return GetColumnValue<int>("TimeValueInvalid"); } set { SetColumnValue("TimeValueInvalid", value); } } [XmlAttribute("ValueTime")] [Bindable(true)] public DateTime? ValueTime { get { return GetColumnValue<DateTime?>("ValueTime"); } set { SetColumnValue("ValueTime", value); } } [XmlAttribute("RawValue")] [Bindable(true)] public double? RawValue { get { return GetColumnValue<double?>("RawValue"); } set { SetColumnValue("RawValue", value); } } [XmlAttribute("ValueText")] [Bindable(true)] public string ValueText { get { return GetColumnValue<string>("ValueText"); } set { SetColumnValue("ValueText", value); } } [XmlAttribute("RawValueInvalid")] [Bindable(true)] public int RawValueInvalid { get { return GetColumnValue<int>("RawValueInvalid"); } set { SetColumnValue("RawValueInvalid", value); } } [XmlAttribute("DataValue")] [Bindable(true)] public double? DataValue { get { return GetColumnValue<double?>("DataValue"); } set { SetColumnValue("DataValue", value); } } [XmlAttribute("TransformValueText")] [Bindable(true)] public string TransformValueText { get { return GetColumnValue<string>("TransformValueText"); } set { SetColumnValue("TransformValueText", value); } } [XmlAttribute("DataValueInvalid")] [Bindable(true)] public int DataValueInvalid { get { return GetColumnValue<int>("DataValueInvalid"); } set { SetColumnValue("DataValueInvalid", value); } } [XmlAttribute("PhenomenonOfferingID")] [Bindable(true)] public Guid? PhenomenonOfferingID { get { return GetColumnValue<Guid?>("PhenomenonOfferingID"); } set { SetColumnValue("PhenomenonOfferingID", value); } } [XmlAttribute("OfferingInvalid")] [Bindable(true)] public int OfferingInvalid { get { return GetColumnValue<int>("OfferingInvalid"); } set { SetColumnValue("OfferingInvalid", value); } } [XmlAttribute("PhenomenonUOMID")] [Bindable(true)] public Guid? PhenomenonUOMID { get { return GetColumnValue<Guid?>("PhenomenonUOMID"); } set { SetColumnValue("PhenomenonUOMID", value); } } [XmlAttribute("UOMInvalid")] [Bindable(true)] public int UOMInvalid { get { return GetColumnValue<int>("UOMInvalid"); } set { SetColumnValue("UOMInvalid", value); } } [XmlAttribute("PhenomenonName")] [Bindable(true)] public string PhenomenonName { get { return GetColumnValue<string>("PhenomenonName"); } set { SetColumnValue("PhenomenonName", value); } } [XmlAttribute("OfferingName")] [Bindable(true)] public string OfferingName { get { return GetColumnValue<string>("OfferingName"); } set { SetColumnValue("OfferingName", value); } } [XmlAttribute("Unit")] [Bindable(true)] public string Unit { get { return GetColumnValue<string>("Unit"); } set { SetColumnValue("Unit", value); } } [XmlAttribute("DataSourceTransformationID")] [Bindable(true)] public Guid? DataSourceTransformationID { get { return GetColumnValue<Guid?>("DataSourceTransformationID"); } set { SetColumnValue("DataSourceTransformationID", value); } } [XmlAttribute("Transformation")] [Bindable(true)] public string Transformation { get { return GetColumnValue<string>("Transformation"); } set { SetColumnValue("Transformation", value); } } [XmlAttribute("StatusID")] [Bindable(true)] public Guid StatusID { get { return GetColumnValue<Guid>("StatusID"); } set { SetColumnValue("StatusID", value); } } [XmlAttribute("Status")] [Bindable(true)] public string Status { get { return GetColumnValue<string>("Status"); } set { SetColumnValue("Status", value); } } [XmlAttribute("ImportBatchID")] [Bindable(true)] public Guid ImportBatchID { get { return GetColumnValue<Guid>("ImportBatchID"); } set { SetColumnValue("ImportBatchID", value); } } [XmlAttribute("RawFieldValue")] [Bindable(true)] public string RawFieldValue { get { return GetColumnValue<string>("RawFieldValue"); } set { SetColumnValue("RawFieldValue", value); } } [XmlAttribute("Comment")] [Bindable(true)] public string Comment { get { return GetColumnValue<string>("Comment"); } set { SetColumnValue("Comment", value); } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string ImportDate = @"ImportDate"; public static string SiteName = @"SiteName"; public static string StationName = @"StationName"; public static string InstrumentName = @"InstrumentName"; public static string SensorID = @"SensorID"; public static string SensorName = @"SensorName"; public static string SensorInvalid = @"SensorInvalid"; public static string ValueDate = @"ValueDate"; public static string InvalidDateValue = @"InvalidDateValue"; public static string DateValueInvalid = @"DateValueInvalid"; public static string InvalidTimeValue = @"InvalidTimeValue"; public static string TimeValueInvalid = @"TimeValueInvalid"; public static string ValueTime = @"ValueTime"; public static string RawValue = @"RawValue"; public static string ValueText = @"ValueText"; public static string RawValueInvalid = @"RawValueInvalid"; public static string DataValue = @"DataValue"; public static string TransformValueText = @"TransformValueText"; public static string DataValueInvalid = @"DataValueInvalid"; public static string PhenomenonOfferingID = @"PhenomenonOfferingID"; public static string OfferingInvalid = @"OfferingInvalid"; public static string PhenomenonUOMID = @"PhenomenonUOMID"; public static string UOMInvalid = @"UOMInvalid"; public static string PhenomenonName = @"PhenomenonName"; public static string OfferingName = @"OfferingName"; public static string Unit = @"Unit"; public static string DataSourceTransformationID = @"DataSourceTransformationID"; public static string Transformation = @"Transformation"; public static string StatusID = @"StatusID"; public static string Status = @"Status"; public static string ImportBatchID = @"ImportBatchID"; public static string RawFieldValue = @"RawFieldValue"; public static string Comment = @"Comment"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using DeOps.Implementation.Protocol; using DeOps.Implementation.Protocol.Net; using DeOps.Implementation.Transport; using DeOps.Services.Location; namespace DeOps.Implementation.Dht { public delegate void SearchRequestHandler(ulong key, byte[] parameters, List<byte[]> values); public class DhtSearchControl { const int MAX_SEARCHES = 5; //super-class public OpCore Core; public DhtNetwork Network; public DhtRouting Routing; public List<DhtSearch> Pending = new List<DhtSearch>(); public List<DhtSearch> Active = new List<DhtSearch>(); public ServiceEvent<SearchRequestHandler> SearchEvent = new ServiceEvent<SearchRequestHandler>(); public DhtSearchControl(DhtNetwork network) { Network = network; Core = Network.Core; Routing = network.Routing; } public void SecondTimer() { // get active search count int searchCount = 0; lock (Active) foreach (DhtSearch search in Active) if (search.ProxyTcp == null || search.ProxyTcp.Proxy == ProxyType.Server) searchCount++; // if pending searches if (Network.Responsive) // only move from pending to active if network responsive while( searchCount < MAX_SEARCHES && Pending.Count > 0) { DhtSearch move = Pending[0]; searchCount++; // do here to get out of loop if (move.Activate()) { move.Log("Active"); Active.Add(move); Pending.Remove(move); } } // pulse active searches List<DhtSearch> removeList = new List<DhtSearch>(); lock (Active) foreach (DhtSearch search in Active) { if (search.Finished) removeList.Add(search); else search.SecondTimer(); } // remove finished searches foreach (DhtSearch search in removeList) { if (Active.Contains(search)) lock (Active) Active.Remove(search); if (Pending.Contains(search)) lock (Pending) Pending.Remove(search); string log = "Finished"; if (search.FoundValues.Count > 0) log += ", " + search.FoundValues.Count.ToString() + " Values Found"; if (search.FinishReason != null) log += ", " + search.FinishReason; search.Log(log); } } public DhtSearch Start(ulong key, string name, uint service, uint datatype, byte[] parameters, Action<DhtSearch, DhtAddress, byte[]> found) { if (Core.InvokeRequired) Debug.Assert(false); // transfer componenent does its own duplicate checks // also there can exist multiple transfers with with same trar if (Core.Transfers == null || service != Core.Transfers.ServiceID) { foreach (DhtSearch pending in Pending) if (pending.TargetID == key && pending.Service == service && Utilities.MemCompare(parameters, pending.Parameters)) return null; foreach (DhtSearch active in Active) if (active.TargetID == key && active.Service == service && Utilities.MemCompare(parameters, active.Parameters)) return null; } DhtSearch search = new DhtSearch(this, key, name, service, datatype); search.FoundEvent = found; search.Parameters = parameters; search.Log("Pending"); Pending.Add(search); return search; } public void SendRequest(DhtAddress address, UInt64 targetID, uint searchID, uint service, uint datatype, byte[] parameters) { SearchReq request = new SearchReq(); request.Source = Network.GetLocalSource(); request.SearchID = searchID; request.TargetID = targetID; request.Service = service; request.DataType = datatype; request.Parameters = parameters; int sentBytes = 0; TcpConnect direct = Network.TcpControl.GetProxy(address); if (direct != null) sentBytes = direct.SendPacket(request); else sentBytes = Network.SendPacket(address, request); Core.ServiceBandwidth[request.Service].OutPerSec += sentBytes; } public void ReceiveRequest(G2ReceivedPacket packet) { SearchReq request = SearchReq.Decode(packet); // loopback if (Network.Local.Equals(request.Source)) return; if (Core.ServiceBandwidth.ContainsKey(request.Service)) Core.ServiceBandwidth[request.Service].InPerSec += packet.Root.Data.Length; if (packet.ReceivedTcp && request.SearchID != 0) { // request from blocked node if (packet.Tcp.Proxy == ProxyType.ClientBlocked) { int proxySearches = 0; lock (Active) foreach (DhtSearch search in Active) if (search.ProxyTcp == packet.Tcp) { proxySearches++; if (request.EndProxySearch && search.SearchID == request.SearchID) { search.FinishSearch("Proxied node finished search"); return; } } if (proxySearches < MAX_SEARCHES) { DhtSearch search = new DhtSearch(this, request.TargetID, "Proxy", request.Service, request.DataType); search.Parameters = request.Parameters; search.ProxyTcp = packet.Tcp; search.SearchID = request.SearchID; search.Activate(); Active.Add(search); search.Log("Active - Proxy Search"); } // continue processing request and send local results } // request from proxy server if (packet.Tcp.Proxy == ProxyType.Server && request.EndProxySearch) { lock (Active) foreach (DhtSearch search in Active) if (search.SearchID == request.SearchID) if( !search.Finished ) search.FinishSearch("Server finished search"); } } if (request.Source.Firewall == FirewallType.Open) Routing.Add(new DhtContact(request.Source, packet.Source.IP)); // forward to proxied nodes foreach (TcpConnect socket in Network.TcpControl.ProxyClients) // prevents incoming udp from proxy and being forwarded to same host tcp if(socket != packet.Tcp && !(packet.Source.UserID == socket.UserID && packet.Source.ClientID == socket.ClientID)) { request.FromAddress = packet.Source; socket.SendPacket(request); } // send ack bool sendNoResults = (request.SearchID != 0 || request.Service == Core.DhtServiceID) && (packet.ReceivedUdp || packet.Tunneled); SearchAck ack = new SearchAck(); ack.Source = Network.GetLocalSource(); ack.SearchID = request.SearchID; ack.Service = request.Service; // search for connected proxy if (Network.TcpControl.ProxyMap.Values.Any(p => p.UserID == request.TargetID)) ack.Proxied = true; // only send nodes from proxy server routing table if (request.Nodes && (packet.ReceivedUdp || packet.Tunneled)) ack.ContactList = Routing.Find(request.TargetID, 8); // dont send an ack if behind a proxy server and no results if (!SearchEvent.Contains(request.Service, request.DataType)) { if (sendNoResults) SendAck(packet, request, ack); } else { List<byte[]> results = new List<byte[]>(); SearchEvent[request.Service, request.DataType].Invoke(request.TargetID, request.Parameters, results); // if nothing found, still send ack with closer contacts if (results == null || results.Count == 0) { if (sendNoResults) SendAck(packet, request, ack); return; } // if a direct search if (request.SearchID == 0) { foreach(byte[] value in results) Network.Store.Send_StoreReq(packet.Source, packet.Tcp, new DataReq(null, request.TargetID, request.Service, request.DataType, value)); return; } // else send normal search results int totalSize = 0; foreach (byte[] data in results) { if (data.Length + totalSize > 1200) { SendAck(packet, request, ack); ack.ValueList.Clear(); ack.ContactList.Clear(); // dont send twice totalSize = 0; } ack.ValueList.Add(data); totalSize += data.Length; } if(totalSize > 0) SendAck(packet, request, ack); } } private void SendAck(G2ReceivedPacket packet, SearchReq request, SearchAck ack) { // if request came in tcp, send back tcp - scenario happens in these situations // req u-> open t-> fw ack t-> open u-> remote // fw req t-> open ack t-> fw // fw1 req t-> open t-> fw2 ack t-> open t-> fw1 int bytesSent = 0; if (packet.ReceivedTcp) { ack.ToAddress = packet.Source; bytesSent = packet.Tcp.SendPacket(ack); } else bytesSent = Network.SendPacket(packet.Source, ack); Core.ServiceBandwidth[ack.Service].OutPerSec += bytesSent; } public void ReceiveAck(G2ReceivedPacket packet) { SearchAck ack = SearchAck.Decode(packet); // loopback if (Network.Local.Equals(ack.Source)) return; if (Core.ServiceBandwidth.ContainsKey(ack.Service)) Core.ServiceBandwidth[ack.Service].InPerSec += packet.Root.Data.Length; if (ack.Source.Firewall == FirewallType.Open) Routing.Add(new DhtContact(ack.Source, packet.Source.IP)); foreach (DhtContact contact in ack.ContactList) Routing.Add(contact); // function calls back into seach system, adding closer nodes // if response to initial pong or crawl if (ack.SearchID == 0) { Core.RunInGuiThread(Network.CrawlerSearchAck, ack, packet); return; } // mark searches as done lock (Active) foreach (DhtSearch search in Active) if (search.SearchID == ack.SearchID) { foreach (DhtLookup lookup in search.LookupList) if (lookup.Contact.UserID == ack.Source.UserID && lookup.Contact.ClientID == ack.Source.ClientID) lookup.Status = LookupStatus.Done; if (search.ProxyTcp != null && search.ProxyTcp.Proxy == ProxyType.ClientBlocked) { ack.FromAddress = packet.Source; search.ProxyTcp.SendPacket(ack); return; } foreach (byte[] value in ack.ValueList) search.Found(value, packet.Source); if (ack.Proxied) search.Found(new DhtContact(ack.Source, packet.Source.IP), true); if (!search.Finished && search.FoundValues.Count > search.TargetResults) search.FinishSearch("Max Values Found"); } } public void Stop(UInt64 id) { lock (Pending) foreach (DhtSearch search in Pending) if (search.TargetID == id) { Pending.Remove(search); break; } lock (Active) foreach (DhtSearch search in Active) if (search.TargetID == id) { Active.Remove(search); search.Log("Stopped"); break; } } // sends a direct request, no acks are returned, if host has what is requested it sends a store request as a reply // make sure whatevers calling this handles the resulting store request public void SendDirectRequest(DhtAddress dest, ulong target, uint service, uint datatype, byte[] parameters) { SearchReq request = new SearchReq(); request.Source = Network.GetLocalSource(); request.TargetID = target; request.Service = service; request.DataType = datatype; request.Parameters = parameters; request.Nodes = false; int sentBytes = 0; TcpConnect socket = Network.TcpControl.GetProxy(dest); if (socket != null) sentBytes = socket.SendPacket(request); else if (dest.TunnelClient != null) sentBytes = Network.SendTunnelPacket(dest, request); else if (Core.Firewall == FirewallType.Blocked) { request.ToAddress = dest; sentBytes = Network.TcpControl.SendRandomProxy(request); } else sentBytes = Network.UdpControl.SendTo(dest, request); Core.ServiceBandwidth[request.Service].OutPerSec += sentBytes; // if remote end has what we need they will send us a store request } } }
/* * 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 platfrom = Environment.Is64BitProcess ? "x64" : "x86"; var resName = string.Format("{0}.{1}", platfrom, IgniteUtils.FileIgniteJniDll); var path = IgniteUtils.UnpackEmbeddedResource(resName, IgniteUtils.FileIgniteJniDll); var ptr = NativeMethods.LoadLibrary(path); if (ptr == IntPtr.Zero) throw new IgniteException(string.Format("Failed to load {0}: {1}", IgniteUtils.FileIgniteJniDll, Marshal.GetLastWin32Error())); 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 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); } #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); } internal static bool ListenableCancel(IUnmanagedTarget target) { return JNI.ListenableCancel(target.Context, target.Target); } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Configuration.ConfigurationElement.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Configuration { abstract public partial class ConfigurationElement { #region Methods and constructors protected ConfigurationElement () { } protected internal virtual new void DeserializeElement (System.Xml.XmlReader reader, bool serializeCollectionKey) { Contract.Requires(reader != null); } public override bool Equals (Object compareTo) { return default(bool); } public override int GetHashCode () { return default(int); } #if NETFRAMEWORK_4_0 protected virtual new string GetTransformedAssemblyString (string assemblyName) { return default(string); } protected virtual new string GetTransformedTypeString (string typeName) { return default(string); } #endif protected internal virtual new void Init () { } protected internal virtual new void InitializeDefault () { } protected internal virtual new bool IsModified () { return default(bool); } public virtual new bool IsReadOnly () { return default(bool); } protected virtual new void ListErrors (System.Collections.IList errorList) { Contract.Requires(errorList != null); } protected virtual new bool OnDeserializeUnrecognizedAttribute (string name, string value) { Contract.Requires(name != null); return default(bool); } protected virtual new bool OnDeserializeUnrecognizedElement (string elementName, System.Xml.XmlReader reader) { Contract.Requires(elementName != null); Contract.Requires(reader != null); return default(bool); } protected virtual new Object OnRequiredPropertyNotFound (string name) { Contract.Requires(name != null); return default(Object); } protected virtual new void PostDeserialize () { } protected virtual new void PreSerialize (System.Xml.XmlWriter writer) { Contract.Requires(writer != null); } protected internal virtual new void Reset (System.Configuration.ConfigurationElement parentElement) { } protected internal virtual new void ResetModified () { } protected internal virtual new bool SerializeElement (System.Xml.XmlWriter writer, bool serializeCollectionKey) { Contract.Requires(writer != null); return default(bool); } protected internal virtual new bool SerializeToXmlElement (System.Xml.XmlWriter writer, string elementName) { Contract.Requires(writer != null); Contract.Requires(elementName != null); return default(bool); } protected void SetPropertyValue (ConfigurationProperty prop, Object value, bool ignoreLocks) { Contract.Requires(prop != null); } protected internal virtual new void SetReadOnly () { } protected internal virtual new void Unmerge (System.Configuration.ConfigurationElement sourceElement, System.Configuration.ConfigurationElement parentElement, ConfigurationSaveMode saveMode) { Contract.Requires(sourceElement != null); } #endregion #region Properties and indexers #if NETFRAMEWORK_4_0 public Configuration CurrentConfiguration { get { return default(Configuration); } } #endif public ElementInformation ElementInformation { get { Contract.Ensures(Contract.Result<ElementInformation>() != null); return default(ElementInformation); } } internal protected virtual new ConfigurationElementProperty ElementProperty { get { Contract.Ensures(Contract.Result<ConfigurationElementProperty>() != null); return default(ConfigurationElementProperty); } } protected ContextInformation EvaluationContext { get { Contract.Ensures(Contract.Result<ContextInformation>() != null); return default(ContextInformation); } } internal protected Object this [ConfigurationProperty prop] { get { Contract.Requires(prop != null); return default(Object); } set { Contract.Requires(prop != null); } } internal protected Object this [string propertyName] { get { return default(Object); } set { } } public ConfigurationLockCollection LockAllAttributesExcept { get { Contract.Ensures(Contract.Result<ConfigurationLockCollection>() != null); return default(ConfigurationLockCollection); } } public ConfigurationLockCollection LockAllElementsExcept { get { Contract.Ensures(Contract.Result<ConfigurationLockCollection>() != null); return default(ConfigurationLockCollection); } } public ConfigurationLockCollection LockAttributes { get { Contract.Ensures(Contract.Result<ConfigurationLockCollection>() != null); return default(ConfigurationLockCollection); } } public ConfigurationLockCollection LockElements { get { Contract.Ensures(Contract.Result<ConfigurationLockCollection>() != null); return default(ConfigurationLockCollection); } } public bool LockItem { get { return default(bool); } set { } } internal protected virtual new ConfigurationPropertyCollection Properties { get { return default(ConfigurationPropertyCollection); } } #endregion } }
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * What is this file about? * * Revision history: * Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here * xxxx-xx-xx, author, fix bug about xxx */ using System; using System.Collections.Generic; using System.IO; namespace rDSN.Tron.Contract { public enum ConsistencyLevel { Any, Eventual, Causal, Strong // Primary-backup or Quorum } public enum PartitionType { None, Fixed, Dynamic } public class ServiceProperty { /// <summary> /// whether the service needs to be deployed by our infrastructure, or it is an existing service that we can invoke directly /// </summary> public bool? IsDeployedAlready { get; set; } /// <summary> /// whether the service is a primtive service or a service composed in TRON /// </summary> public bool? IsPrimitive { get; set; } /// <summary> /// whether the service is partitioned and will be deployed on multiple machines /// </summary> public bool? IsPartitioned { get; set; } /// <summary> /// whether the service is stateful or stateless. A stateless service can lose its state safely. /// </summary> public bool? IsStateful { get; set; } /// <summary> /// whether the service is replicated (multiple copies) /// </summary> public bool? IsReplicated { get; set; } } /// <summary> /// service description /// </summary> public class Service { public Service(string package, string url, string name = "") { PackageName = package; URL = url; Name = !string.IsNullOrEmpty(name) ? name : url; Properties = new ServiceProperty(); Spec = new ServiceSpec(); } /// <summary> /// package name for this service (the package is published and stored in a service store) /// with the package, the service can be deployed with a deployment service /// </summary> public string PackageName { get; private set; } /// <summary> /// universal remote link for the service, which is used for service address resolve /// example: http://service-manager-url/service-name /// </summary> public string URL { get; private set; } /// <summary> /// service name for print and RPC resolution (e.g., service-name.method-name for invoking a RPC) /// </summary> public string Name { get; private set; } /// <summary> /// service properties /// </summary> public ServiceProperty Properties { get; set; } /// <summary> /// spec info /// </summary> public ServiceSpec Spec { get; private set; } public string TypeName () { return (GetType().Namespace + "." + GetType().Name.Substring("Service_".Length)); } public string PlainTypeName () { return TypeName().Replace('.', '_'); } public ServiceSpec ExtractSpec() { if (Spec.Directory != "") return Spec; Spec.Directory = "."; var files = new List<string> {Spec.MainSpecFile}; files.AddRange(Spec.ReferencedSpecFiles); foreach (var f in files) { if (File.Exists(Path.Combine(Spec.Directory, f))) continue; var stream = GetType().Assembly.GetManifestResourceStream(f); using (Stream file = File.Create(Path.Combine(Spec.Directory, f))) { int len; var buffer = new byte[8 * 1024]; while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) { file.Write(buffer, 0, len); } } } return Spec; } } public class PrimitiveService { public PrimitiveService(string name, string classFullName, string classShortName) { Name = name; ServiceClassFullName = classFullName; ServiceClassShortName = classShortName; ReadConsistency = ConsistencyLevel.Any; WriteConsistency = ConsistencyLevel.Any; PartitionKey = null; PartitionType = PartitionType.None; PartitionCount = 1; } protected PrimitiveService Replicate( int minDegree, int maxDegree, ConsistencyLevel readConsistency = ConsistencyLevel.Any, ConsistencyLevel writeConsistency = ConsistencyLevel.Any ) { ReplicateMinDegree = minDegree; ReplicateMaxDegree = maxDegree; ReadConsistency = readConsistency; WriteConsistency = writeConsistency; return this; } protected PrimitiveService Partition(Type key, PartitionType type, int partitionCount = 1) { PartitionKey = key; PartitionType = type; PartitionCount = partitionCount; return this; } protected PrimitiveService SetDataSource(string dataSource) // e.g., cosmos structured stream { DataSource = dataSource; return this; } protected PrimitiveService SetConfiguration(string uri) { Configuration = uri; return this; } public Type PartitionKey { get; private set; } public PartitionType PartitionType { get; private set; } public int PartitionCount { get; private set; } public int ReplicateMinDegree { get; private set; } public int ReplicateMaxDegree { get; private set; } public ConsistencyLevel ReadConsistency { get; private set; } public ConsistencyLevel WriteConsistency { get; private set; } public string DataSource { get; private set; } public string Configuration { get; private set; } public string Name { get; private set; } public string ServiceClassFullName { get; private set; } public string ServiceClassShortName { get; private set; } } public class PrimitiveService<TSelf> : PrimitiveService where TSelf : PrimitiveService<TSelf> { public PrimitiveService(string name, string classFullName) : base(name, classFullName, classFullName.Substring(classFullName.LastIndexOfAny(new[]{':', '.'}) + 1)) { } public new TSelf Replicate( int minDegree, int maxDegree, ConsistencyLevel readConsistency = ConsistencyLevel.Any, ConsistencyLevel writeConsistency = ConsistencyLevel.Any ) { return base.Replicate(minDegree, maxDegree, readConsistency, writeConsistency) as TSelf; } public new TSelf Partition(Type key, PartitionType type = PartitionType.Dynamic, int partitionCount = 1) { return base.Partition(key, type, partitionCount) as TSelf; } public TSelf DataSource(string dataSource) // e.g., cosmos structured stream { return SetDataSource(dataSource) as TSelf; } public TSelf Configuration(string uri) { return SetConfiguration(uri) as TSelf; } } public class SLA { public enum Metric { Latency99Percentile, Latency95Percentile, Latency90Percentile, Latency50Percentile, WorkflowConsistency } public enum WorkflowConsistencyLevel { Any, Atomic, ACID } public SLA Add<TValue>(Metric prop, TValue value) { return Add(prop, value.ToString()); } public SLA Add(Metric prop, string value) { m_properties.Add(prop, value); return this; } public string Get(Metric prop) { string v; m_properties.TryGetValue(prop, out v); return v; } private Dictionary<Metric, string> m_properties = new Dictionary<Metric, string>(); } }
using BulletML.Enums; using BulletML.Nodes; using NUnit.Framework; using Tests.Utils; namespace Tests.Task.FireTask { [TestFixture()] [Category("TaskTest")] [Category("FireTaskTest")] public class FireTaskSpeedTest { [SetUp] public void SetupHarness() { TestUtils.Initialize(); } [Test] public void BulletCreated() { var filename = TestUtils.GetFilePath(@"Content\FireSpeed.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.InitTopNode(TestUtils.Pattern.RootNode); mover.Speed = 100; TestUtils.Manager.Update(); Assert.AreEqual(TestUtils.Manager.Movers.Count, 2); } [Test] public void BulletDefaultSpeed() { var filename = TestUtils.GetFilePath(@"Content\FireActionEmpty.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.InitTopNode(TestUtils.Pattern.RootNode); var myTask = mover.Tasks[0]; var fireTask = myTask.ChildTasks[0] as BulletML.Tasks.FireTask; Assert.IsNotNull(fireTask); Assert.IsNull(fireTask.SpeedTask); Assert.IsNull(fireTask.DirectionTask); } [Test] public void BulletDefaultSpeed1() { var filename = TestUtils.GetFilePath(@"Content\FireActionEmpty.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.InitTopNode(TestUtils.Pattern.RootNode); mover.Speed = 100.0f; var myTask = mover.Tasks[0]; var fireTask = myTask.ChildTasks[0] as BulletML.Tasks.FireTask; Assert.IsNotNull(fireTask); var fireTask2 = new BulletML.Tasks.FireTask(fireTask.Node as FireNode, fireTask); fireTask2.InitTask(mover); Assert.IsNull(fireTask2.SpeedTask); Assert.IsNull(fireTask2.DirectionTask); Assert.AreEqual(100.0f, fireTask2.FireSpeed); } [Test] public void BulletDefaultSpeed2() { var filename = TestUtils.GetFilePath(@"Content\FireActionEmpty.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.Speed = 100; mover.InitTopNode(TestUtils.Pattern.RootNode); TestUtils.Manager.Update(); var bullet = TestUtils.Manager.Movers[1]; Assert.AreEqual(100.0f, bullet.Speed); } [Test] public void SpeedDefault() { var filename = TestUtils.GetFilePath(@"Content\FireSpeed.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.Speed = 100; mover.InitTopNode(TestUtils.Pattern.RootNode); TestUtils.Manager.Update(); var bullet = TestUtils.Manager.Movers[1]; Assert.AreEqual(5.0f, bullet.Speed); } [Test] public void AbsSpeedDefault() { var filename = TestUtils.GetFilePath(@"Content\FireSpeedAbsolute.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.InitTopNode(TestUtils.Pattern.RootNode); mover.Speed = 100; TestUtils.Manager.Update(); var bullet = TestUtils.Manager.Movers[1]; Assert.AreEqual(5.0f, bullet.Speed); } [Test] public void RelSpeedDefault() { var filename = TestUtils.GetFilePath(@"Content\FireSpeedRelative.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.Speed = 100; mover.InitTopNode(TestUtils.Pattern.RootNode); TestUtils.Manager.Update(); var myTask = mover.Tasks[0]; var fireTask = myTask.ChildTasks[0] as BulletML.Tasks.FireTask; Assert.IsNotNull(fireTask); Assert.AreEqual(105.0f, fireTask.FireSpeed); } [Test] public void RelSpeedDefault1() { var filename = TestUtils.GetFilePath(@"Content\FireSpeedRelative.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.Speed = 100; mover.InitTopNode(TestUtils.Pattern.RootNode); TestUtils.Manager.Update(); var bullet = TestUtils.Manager.Movers[1]; Assert.AreEqual(105.0f, bullet.Speed); } [Test] public void RightInitSpeed() { var filename = TestUtils.GetFilePath(@"Content\FireSpeedBulletSpeed.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.InitTopNode(TestUtils.Pattern.RootNode); mover.Speed = 100; TestUtils.Manager.Update(); var bullet = TestUtils.Manager.Movers[1]; Assert.AreEqual(5.0f, bullet.Speed); } [Test] public void IgnoreSequenceInitSpeed1() { var filename = TestUtils.GetFilePath(@"Content\FireSpeedSequence.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.InitTopNode(TestUtils.Pattern.RootNode); mover.Speed = 100; var myTask = mover.Tasks[0]; var fireTask = myTask.ChildTasks[0] as BulletML.Tasks.FireTask; Assert.IsNotNull(fireTask); Assert.AreEqual(NodeType.sequence, fireTask.SpeedTask.Node.NodeType); } [Test] public void IgnoreSequenceInitSpeed2() { var filename = TestUtils.GetFilePath(@"Content\FireSpeedSequence.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.InitTopNode(TestUtils.Pattern.RootNode); mover.Speed = 100; var myTask = mover.Tasks[0]; var fireTask = myTask.ChildTasks[0] as BulletML.Tasks.FireTask; Assert.IsNotNull(fireTask); Assert.IsNotNull(fireTask.SpeedTask); Assert.AreEqual(NodeType.sequence, fireTask.SpeedTask.Node.NodeType); Assert.AreEqual(100.0f, mover.Speed); Assert.AreEqual(5.0f, fireTask.SpeedTask.Node.GetValue(fireTask)); } [Test] public void IgnoreSequenceInitSpeed3() { var filename = TestUtils.GetFilePath(@"Content\FireSpeedSequence.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.Speed = 100; mover.InitTopNode(TestUtils.Pattern.RootNode); var myTask = mover.Tasks[0]; var fireTask = myTask.ChildTasks[0] as BulletML.Tasks.FireTask; Assert.IsNotNull(fireTask); Assert.AreEqual(105f, fireTask.FireSpeed); } [Test] public void IgnoreSequenceInitSpeed4() { var filename = TestUtils.GetFilePath(@"Content\FireSpeedSequence.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.Speed = 100; mover.InitTopNode(TestUtils.Pattern.RootNode); TestUtils.Manager.Update(); var testDude = TestUtils.Manager.Movers[1]; Assert.AreEqual(105f, testDude.Speed); } [Test] public void FireAbsSpeed() { var filename = TestUtils.GetFilePath(@"Content\FireSpeedAbsolute.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.Speed = 100; mover.InitTopNode(TestUtils.Pattern.RootNode); TestUtils.Manager.Update(); var bullet = TestUtils.Manager.Movers[1]; Assert.AreEqual(5.0f, bullet.Speed); } [Test] public void FireRelSpeed() { var filename = TestUtils.GetFilePath(@"Content\FireSpeedRelative.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.Speed = 100; mover.InitTopNode(TestUtils.Pattern.RootNode); TestUtils.Manager.Update(); var bullet = TestUtils.Manager.Movers[1]; Assert.AreEqual(105.0f, bullet.Speed); } [Test] public void NestedBullets() { var filename = TestUtils.GetFilePath(@"Content\NestedBulletsSpeed.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.InitTopNode(TestUtils.Pattern.RootNode); TestUtils.Manager.Update(); // Test the second bullet var bullet = TestUtils.Manager.Movers[1]; Assert.AreEqual(10.0f, bullet.Speed); } [Test] public void NestedBullets1() { var filename = TestUtils.GetFilePath(@"Content\NestedBulletsSpeed.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.InitTopNode(TestUtils.Pattern.RootNode); TestUtils.Manager.Update(); Assert.AreEqual(3, TestUtils.Manager.Movers.Count); } [Test] public void NestedBullets2() { var filename = TestUtils.GetFilePath(@"Content\NestedBulletsSpeed.xml"); TestUtils.Pattern.Parse(filename); var mover = (Mover)TestUtils.Manager.CreateBullet(); mover.InitTopNode(TestUtils.Pattern.RootNode); TestUtils.Manager.Update(); // Test the second bullet var bullet = TestUtils.Manager.Movers[2]; Assert.AreEqual(20.0f, bullet.Speed); } } }
//----------------------------------------------------------------------- // <copyright file="ReverseArrowSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.TestKit; using FluentAssertions; using Microsoft.CSharp.RuntimeBinder; using Xunit; // ReSharper disable InvokeAsExtensionMethod namespace Akka.Streams.Tests.Dsl { public class ReverseArrowSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public ReverseArrowSpec() { var settings = ActorMaterializerSettings.Create(Sys); Materializer = ActorMaterializer.Create(Sys, settings); } private static Task<IImmutableList<int>> MaterializedValue => Task.FromResult<IImmutableList<int>>(ImmutableList<int>.Empty); private static Source<int, Task<IImmutableList<int>>> Source => Streams.Dsl.Source.From(Enumerable.Range(1, 3)).MapMaterializedValue(_ => MaterializedValue); private static Sink<int, Task<IImmutableList<int>>> Sink => Flow.Create<int>().Limit(10).ToMaterialized(Streams.Dsl.Sink.Seq<int>(), Keep.Right); [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_from_Inlets() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { b.To(s.Inlet).From(Source); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] {1, 2, 3}); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_from_SinkShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { b.To(s).From(Source); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_from_Sink() { var sub = this.CreateManualSubscriberProbe<int>(); RunnableGraph.FromGraph(GraphDsl.Create(b => { b.To(Streams.Dsl.Sink.FromSubscriber(sub)) .From(Streams.Dsl.Source.From(Enumerable.Range(1, 3))); return ClosedShape.Instance; })).Run(Materializer); sub.ExpectSubscription().Request(10); sub.ExpectNext(1, 2, 3); sub.ExpectComplete(); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_not_work_from_Outlets() { RunnableGraph.FromGraph( GraphDsl.Create(b => { var o = b.Add(Source).Outlet; b.Invoking(builder => ((dynamic) builder).To(o).From(Source)) .ShouldThrow<RuntimeBinderException>(); b.To(Sink).From(o); return ClosedShape.Instance; })); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_not_work_from_SourceShape() { RunnableGraph.FromGraph( GraphDsl.Create(b => { var o = b.Add(Source); b.Invoking(builder => ((dynamic) builder).To(o).From(Source)) .ShouldThrow<RuntimeBinderException>(); b.To(Sink).From(o); return ClosedShape.Instance; })); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_not_work_from_Source() { var b = new GraphDsl.Builder<NotUsed>(); b.Invoking(builder => ((dynamic) builder).To(Source).From(Source)).ShouldThrow<RuntimeBinderException>(); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_from_FlowShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { var f = b.Add(Flow.Create<int>()); b.To(f).From(Source); b.From(f).To(s); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_from_UniformFanInShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { var f = b.Add(new Merge<int, int>(2)); b.To(f).From(Source); b.To(f).From(Streams.Dsl.Source.Empty<int>().MapMaterializedValue(_ => MaterializedValue)); b.From(f).To(s); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_from_UniformFanOutShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { var f = b.Add(new Broadcast<int>(2)); b.To(f).From(Source); b.From(f).To(Streams.Dsl.Sink.Ignore<int>().MapMaterializedValue(_ => MaterializedValue)); b.From(f).To(s); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_towards_Outlets() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { var o = b.Add(Source).Outlet; b.To(s).From(o); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_towards_SourceShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { var o = b.Add(Source); b.To(s).From(o); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_towards_Source() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { b.To(s).From(Source); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_towards_FlowShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { var f = b.Add(Flow.Create<int>()); b.To(s).From(f); b.From(Source).To(f); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_towards_UniformFanInShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { var f = b.Add(new Merge<int, int>(2)); b.To(s).From(f); b.From(Streams.Dsl.Source.Empty<int>().MapMaterializedValue(_ => MaterializedValue)).To(f); b.From(Source).To(f); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_fail_towards_already_full_UniformFanInShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { var f = b.Add(new Merge<int, int>(2)); var src = b.Add(Source); b.From(Streams.Dsl.Source.Empty<int>().MapMaterializedValue(_ => MaterializedValue)).To(f); b.From(src).To(f); b.Invoking(builder => builder.To(s).Via(f).From(src)) .ShouldThrow<ArgumentException>() .WithMessage("No more inlets on junction"); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_towards_UniformFanOutShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { var f = b.Add(new Broadcast<int>(2)); b.To(s).From(f); b.To(Streams.Dsl.Sink.Ignore<int>().MapMaterializedValue(_ => MaterializedValue)).From(f); b.From(Source).To(f); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_fail_towards_already_full_UniformFanOutShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { var f = b.Add(new Broadcast<int>(2)); var sink2 = b.Add(Streams.Dsl.Sink.Ignore<int>().MapMaterializedValue(_ => MaterializedValue)); var src = b.Add(Source); b.From(src).To(f); b.To(sink2).From(f); b.Invoking(builder => builder.To(s).Via(f).From(src)) .ShouldThrow<ArgumentException>() .WithMessage("The output port [StatefulSelectMany.out] is already connected"); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_across_a_Flow() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { b.To(s).Via(Flow.Create<int>().MapMaterializedValue(_ => MaterializedValue)).From(Source); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } [Fact] public void Reverse_Arrows_in_the_GraphDsl_must_work_across_a_FlowShape() { var task = RunnableGraph.FromGraph(GraphDsl.Create(Sink, (b, s) => { b.To(s).Via(b.Add(Flow.Create<int>().MapMaterializedValue(_ => MaterializedValue))).From(Source); return ClosedShape.Instance; })).Run(Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] { 1, 2, 3 }); } } }
using Microsoft.Isam.Esent.Interop; namespace Rhino.PersistentHashTable { using System; using System.Text; [CLSCompliant(false)] public class SchemaCreator { private readonly Session session; public const string SchemaVersion = "1.8"; public SchemaCreator(Session session) { this.session = session; } public void Create(string database) { JET_DBID dbid; Api.JetCreateDatabase(session, database, null, out dbid, CreateDatabaseGrbit.None); try { using (var tx = new Transaction(session)) { CreateDetailsTable(dbid); CreateNextHiTable(dbid); CreateKeysTable(dbid); CreateDataTable(dbid); CreateListTable(dbid); CreateReplicationInfoTable(dbid); CreateReplicationRemovalTable(dbid); tx.Commit(CommitTransactionGrbit.None); } } finally { Api.JetCloseDatabase(session, dbid, CloseDatabaseGrbit.None); } } private void CreateListTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "lists", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "key", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, cp = JET_CP.Unicode, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "id", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL|ColumndefGrbit.ColumnAutoincrement }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "data", new JET_COLUMNDEF { coltyp = JET_coltyp.LongBinary, // For Win2k3 support, it doesn't support long binary columsn that are not null //grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); var indexDef = "+key\0+id\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); indexDef = "+key\0\0"; Api.JetCreateIndex(session, tableid, "by_key", CreateIndexGrbit.IndexDisallowNull, indexDef, indexDef.Length, 100); } private void CreateNextHiTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "next_hi", 16, 100, out tableid); JET_COLUMNID id; Api.JetAddColumn(session, tableid, "val", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out id); using (var update = new Update(session, tableid, JET_prep.Insert)) { Api.SetColumn(session, tableid, id, 0); update.Save(); } } private void CreateDetailsTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "details", 16, 100, out tableid); JET_COLUMNID id; Api.JetAddColumn(session, tableid, "id", new JET_COLUMNDEF { cbMax = 16, coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnNotNULL|ColumndefGrbit.ColumnFixed }, null, 0, out id); JET_COLUMNID schemaVersion; Api.JetAddColumn(session, tableid, "schema_version", new JET_COLUMNDEF { cbMax = Encoding.Unicode.GetByteCount(SchemaVersion), cp = JET_CP.Unicode, coltyp = JET_coltyp.Text, grbit = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed }, null, 0, out schemaVersion); using(var update = new Update(session, tableid, JET_prep.Insert)) { Api.SetColumn(session, tableid, id, Guid.NewGuid().ToByteArray()); Api.SetColumn(session, tableid, schemaVersion, SchemaVersion, Encoding.Unicode); update.Save(); } } private void CreateKeysTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "keys", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "key", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, cp = JET_CP.Unicode, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "version_instance_id", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, cbMax = 16, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "version_number", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "tag", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "expiresAt", new JET_COLUMNDEF { coltyp = JET_coltyp.DateTime, grbit = ColumndefGrbit.ColumnFixed }, null, 0, out columnid); var indexDef = "+key\0+version_number\0+version_instance_id\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); indexDef = "+key\0\0"; Api.JetCreateIndex(session, tableid, "by_key", CreateIndexGrbit.IndexDisallowNull, indexDef, indexDef.Length, 100); indexDef = "+tag\0\0"; Api.JetCreateIndex(session, tableid, "by_tag", CreateIndexGrbit.IndexIgnoreAnyNull, indexDef, indexDef.Length, 100); indexDef = "+expiresAt\0\0"; Api.JetCreateIndex(session, tableid, "by_expiry", CreateIndexGrbit.IndexIgnoreAnyNull, indexDef, indexDef.Length, 100); } private void CreateReplicationRemovalTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "replication_removal_info", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "key", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, cp = JET_CP.Unicode, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "version_instance_id", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, cbMax = 16, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "version_number", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "sha256_hash", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL, cbMax = 32 }, null, 0, out columnid); var indexDef = "+key\0+version_instance_id\0+version_number\0+sha256_hash\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); indexDef = "+sha256_hash\0\0"; Api.JetCreateIndex(session, tableid, "by_hash", CreateIndexGrbit.IndexDisallowNull, indexDef, indexDef.Length, 100); } private void CreateReplicationInfoTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "replication_info", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "key", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, cp = JET_CP.Unicode, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "version_instance_id", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, cbMax = 16, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "version_number", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "sha256_hash", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL, cbMax = 32 }, null, 0, out columnid); var indexDef = "+key\0+version_number\0+version_instance_id\0+sha256_hash\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); indexDef = "+key\0+version_number\0+version_instance_id\0\0"; Api.JetCreateIndex(session, tableid, "by_key_and_version", CreateIndexGrbit.IndexDisallowNull, indexDef, indexDef.Length, 100); } private void CreateDataTable(JET_DBID dbid) { JET_TABLEID tableid; Api.JetCreateTable(session, dbid, "data", 16, 100, out tableid); JET_COLUMNID columnid; Api.JetAddColumn(session, tableid, "key", new JET_COLUMNDEF { cbMax = 255, coltyp = JET_coltyp.Text, cp = JET_CP.Unicode, grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "version_instance_id", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, cbMax = 16, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "version_number", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "tag", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "timestamp", new JET_COLUMNDEF { coltyp = JET_coltyp.DateTime, grbit = ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "data", new JET_COLUMNDEF { coltyp = JET_coltyp.LongBinary, // For Win2k3 support, it doesn't support long binary columsn that are not null //grbit = ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "expiresAt", new JET_COLUMNDEF { coltyp = JET_coltyp.DateTime, grbit = ColumndefGrbit.ColumnFixed }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "sha256_hash", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL, cbMax = 32 }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "readonly", new JET_COLUMNDEF { coltyp = JET_coltyp.Bit, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, null, 0, out columnid); Api.JetAddColumn(session, tableid, "parentVersions", new JET_COLUMNDEF { coltyp = JET_coltyp.Binary, cbMax = 20, /*16 + 4*/ grbit = ColumndefGrbit.ColumnTagged | ColumndefGrbit.ColumnMultiValued }, null, 0, out columnid); const string indexDef = "+key\0+version_number\0+version_instance_id\0\0"; Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length, 100); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging.Abstractions; using Orleans; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Streams; using Xunit; namespace UnitTests.OrleansRuntime.Streams { public class PooledQueueCacheTests { private const int PooledBufferCount = 8; private const int PooledBufferSize = 1 << 10; // 1K private const int MessageSize = 1 << 7; // 128 private const int MessagesPerBuffer = 8; private const string TestStreamNamespace = "blarg"; private class TestQueueMessage { private static readonly byte[] FixedMessage = new byte[MessageSize]; public StreamId StreamId; public long SequenceNumber; public readonly byte[] Data = FixedMessage; public DateTime EnqueueTimeUtc = DateTime.UtcNow; } [GenerateSerializer] public class TestBatchContainer : IBatchContainer { [Id(0)] public StreamId StreamId { get; set; } [Id(1)] public StreamSequenceToken SequenceToken { get; set; } [Id(2)] public byte[] Data { get; set; } public IEnumerable<Tuple<T, StreamSequenceToken>> GetEvents<T>() { throw new NotImplementedException(); } public bool ImportRequestContext() { throw new NotImplementedException(); } } private class TestCacheDataAdapter : ICacheDataAdapter { public IBatchContainer GetBatchContainer(ref CachedMessage cachedMessage) { //Deserialize payload int readOffset = 0; ArraySegment<byte> payload = SegmentBuilder.ReadNextBytes(cachedMessage.Segment, ref readOffset); return new TestBatchContainer { StreamId = cachedMessage.StreamId, SequenceToken = GetSequenceToken(ref cachedMessage), Data = payload.ToArray() }; } public StreamSequenceToken GetSequenceToken(ref CachedMessage cachedMessage) { return new EventSequenceTokenV2(cachedMessage.SequenceNumber); } } private class CachedMessageConverter { private readonly IObjectPool<FixedSizeBuffer> bufferPool; private readonly IEvictionStrategy evictionStrategy; private FixedSizeBuffer currentBuffer; public CachedMessageConverter(IObjectPool<FixedSizeBuffer> bufferPool, IEvictionStrategy evictionStrategy) { this.bufferPool = bufferPool; this.evictionStrategy = evictionStrategy; } public CachedMessage ToCachedMessage(TestQueueMessage queueMessage, DateTime dequeueTimeUtc) { StreamPosition streamPosition = GetStreamPosition(queueMessage); return new CachedMessage { StreamId = streamPosition.StreamId, SequenceNumber = queueMessage.SequenceNumber, EnqueueTimeUtc = queueMessage.EnqueueTimeUtc, DequeueTimeUtc = dequeueTimeUtc, Segment = SerializeMessageIntoPooledSegment(queueMessage), }; } private StreamPosition GetStreamPosition(TestQueueMessage queueMessage) { StreamSequenceToken sequenceToken = new EventSequenceTokenV2(queueMessage.SequenceNumber); return new StreamPosition(queueMessage.StreamId, sequenceToken); } private ArraySegment<byte> SerializeMessageIntoPooledSegment(TestQueueMessage queueMessage) { // serialize payload int size = SegmentBuilder.CalculateAppendSize(queueMessage.Data); // get segment from current block ArraySegment<byte> segment; if (currentBuffer == null || !currentBuffer.TryGetSegment(size, out segment)) { // no block or block full, get new block and try again currentBuffer = bufferPool.Allocate(); //call EvictionStrategy's OnBlockAllocated method this.evictionStrategy.OnBlockAllocated(currentBuffer); // if this fails with clean block, then requested size is too big if (!currentBuffer.TryGetSegment(size, out segment)) { string errmsg = String.Format(CultureInfo.InvariantCulture, "Message size is too big. MessageSize: {0}", size); throw new ArgumentOutOfRangeException(nameof(queueMessage), errmsg); } } // encode namespace, offset, partitionkey, properties and payload into segment int writeOffset = 0; SegmentBuilder.Append(segment, ref writeOffset, queueMessage.Data); return segment; } } /// <summary> /// Fill the cache with 2 streams. /// Get valid cursor to start of each stream. /// Walk each cursor until there is no more data on each stream. /// Alternate adding messages to cache and walking cursors. /// </summary> [Fact, TestCategory("BVT"), TestCategory("Streaming")] public void GoldenPathTest() { var bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(PooledBufferSize)); var dataAdapter = new TestCacheDataAdapter(); var cache = new PooledQueueCache(dataAdapter, NullLogger.Instance, null, null); var evictionStrategy = new ChronologicalEvictionStrategy(NullLogger.Instance, new TimePurgePredicate(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10)), null, null); evictionStrategy.PurgeObservable = cache; var converter = new CachedMessageConverter(bufferPool, evictionStrategy); RunGoldenPath(cache, converter, 111); } /// <summary> /// Run normal golden path test, then purge the cache, and then run another golden path test. /// Goal is to make sure cache cleans up correctly when all data is purged. /// </summary> [Fact, TestCategory("BVT"), TestCategory("Streaming")] public void CacheDrainTest() { var bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(PooledBufferSize)); var dataAdapter = new TestCacheDataAdapter(); var cache = new PooledQueueCache(dataAdapter, NullLogger.Instance, null, null); var evictionStrategy = new ChronologicalEvictionStrategy(NullLogger.Instance, new TimePurgePredicate(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10)), null, null); evictionStrategy.PurgeObservable = cache; var converter = new CachedMessageConverter(bufferPool, evictionStrategy); int startSequenceNuber = 222; startSequenceNuber = RunGoldenPath(cache, converter, startSequenceNuber); RunGoldenPath(cache, converter, startSequenceNuber); } [Fact, TestCategory("BVT"), TestCategory("Streaming")] public void AvoidCacheMissNotEmptyCache() { AvoidCacheMiss(false); } [Fact, TestCategory("BVT"), TestCategory("Streaming")] public void AvoidCacheMissEmptyCache() { AvoidCacheMiss(true); } [Fact, TestCategory("BVT"), TestCategory("Streaming")] public void AvoidCacheMissMultipleStreamsActive() { var bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(PooledBufferSize)); var dataAdapter = new TestCacheDataAdapter(); var cache = new PooledQueueCache(dataAdapter, NullLogger.Instance, null, null, TimeSpan.FromSeconds(30)); var evictionStrategy = new ChronologicalEvictionStrategy(NullLogger.Instance, new TimePurgePredicate(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)), null, null); evictionStrategy.PurgeObservable = cache; var converter = new CachedMessageConverter(bufferPool, evictionStrategy); var seqNumber = 123; var streamKey = Guid.NewGuid(); var stream = StreamId.Create(TestStreamNamespace, streamKey); // Enqueue a message for our stream var firstSequenceNumber = EnqueueMessage(streamKey); // Enqueue a few other messages for other streams EnqueueMessage(Guid.NewGuid()); EnqueueMessage(Guid.NewGuid()); // Consume the first event and see that the cursor has moved to last seen event (not matching our streamIdentity) var cursor = cache.GetCursor(stream, new EventSequenceTokenV2(firstSequenceNumber)); Assert.True(cache.TryGetNextMessage(cursor, out var firstContainer)); Assert.False(cache.TryGetNextMessage(cursor, out _)); // Remove multiple events, including the one that the cursor is currently pointing to cache.RemoveOldestMessage(); cache.RemoveOldestMessage(); cache.RemoveOldestMessage(); // Enqueue another message for stream var lastSequenceNumber = EnqueueMessage(streamKey); // Should be able to consume the event just pushed Assert.True(cache.TryGetNextMessage(cursor, out var lastContainer)); Assert.Equal(stream, lastContainer.StreamId); Assert.Equal(lastSequenceNumber, lastContainer.SequenceToken.SequenceNumber); long EnqueueMessage(Guid streamId) { var now = DateTime.UtcNow; var msg = new TestQueueMessage { StreamId = StreamId.Create(TestStreamNamespace, streamId), SequenceNumber = seqNumber, }; cache.Add(new List<CachedMessage>() { converter.ToCachedMessage(msg, now) }, now); seqNumber++; return msg.SequenceNumber; } } private void AvoidCacheMiss(bool emptyCache) { var bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(PooledBufferSize)); var dataAdapter = new TestCacheDataAdapter(); var cache = new PooledQueueCache(dataAdapter, NullLogger.Instance, null, null, TimeSpan.FromSeconds(30)); var evictionStrategy = new ChronologicalEvictionStrategy(NullLogger.Instance, new TimePurgePredicate(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)), null, null); evictionStrategy.PurgeObservable = cache; var converter = new CachedMessageConverter(bufferPool, evictionStrategy); var seqNumber = 123; var stream = StreamId.Create(TestStreamNamespace, Guid.NewGuid()); // Enqueue a message for stream var firstSequenceNumber = EnqueueMessage(stream); // Consume first event var cursor = cache.GetCursor(stream, new EventSequenceTokenV2(firstSequenceNumber)); Assert.True(cache.TryGetNextMessage(cursor, out var firstContainer)); Assert.Equal(stream, firstContainer.StreamId); Assert.Equal(firstSequenceNumber, firstContainer.SequenceToken.SequenceNumber); // Remove first message, that was consumed cache.RemoveOldestMessage(); if (!emptyCache) { // Enqueue something not related to the stream // so the cache isn't empty EnqueueMessage(StreamId.Create(TestStreamNamespace, Guid.NewGuid())); EnqueueMessage(StreamId.Create(TestStreamNamespace, Guid.NewGuid())); EnqueueMessage(StreamId.Create(TestStreamNamespace, Guid.NewGuid())); EnqueueMessage(StreamId.Create(TestStreamNamespace, Guid.NewGuid())); EnqueueMessage(StreamId.Create(TestStreamNamespace, Guid.NewGuid())); EnqueueMessage(StreamId.Create(TestStreamNamespace, Guid.NewGuid())); } // Enqueue another message for stream var lastSequenceNumber = EnqueueMessage(stream); // Should be able to consume the event just pushed Assert.True(cache.TryGetNextMessage(cursor, out var lastContainer)); Assert.Equal(stream, lastContainer.StreamId); Assert.Equal(lastSequenceNumber, lastContainer.SequenceToken.SequenceNumber); long EnqueueMessage(StreamId streamId) { var now = DateTime.UtcNow; var msg = new TestQueueMessage { StreamId = streamId, SequenceNumber = seqNumber, }; cache.Add(new List<CachedMessage>() { converter.ToCachedMessage(msg, now) }, now); seqNumber++; return msg.SequenceNumber; } } [Fact, TestCategory("BVT"), TestCategory("Streaming")] public void SimpleCacheMiss() { var bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(PooledBufferSize)); var dataAdapter = new TestCacheDataAdapter(); var cache = new PooledQueueCache(dataAdapter, NullLogger.Instance, null, null, TimeSpan.FromSeconds(10)); var evictionStrategy = new ChronologicalEvictionStrategy(NullLogger.Instance, new TimePurgePredicate(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)), null, null); evictionStrategy.PurgeObservable = cache; var converter = new CachedMessageConverter(bufferPool, evictionStrategy); var seqNumber = 123; var streamKey = Guid.NewGuid(); var stream = StreamId.Create(TestStreamNamespace, streamKey); var cursor = cache.GetCursor(stream, new EventSequenceTokenV2(seqNumber)); // Start by enqueuing a message for stream, followed bu another one destined for another one EnqueueMessage(streamKey); EnqueueMessage(Guid.NewGuid()); // Consume the stream, should be fine Assert.True(cache.TryGetNextMessage(cursor, out _)); Assert.False(cache.TryGetNextMessage(cursor, out _)); // Enqueue a new batch // First and last messages destined for stream, following messages // destined for other streams EnqueueMessage(streamKey); for (var idx = 0; idx < 20; idx++) { EnqueueMessage(Guid.NewGuid()); } // Remove first three messages from the cache cache.RemoveOldestMessage(); // Destined for stream, consumed cache.RemoveOldestMessage(); // Not destined for stream cache.RemoveOldestMessage(); // Destined for stream, not consumed // Enqueue a new message for stream EnqueueMessage(streamKey); // Should throw since we missed the second message destined for stream Assert.Throws<QueueCacheMissException>(() => cache.TryGetNextMessage(cursor, out _)); long EnqueueMessage(Guid streamId) { var now = DateTime.UtcNow; var msg = new TestQueueMessage { StreamId = StreamId.Create(TestStreamNamespace, streamId), SequenceNumber = seqNumber, }; cache.Add(new List<CachedMessage>() { converter.ToCachedMessage(msg, now) }, now); seqNumber++; return msg.SequenceNumber; } } private int RunGoldenPath(PooledQueueCache cache, CachedMessageConverter converter, int startOfCache) { int sequenceNumber = startOfCache; IBatchContainer batch; var stream1 = StreamId.Create(TestStreamNamespace, Guid.NewGuid()); var stream2 = StreamId.Create(TestStreamNamespace, Guid.NewGuid()); // now add messages into cache newer than cursor // Adding enough to fill the pool List<TestQueueMessage> messages = Enumerable.Range(0, MessagesPerBuffer * PooledBufferCount) .Select(i => new TestQueueMessage { StreamId = i % 2 == 0 ? stream1 : stream2, SequenceNumber = sequenceNumber + i }) .ToList(); DateTime utcNow = DateTime.UtcNow; List<CachedMessage> cachedMessages = messages .Select(m => converter.ToCachedMessage(m, utcNow)) .ToList(); cache.Add(cachedMessages, utcNow); sequenceNumber += MessagesPerBuffer * PooledBufferCount; // get cursor for stream1, walk all the events in the stream using the cursor object stream1Cursor = cache.GetCursor(stream1, new EventSequenceTokenV2(startOfCache)); int stream1EventCount = 0; while (cache.TryGetNextMessage(stream1Cursor, out batch)) { Assert.NotNull(stream1Cursor); Assert.NotNull(batch); Assert.Equal(stream1, batch.StreamId); Assert.NotNull(batch.SequenceToken); stream1EventCount++; } Assert.Equal((sequenceNumber - startOfCache) / 2, stream1EventCount); // get cursor for stream2, walk all the events in the stream using the cursor object stream2Cursor = cache.GetCursor(stream2, new EventSequenceTokenV2(startOfCache)); int stream2EventCount = 0; while (cache.TryGetNextMessage(stream2Cursor, out batch)) { Assert.NotNull(stream2Cursor); Assert.NotNull(batch); Assert.Equal(stream2, batch.StreamId); Assert.NotNull(batch.SequenceToken); stream2EventCount++; } Assert.Equal((sequenceNumber - startOfCache) / 2, stream2EventCount); // Add a blocks worth of events to the cache, then walk each cursor. Do this enough times to fill the cache twice. for (int j = 0; j < PooledBufferCount*2; j++) { List<TestQueueMessage> moreMessages = Enumerable.Range(0, MessagesPerBuffer) .Select(i => new TestQueueMessage { StreamId = i % 2 == 0 ? stream1 : stream2, SequenceNumber = sequenceNumber + i }) .ToList(); utcNow = DateTime.UtcNow; List<CachedMessage> moreCachedMessages = moreMessages .Select(m => converter.ToCachedMessage(m, utcNow)) .ToList(); cache.Add(moreCachedMessages, utcNow); sequenceNumber += MessagesPerBuffer; // walk all the events in the stream using the cursor while (cache.TryGetNextMessage(stream1Cursor, out batch)) { Assert.NotNull(stream1Cursor); Assert.NotNull(batch); Assert.Equal(stream1, batch.StreamId); Assert.NotNull(batch.SequenceToken); stream1EventCount++; } Assert.Equal((sequenceNumber - startOfCache) / 2, stream1EventCount); // walk all the events in the stream using the cursor while (cache.TryGetNextMessage(stream2Cursor, out batch)) { Assert.NotNull(stream2Cursor); Assert.NotNull(batch); Assert.Equal(stream2, batch.StreamId); Assert.NotNull(batch.SequenceToken); stream2EventCount++; } Assert.Equal((sequenceNumber - startOfCache) / 2, stream2EventCount); } return sequenceNumber; } } }
#pragma warning disable 109, 114, 219, 429, 168, 162 public class PlacePoint : global::UnityEngine.MonoBehaviour, global::haxe.lang.IHxObject { public PlacePoint(global::haxe.lang.EmptyObject empty) : base() { unchecked { } #line default } public PlacePoint() : base() { unchecked { } #line default } public static object __hx_createEmpty() { unchecked { #line 17 "src/PlacePoint.hx" return new global::PlacePoint(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static object __hx_create(global::Array arr) { unchecked { #line 17 "src/PlacePoint.hx" return new global::PlacePoint(); } #line default } public global::pony.events.Signal click; public global::UnityEngine.GameObject g; public virtual void Start() { unchecked { #line 24 "src/PlacePoint.hx" global::pony.unity3d.scene.MouseHelper h = ((global::pony.unity3d.scene.MouseHelper) (global::hugs.GameObjectMethods.getOrAddTypedComponent<object>(this.gameObject, typeof(global::pony.unity3d.scene.MouseHelper))) ); object __temp_stmt285 = default(object); #line 25 "src/PlacePoint.hx" { #line 25 "src/PlacePoint.hx" object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("over"), ((int) (1236832596) ))) ), 0); #line 25 "src/PlacePoint.hx" __temp_stmt285 = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false); } #line 25 "src/PlacePoint.hx" h.over.@add(__temp_stmt285, default(global::haxe.lang.Null<int>)); object __temp_stmt286 = default(object); #line 26 "src/PlacePoint.hx" { #line 26 "src/PlacePoint.hx" object f1 = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("out"), ((int) (5546126) ))) ), 0); #line 26 "src/PlacePoint.hx" __temp_stmt286 = global::pony.events._Listener.Listener_Impl_._fromFunction(f1, false); } #line 26 "src/PlacePoint.hx" h.@out.@add(__temp_stmt286, default(global::haxe.lang.Null<int>)); this.click = h.down; } #line default } public virtual void over() { unchecked { #line 31 "src/PlacePoint.hx" this.transform.localScale = new global::UnityEngine.Vector3(((float) (2) ), ((float) (2) ), ((float) (2) )); } #line default } public virtual void @out() { unchecked { #line 35 "src/PlacePoint.hx" this.transform.localScale = new global::UnityEngine.Vector3(((float) (1) ), ((float) (1) ), ((float) (1) )); } #line default } public virtual void @set(global::pony.events.Event e) { unchecked { #line 39 "src/PlacePoint.hx" if (( this.g != default(global::UnityEngine.GameObject) )) { global::UnityEngine.Object.Destroy(((global::UnityEngine.Object) (this.g) )); this.g = default(global::UnityEngine.GameObject); } #line 43 "src/PlacePoint.hx" global::Player p = ((global::Player) (e.args[0]) ); if (( p != default(global::Player) )) { this.g = ((global::UnityEngine.GameObject) (global::UnityEngine.Object.Instantiate(((global::UnityEngine.GameObject) (global::Scene.players.@get(p).@value) ), ((global::UnityEngine.Vector3) (this.transform.position) ), ((global::UnityEngine.Quaternion) (this.transform.rotation) ))) ); this.g.active = true; this.gameObject.active = false; } else { #line 49 "src/PlacePoint.hx" this.gameObject.active = true; } } #line default } public virtual bool __hx_deleteField(string field, int hash) { unchecked { #line 17 "src/PlacePoint.hx" return false; } #line default } public virtual object __hx_lookupField(string field, int hash, bool throwErrors, bool isCheck) { unchecked { #line 17 "src/PlacePoint.hx" if (isCheck) { #line 17 "src/PlacePoint.hx" return global::haxe.lang.Runtime.undefined; } else { #line 17 "src/PlacePoint.hx" if (throwErrors) { #line 17 "src/PlacePoint.hx" throw global::haxe.lang.HaxeException.wrap("Field not found."); } else { #line 17 "src/PlacePoint.hx" return default(object); } } } #line default } public virtual double __hx_lookupField_f(string field, int hash, bool throwErrors) { unchecked { #line 17 "src/PlacePoint.hx" if (throwErrors) { #line 17 "src/PlacePoint.hx" throw global::haxe.lang.HaxeException.wrap("Field not found or incompatible field type."); } else { #line 17 "src/PlacePoint.hx" return default(double); } } #line default } public virtual object __hx_lookupSetField(string field, int hash, object @value) { unchecked { #line 17 "src/PlacePoint.hx" throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing."); } #line default } public virtual double __hx_lookupSetField_f(string field, int hash, double @value) { unchecked { #line 17 "src/PlacePoint.hx" throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing or incompatible type."); } #line default } public virtual double __hx_setField_f(string field, int hash, double @value, bool handleProperties) { unchecked { #line 17 "src/PlacePoint.hx" switch (hash) { default: { #line 17 "src/PlacePoint.hx" return this.__hx_lookupSetField_f(field, hash, @value); } } } #line default } public virtual object __hx_setField(string field, int hash, object @value, bool handleProperties) { unchecked { #line 17 "src/PlacePoint.hx" switch (hash) { case 1575675685: { #line 17 "src/PlacePoint.hx" this.hideFlags = ((global::UnityEngine.HideFlags) (@value) ); #line 17 "src/PlacePoint.hx" return @value; } case 1224700491: { #line 17 "src/PlacePoint.hx" this.name = global::haxe.lang.Runtime.toString(@value); #line 17 "src/PlacePoint.hx" return @value; } case 5790298: { #line 17 "src/PlacePoint.hx" this.tag = global::haxe.lang.Runtime.toString(@value); #line 17 "src/PlacePoint.hx" return @value; } case 373703110: { #line 17 "src/PlacePoint.hx" this.active = ((bool) (@value) ); #line 17 "src/PlacePoint.hx" return @value; } case 2117141633: { #line 17 "src/PlacePoint.hx" this.enabled = ((bool) (@value) ); #line 17 "src/PlacePoint.hx" return @value; } case 896046654: { #line 17 "src/PlacePoint.hx" this.useGUILayout = ((bool) (@value) ); #line 17 "src/PlacePoint.hx" return @value; } case 103: { #line 17 "src/PlacePoint.hx" this.g = ((global::UnityEngine.GameObject) (@value) ); #line 17 "src/PlacePoint.hx" return @value; } case 1214151752: { #line 17 "src/PlacePoint.hx" this.click = ((global::pony.events.Signal) (@value) ); #line 17 "src/PlacePoint.hx" return @value; } default: { #line 17 "src/PlacePoint.hx" return this.__hx_lookupSetField(field, hash, @value); } } } #line default } public virtual object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties) { unchecked { #line 17 "src/PlacePoint.hx" switch (hash) { case 1826409040: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetType"), ((int) (1826409040) ))) ); } case 304123084: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("ToString"), ((int) (304123084) ))) ); } case 276486854: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetInstanceID"), ((int) (276486854) ))) ); } case 295397041: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetHashCode"), ((int) (295397041) ))) ); } case 1955029599: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Equals"), ((int) (1955029599) ))) ); } case 1575675685: { #line 17 "src/PlacePoint.hx" return this.hideFlags; } case 1224700491: { #line 17 "src/PlacePoint.hx" return this.name; } case 294420221: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessageUpwards"), ((int) (294420221) ))) ); } case 139469119: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessage"), ((int) (139469119) ))) ); } case 967979664: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentsInChildren"), ((int) (967979664) ))) ); } case 2122408236: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponents"), ((int) (2122408236) ))) ); } case 1328964235: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentInChildren"), ((int) (1328964235) ))) ); } case 1723652455: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponent"), ((int) (1723652455) ))) ); } case 89600725: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CompareTag"), ((int) (89600725) ))) ); } case 2134927590: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("BroadcastMessage"), ((int) (2134927590) ))) ); } case 5790298: { #line 17 "src/PlacePoint.hx" return this.tag; } case 373703110: { #line 17 "src/PlacePoint.hx" return this.active; } case 1471506513: { #line 17 "src/PlacePoint.hx" return this.gameObject; } case 1751728597: { #line 17 "src/PlacePoint.hx" return this.particleSystem; } case 524620744: { #line 17 "src/PlacePoint.hx" return this.particleEmitter; } case 964013983: { #line 17 "src/PlacePoint.hx" return this.hingeJoint; } case 1238753076: { #line 17 "src/PlacePoint.hx" return this.collider; } case 674101152: { #line 17 "src/PlacePoint.hx" return this.guiTexture; } case 262266241: { #line 17 "src/PlacePoint.hx" return this.guiElement; } case 1515196979: { #line 17 "src/PlacePoint.hx" return this.networkView; } case 801759432: { #line 17 "src/PlacePoint.hx" return this.guiText; } case 662730966: { #line 17 "src/PlacePoint.hx" return this.audio; } case 853263683: { #line 17 "src/PlacePoint.hx" return this.renderer; } case 1431885287: { #line 17 "src/PlacePoint.hx" return this.constantForce; } case 1261760260: { #line 17 "src/PlacePoint.hx" return this.animation; } case 1962709206: { #line 17 "src/PlacePoint.hx" return this.light; } case 931940005: { #line 17 "src/PlacePoint.hx" return this.camera; } case 1895479501: { #line 17 "src/PlacePoint.hx" return this.rigidbody; } case 1167273324: { #line 17 "src/PlacePoint.hx" return this.transform; } case 2117141633: { #line 17 "src/PlacePoint.hx" return this.enabled; } case 2084823382: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopCoroutine"), ((int) (2084823382) ))) ); } case 1856815770: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopAllCoroutines"), ((int) (1856815770) ))) ); } case 832859768: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine_Auto"), ((int) (832859768) ))) ); } case 987108662: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine"), ((int) (987108662) ))) ); } case 602588383: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("IsInvoking"), ((int) (602588383) ))) ); } case 1641152943: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("InvokeRepeating"), ((int) (1641152943) ))) ); } case 1416948632: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Invoke"), ((int) (1416948632) ))) ); } case 757431474: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CancelInvoke"), ((int) (757431474) ))) ); } case 896046654: { #line 17 "src/PlacePoint.hx" return this.useGUILayout; } case 5741474: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("set"), ((int) (5741474) ))) ); } case 5546126: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("out"), ((int) (5546126) ))) ); } case 1236832596: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("over"), ((int) (1236832596) ))) ); } case 389604418: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Start"), ((int) (389604418) ))) ); } case 103: { #line 17 "src/PlacePoint.hx" return this.g; } case 1214151752: { #line 17 "src/PlacePoint.hx" return this.click; } default: { #line 17 "src/PlacePoint.hx" return this.__hx_lookupField(field, hash, throwErrors, isCheck); } } } #line default } public virtual double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties) { unchecked { #line 17 "src/PlacePoint.hx" switch (hash) { default: { #line 17 "src/PlacePoint.hx" return this.__hx_lookupField_f(field, hash, throwErrors); } } } #line default } public virtual object __hx_invokeField(string field, int hash, global::Array dynargs) { unchecked { #line 17 "src/PlacePoint.hx" switch (hash) { case 757431474:case 1416948632:case 1641152943:case 602588383:case 987108662:case 832859768:case 1856815770:case 2084823382:case 2134927590:case 89600725:case 1723652455:case 1328964235:case 2122408236:case 967979664:case 139469119:case 294420221:case 1955029599:case 295397041:case 276486854:case 304123084:case 1826409040: { #line 17 "src/PlacePoint.hx" return global::haxe.lang.Runtime.slowCallField(this, field, dynargs); } case 5741474: { #line 17 "src/PlacePoint.hx" this.@set(((global::pony.events.Event) (dynargs[0]) )); #line 17 "src/PlacePoint.hx" break; } case 5546126: { #line 17 "src/PlacePoint.hx" this.@out(); #line 17 "src/PlacePoint.hx" break; } case 1236832596: { #line 17 "src/PlacePoint.hx" this.over(); #line 17 "src/PlacePoint.hx" break; } case 389604418: { #line 17 "src/PlacePoint.hx" this.Start(); #line 17 "src/PlacePoint.hx" break; } default: { #line 17 "src/PlacePoint.hx" return ((global::haxe.lang.Function) (this.__hx_getField(field, hash, true, false, false)) ).__hx_invokeDynamic(dynargs); } } #line 17 "src/PlacePoint.hx" return default(object); } #line default } public virtual void __hx_getFields(global::Array<object> baseArr) { unchecked { #line 17 "src/PlacePoint.hx" baseArr.push("hideFlags"); #line 17 "src/PlacePoint.hx" baseArr.push("name"); #line 17 "src/PlacePoint.hx" baseArr.push("tag"); #line 17 "src/PlacePoint.hx" baseArr.push("active"); #line 17 "src/PlacePoint.hx" baseArr.push("gameObject"); #line 17 "src/PlacePoint.hx" baseArr.push("particleSystem"); #line 17 "src/PlacePoint.hx" baseArr.push("particleEmitter"); #line 17 "src/PlacePoint.hx" baseArr.push("hingeJoint"); #line 17 "src/PlacePoint.hx" baseArr.push("collider"); #line 17 "src/PlacePoint.hx" baseArr.push("guiTexture"); #line 17 "src/PlacePoint.hx" baseArr.push("guiElement"); #line 17 "src/PlacePoint.hx" baseArr.push("networkView"); #line 17 "src/PlacePoint.hx" baseArr.push("guiText"); #line 17 "src/PlacePoint.hx" baseArr.push("audio"); #line 17 "src/PlacePoint.hx" baseArr.push("renderer"); #line 17 "src/PlacePoint.hx" baseArr.push("constantForce"); #line 17 "src/PlacePoint.hx" baseArr.push("animation"); #line 17 "src/PlacePoint.hx" baseArr.push("light"); #line 17 "src/PlacePoint.hx" baseArr.push("camera"); #line 17 "src/PlacePoint.hx" baseArr.push("rigidbody"); #line 17 "src/PlacePoint.hx" baseArr.push("transform"); #line 17 "src/PlacePoint.hx" baseArr.push("enabled"); #line 17 "src/PlacePoint.hx" baseArr.push("useGUILayout"); #line 17 "src/PlacePoint.hx" baseArr.push("g"); #line 17 "src/PlacePoint.hx" baseArr.push("click"); } #line default } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics.Contracts; using Microsoft.Research.ClousotRegression; internal class Obj { public Obj() { } public extern int FooBar(); public static extern Obj MakeObj(); public int f; public int g; } internal class Test { #if !CLOUSOT2 // check for persisting inferred assume across versions to maintain suppression [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possibly calling a method on a null reference 'b'", PrimaryILOffset = 1, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven. Are you making some assumption on FooBar that the static checker is unaware of? ", PrimaryILOffset = 14, MethodILOffset = 0)] public int Test1(Obj b) { int tmp = b.FooBar(); Contract.Assert(tmp >= 0); return 7; } #else [RegressionOutcome("No entry found in the cache")] // can't find method by hash... [RegressionOutcome("Assumes have been found in the cache.")] // but do find assume's [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 20, MethodILOffset = 0)] public int Test1(Obj b) { int tmp = b.FooBar(); int j = 0; j++; Contract.Assert(tmp >= 0); return 7; } #endif // check that a new warning of the same type that should be reported is still reported [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly accessing a field on a null reference 'o2'. Are you making some assumption on MakeObj that the static checker is unaware of? ", PrimaryILOffset = 7, MethodILOffset = 0)] public int Test2(Obj o1, int j) { Obj o2 = Obj.MakeObj(); return o2.f + j; } #else [RegressionOutcome("No entry found in the cache")] // can't find method by hash... [RegressionOutcome("Assumes have been found in the cache.")] // but do find assume's [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 13, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possibly accessing a field on a null reference 'o1'", PrimaryILOffset = 20, MethodILOffset = 0)] public int Test2(Obj o1, int j) { Obj o2 = Obj.MakeObj(); j++; return j + o2.f + o1.g; } #endif // check if multiple variables in the assume() are hanlded correctly [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven. Are you making some assumption on Obj.FooBar() that the static checker is unaware of? ", PrimaryILOffset = 14, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference 'b'", PrimaryILOffset = 1, MethodILOffset = 0)] public int Test3(Obj b, int i) { int tmp = b.FooBar(); Contract.Assert(tmp >= i); return 7; } #else [RegressionOutcome("No entry found in the cache")] // can't find method by hash... [RegressionOutcome("Assumes have been found in the cache.")] // but do find assume's [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 20, MethodILOffset = 0)] public int Test3(Obj b, int i) { int tmp = b.FooBar(); int j = 0; j++; Contract.Assert(tmp >= i); return 7; } #endif // see if using a parameter as a return value is handled correctly [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possibly calling a method on a null reference 'b'", PrimaryILOffset = 3, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven. Are you making some assumption on FooBar that the static checker is unaware of? ", PrimaryILOffset = 17, MethodILOffset = 0)] public int Test4(Obj b, int i) { int tmp = 2; i = b.FooBar(); Contract.Assert(tmp >= i); return 7; } #else [RegressionOutcome("No entry found in the cache")] // can't find method by hash... [RegressionOutcome("Assumes have been found in the cache.")] // but do find assume's [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 3, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 23, MethodILOffset = 0)] public int Test4(Obj b, int i) { int tmp = 2; i = b.FooBar(); int j = 0; j++; Contract.Assert(tmp >= i); return 7; } #endif // see if using a parameter as a return value is handled correctly [ClousotRegressionTest] [RegressionOutcome("No entry found in the cache")] #if FIRST [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference 'b' (Fixing this warning may solve one additional issue in the code)", PrimaryILOffset = 7, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference 'b'", PrimaryILOffset = 16, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven. Are you making some assumption on FooBar that the static checker is unaware of? ", PrimaryILOffset = 29, MethodILOffset = 0)] public int Test5(Obj b, int i) { int tmp = 2; int x; if (i > 0) { x = b.FooBar(); } else { x = b.FooBar(); } Contract.Assert(tmp >= x); return 7; } #else [RegressionOutcome("Assumes have been found in the cache.")] // but do find assume's [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 16, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 33, MethodILOffset = 0)] public int Test5(Obj b, int i) { int tmp = 2; int x; if (i > 0) { x = b.FooBar(); } else { x = b.FooBar(); x--; } Contract.Assert(tmp >= x); return 7; } #endif [ContractVerification(false)] private static int UnknownFunction(int z) { return System.Environment.TickCount; } private int a; [ClousotRegressionTest] [RegressionOutcome("No entry found in the cache")] #if FIRST [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven. Are you making some assumption on UnknownFunction that the static checker is unaware of? ", PrimaryILOffset = 19, MethodILOffset = 0)] #else [RegressionOutcome("Assumes have been found in the cache.")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 19, MethodILOffset = 0)] #endif public void TestLocal() { var i = 0; var local = UnknownFunction(i); if (local < 100) { Contract.Assert(local > 10); } } [ClousotRegressionTest] [RegressionOutcome("No entry found in the cache")] #if FIRST [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 9, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 15, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven. Are you making some assumption on UnknownFunction that the static checker is unaware of? ", PrimaryILOffset = 31, MethodILOffset = 0)] #else [RegressionOutcome("Assumes have been found in the cache.")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 9, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 15, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 31, MethodILOffset = 0)] #endif public void TestField() { var i = 0; a = UnknownFunction(i); var local = a; if (local < 100) { Contract.Assert(local > 10); } } private int[] data; [ClousotRegressionTest] [RegressionOutcome("No entry found in the cache")] #if FIRST [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 10, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 16, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 28, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 30, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 36, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Array creation : ok", PrimaryILOffset = 5, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 28, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Upper bound access ok", PrimaryILOffset = 28, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 36, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Upper bound access ok", PrimaryILOffset = 36, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven. Are you making some assumption on UnknownFunction that the static checker is unaware of? ", PrimaryILOffset = 48, MethodILOffset = 0)] #else [RegressionOutcome("Assumes have been found in the cache.")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 10, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 16, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 28, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 30, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 36, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Array creation : ok", PrimaryILOffset = 5, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 28, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Upper bound access ok", PrimaryILOffset = 28, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 36, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Upper bound access ok", PrimaryILOffset = 36, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 48, MethodILOffset = 0)] #endif public void TestArray() { var i = 0; data = new int[10]; data[5] = UnknownFunction(i); var local = data[5]; if (local < 100) { Contract.Assert(local > 10); } } public void OtherFunc(int x) { Contract.Requires(x > 10); } [ClousotRegressionTest] [RegressionOutcome("No entry found in the cache")] #if FIRST [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 9, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "requires unproven: x > 10", PrimaryILOffset = 5, MethodILOffset = 9)] #else [RegressionOutcome("Assumes have been found in the cache.")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 9, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 5, MethodILOffset = 9)] #endif public void TestChain() { var i = 0; OtherFunc(UnknownFunction(i)); } [ContractVerification(false)] private static int RelationOnResult(out int[] array) { array = new int[10]; return System.Environment.TickCount; } [ClousotRegressionTest] [RegressionOutcome("No entry found in the cache")] #if FIRST [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possible use of a null array 'data'", PrimaryILOffset = 11, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Array access might be below the lower bound. Are you making some assumption on RelationOnResult that the static checker is unaware of? ", PrimaryILOffset = 11, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Array access might be above the upper bound. Are you making some assumption on Test.RelationOnResult(System.Int32[]@) that the static checker is unaware of? ", PrimaryILOffset = 11, MethodILOffset = 0)] #else [RegressionOutcome("Assumes have been found in the cache.")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 11, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 11, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Upper bound access ok", PrimaryILOffset = 11, MethodILOffset = 0)] #endif public void TestRelation() { int[] data; var i = RelationOnResult(out data); data[i] = 0; } #else // if CCI2 // dummy test to prevent above tests from failing on CCI2 [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] public void Dummy() { } #else [RegressionOutcome("An entry has been found in the cache")] public void Dummy() { } #endif #endif }
using System; using System.IO; using FluentAssertions; using FluentAssertions.Extensions; using TestableFileSystem.Fakes.Builders; using TestableFileSystem.Interfaces; using Xunit; namespace TestableFileSystem.Fakes.Tests.Specs.FakeDirectory { public sealed class DirectoryTimeLastWriteSpecs { private static readonly DateTime DefaultTimeUtc = 1.February(2034).At(12, 34, 56).AsUtc(); private static readonly DateTime DefaultTime = DefaultTimeUtc.ToLocalTime(); private static readonly DateTime HighTime = DateTime.MaxValue.AddDays(-2).AsUtc().ToLocalTime(); private static readonly DateTime ZeroFileTime = 1.January(1601).AsUtc().ToLocalTime(); [Fact] private void When_getting_last_write_time_in_local_zone_for_null_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act // ReSharper disable once AssignNullToNotNullAttribute Action action = () => fileSystem.Directory.GetLastWriteTime(null); // Assert action.Should().ThrowExactly<ArgumentNullException>(); } [Fact] private void When_setting_last_write_time_in_local_zone_for_null_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act // ReSharper disable once AssignNullToNotNullAttribute Action action = () => fileSystem.Directory.SetLastWriteTime(null, DefaultTime); // Assert action.Should().ThrowExactly<ArgumentNullException>(); } [Fact] private void When_getting_last_write_time_in_local_zone_for_empty_string_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.GetLastWriteTime(string.Empty); // Assert action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*"); } [Fact] private void When_setting_last_write_time_in_local_zone_for_empty_string_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(string.Empty, DefaultTime); // Assert action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*"); } [Fact] private void When_getting_last_write_time_in_local_zone_for_whitespace_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.GetLastWriteTime(" "); // Assert action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*"); } [Fact] private void When_setting_last_write_time_in_local_zone_for_whitespace_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(" ", DefaultTime); // Assert action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*"); } [Fact] private void When_getting_last_write_time_in_local_zone_for_invalid_drive_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.GetLastWriteTime("_:"); // Assert action.Should().ThrowExactly<NotSupportedException>().WithMessage("The given path's format is not supported."); } [Fact] private void When_setting_last_write_time_in_local_zone_for_invalid_drive_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime("_:", DefaultTime); // Assert action.Should().ThrowExactly<NotSupportedException>().WithMessage("The given path's format is not supported."); } [Fact] private void When_getting_last_write_time_in_local_zone_for_wildcard_characters_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.GetLastWriteTime(@"c:\dir?i"); // Assert action.Should().ThrowExactly<ArgumentException>().WithMessage("Illegal characters in path.*"); } [Fact] private void When_setting_last_write_time_in_local_zone_for_wildcard_characters_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(@"c:\dir?i", DefaultTime); // Assert action.Should().ThrowExactly<ArgumentException>().WithMessage("Illegal characters in path.*"); } [Fact] private void When_getting_last_write_time_in_local_zone_for_missing_directory_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"C:\some") .Build(); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(@"C:\some\nested"); // Assert time.Should().Be(ZeroFileTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_missing_directory_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"C:\some") .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(@"C:\some\nested", DefaultTime); // Assert action.Should().ThrowExactly<FileNotFoundException>().WithMessage(@"Could not find file 'C:\some\nested'."); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_directory_it_must_succeed() { // Arrange const string path = @"C:\some"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(path) .Build(); // Act fileSystem.Directory.SetLastWriteTime(path, DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(path).Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_directory_with_trailing_whitespace_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"C:\some") .Build(); // Act fileSystem.Directory.SetLastWriteTime(@"C:\some ", DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(@"C:\some ").Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_readonly_directory_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"C:\some", FileAttributes.ReadOnly) .Build(); // Act fileSystem.Directory.SetLastWriteTime(@"C:\some", DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(@"C:\some").Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_subdirectory_in_readonly_directory_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"c:\folder", FileAttributes.ReadOnly) .IncludingDirectory(@"C:\folder\some") .Build(); // Act fileSystem.Directory.SetLastWriteTime(@"C:\folder\some", DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(@"C:\folder\some").Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_current_directory_it_must_succeed() { // Arrange const string path = @"C:\some\folder"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(path) .Build(); fileSystem.Directory.SetCurrentDirectory(path); // Act fileSystem.Directory.SetLastWriteTime(path, DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(path).Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_directory_to_MinValue_it_must_fail() { // Arrange const string path = @"C:\some"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(path) .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(path, DateTime.MinValue); // Assert action.Should().ThrowExactly<ArgumentOutOfRangeException>().WithMessage("Not a valid Win32 FileTime.*"); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_directory_to_MaxValue_it_must_succeed() { // Arrange const string path = @"C:\some"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(path) .Build(); // Act fileSystem.Directory.SetLastWriteTime(path, HighTime); // Assert fileSystem.Directory.GetLastWriteTime(path).Should().Be(HighTime); } [Fact] private void When_getting_last_write_time_in_local_zone_for_drive_it_must_succeed() { // Arrange const string path = @"C:\"; var clock = new SystemClock(() => DefaultTimeUtc); IFileSystem fileSystem = new FakeFileSystemBuilder(clock) .IncludingDirectory(path) .Build(); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(path); // Assert time.Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_drive_it_must_fail() { // Arrange const string path = @"C:\"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(path) .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(path, DefaultTime); // Assert action.Should().ThrowExactly<ArgumentException>().WithMessage("Path must not be a drive.*"); } [Fact] private void When_getting_last_write_time_in_local_zone_using_absolute_path_without_drive_letter_it_must_succeed() { // Arrange var clock = new SystemClock(() => DefaultTimeUtc); IFileSystem fileSystem = new FakeFileSystemBuilder(clock) .IncludingDirectory(@"c:\some") .IncludingDirectory(@"C:\folder") .Build(); fileSystem.Directory.SetCurrentDirectory(@"C:\some"); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(@"\folder"); // Assert time.Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_using_absolute_path_without_drive_letter_it_must_succeed() { // Arrange var clock = new SystemClock(() => DefaultTimeUtc); IFileSystem fileSystem = new FakeFileSystemBuilder(clock) .IncludingDirectory(@"c:\some") .IncludingDirectory(@"C:\folder") .Build(); fileSystem.Directory.SetCurrentDirectory(@"C:\some"); // Act fileSystem.Directory.SetLastWriteTime(@"\folder", DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(@"c:\folder").Should().Be(DefaultTime); } [Fact] private void When_getting_last_write_time_in_local_zone_for_existing_relative_local_directory_it_must_succeed() { // Arrange var clock = new SystemClock(() => DefaultTimeUtc); IFileSystem fileSystem = new FakeFileSystemBuilder(clock) .IncludingDirectory(@"C:\folder\some") .Build(); fileSystem.Directory.SetCurrentDirectory(@"c:\folder"); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(@"some"); // Assert time.Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_relative_local_directory_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"C:\folder\some") .Build(); fileSystem.Directory.SetCurrentDirectory(@"c:\folder"); // Act fileSystem.Directory.SetLastWriteTime(@"some", DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(@"C:\folder\some").Should().Be(DefaultTime); } [Fact] private void When_getting_last_write_time_in_local_zone_for_existing_local_directory_with_different_casing_it_must_succeed() { // Arrange var clock = new SystemClock(() => DefaultTimeUtc); IFileSystem fileSystem = new FakeFileSystemBuilder(clock) .IncludingDirectory(@"C:\FOLDER\some") .Build(); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(@"C:\folder\SOME"); // Assert time.Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_local_directory_with_different_casing_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"C:\FOLDER\some") .Build(); // Act fileSystem.Directory.SetLastWriteTime(@"C:\folder\SOME", DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(@"C:\FOLDER\some").Should().Be(DefaultTime); } [Fact] private void When_getting_last_write_time_in_local_zone_for_missing_parent_directory_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(@"C:\some\folder"); // Assert time.Should().Be(ZeroFileTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_missing_parent_directory_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(@"C:\some\folder", DefaultTime); // Assert action.Should().ThrowExactly<DirectoryNotFoundException>().WithMessage( @"Could not find a part of the path 'C:\some\folder'."); } [Fact] private void When_getting_last_write_time_in_local_zone_for_existing_file_it_must_succeed() { // Arrange const string path = @"C:\some\file.txt"; var clock = new SystemClock(() => DefaultTimeUtc); IFileSystem fileSystem = new FakeFileSystemBuilder(clock) .IncludingEmptyFile(path) .Build(); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(path); // Assert time.Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_file_it_must_succeed() { // Arrange const string path = @"C:\some\file.txt"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingEmptyFile(path) .Build(); // Act fileSystem.Directory.SetLastWriteTime(path, DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(path).Should().Be(DefaultTime); } [Fact] private void When_getting_last_write_time_in_local_zone_for_parent_directory_that_exists_as_file_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingEmptyFile(@"c:\some\file.txt") .Build(); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(@"c:\some\file.txt\nested.txt"); // Assert time.Should().Be(ZeroFileTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_parent_directory_that_exists_as_file_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingEmptyFile(@"c:\some\file.txt") .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(@"c:\some\file.txt\nested", DefaultTime); // Assert action.Should().ThrowExactly<DirectoryNotFoundException>().WithMessage( @"Could not find a part of the path 'c:\some\file.txt\nested'."); } [Fact] private void When_getting_last_write_time_in_local_zone_for_parent_parent_directory_that_exists_as_file_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingEmptyFile(@"c:\some\file.txt") .Build(); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(@"c:\some\file.txt\nested\more"); // Assert time.Should().Be(ZeroFileTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_parent_parent_directory_that_exists_as_file_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingEmptyFile(@"c:\some\file.txt") .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(@"c:\some\file.txt\nested\more", DefaultTime); // Assert action.Should().ThrowExactly<DirectoryNotFoundException>().WithMessage( @"Could not find a part of the path 'c:\some\file.txt\nested\more'."); } [Fact] private void When_getting_last_write_time_in_local_zone_for_missing_network_share_it_must_fail() { // Arrange const string path = @"\\server\share\missing"; IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.GetLastWriteTime(path); // Assert action.Should().ThrowExactly<IOException>().WithMessage("The network path was not found."); } [Fact] private void When_setting_last_write_time_in_local_zone_for_missing_network_share_it_must_fail() { // Arrange const string path = @"\\server\share\missing"; IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(path, DefaultTime); // Assert action.Should().ThrowExactly<IOException>().WithMessage("The network path was not found."); } [Fact] private void When_getting_last_write_time_in_local_zone_for_existing_network_share_it_must_succeed() { // Arrange const string path = @"\\server\share"; var clock = new SystemClock(() => DefaultTimeUtc); IFileSystem fileSystem = new FakeFileSystemBuilder(clock) .IncludingDirectory(path) .Build(); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(path); // Assert time.Should().Be(DefaultTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_network_share_it_must_succeed() { // Arrange const string path = @"\\server\share"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(path) .Build(); // Act fileSystem.Directory.SetLastWriteTime(path, DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(path).Should().Be(DefaultTime); } [Fact] private void When_getting_last_write_time_in_local_zone_for_missing_remote_directory_it_must_succeed() { // Arrange const string path = @"\\server\share\missing"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"\\server\share") .Build(); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(path); // Assert time.Should().Be(ZeroFileTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_missing_remote_directory_it_must_fail() { // Arrange const string path = @"\\server\share\missing"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"\\server\share") .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(path, DefaultTime); // Assert action.Should().ThrowExactly<FileNotFoundException>().WithMessage(@"Could not find file '\\server\share\missing'."); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_remote_directory_it_must_succeed() { // Arrange const string path = @"\\server\share\personal"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(path) .Build(); // Act fileSystem.Directory.SetLastWriteTime(path, DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(path).Should().Be(DefaultTime); } [Fact] private void When_getting_last_write_time_in_local_zone_for_reserved_name_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.GetLastWriteTime("COM1"); // Assert action.Should().ThrowExactly<PlatformNotSupportedException>().WithMessage("Reserved names are not supported."); } [Fact] private void When_setting_last_write_time_in_local_zone_for_reserved_name_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime("COM1", DefaultTime); // Assert action.Should().ThrowExactly<PlatformNotSupportedException>().WithMessage("Reserved names are not supported."); } [Fact] private void When_getting_last_write_time_in_local_zone_for_missing_extended_local_directory_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"c:\some") .Build(); // Act DateTime time = fileSystem.Directory.GetLastWriteTime(@"\\?\C:\some\missing"); // Assert time.Should().Be(ZeroFileTime); } [Fact] private void When_setting_last_write_time_in_local_zone_for_missing_extended_local_directory_it_must_fail() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"c:\some") .Build(); // Act Action action = () => fileSystem.Directory.SetLastWriteTime(@"\\?\C:\some\missing", DefaultTime); // Assert action.Should().ThrowExactly<FileNotFoundException>().WithMessage(@"Could not find file '\\?\C:\some\missing'."); } [Fact] private void When_setting_last_write_time_in_local_zone_for_existing_extended_local_directory_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"C:\some\other") .Build(); // Act fileSystem.Directory.SetLastWriteTime(@"\\?\C:\some\other", DefaultTime); // Assert fileSystem.Directory.GetLastWriteTime(@"\\?\C:\some\other").Should().Be(DefaultTime); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Orleans; using Orleans.Configuration; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Streams; using Orleans.TestingHost; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; using Orleans.Hosting; using Orleans.Serialization; namespace UnitTests.General { [TestCategory("BVT"), TestCategory("GrainCallFilter")] public class GrainCallFilterTests : OrleansTestingBase, IClassFixture<GrainCallFilterTests.Fixture> { public class Fixture : BaseTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration); builder.AddSiloBuilderConfigurator<SiloInvokerTestSiloBuilderConfigurator>(); builder.AddClientBuilderConfigurator<ClientConfigurator>(); } private class SiloInvokerTestSiloBuilderConfigurator : ISiloConfigurator { public void Configure(ISiloBuilder hostBuilder) { hostBuilder .AddIncomingGrainCallFilter(context => { if (string.Equals(context.InterfaceMethod?.Name, nameof(IGrainCallFilterTestGrain.GetRequestContext))) { if (RequestContext.Get(GrainCallFilterTestConstants.Key) != null) throw new InvalidOperationException(); RequestContext.Set(GrainCallFilterTestConstants.Key, "1"); } return context.Invoke(); }) .AddIncomingGrainCallFilter<GrainCallFilterWithDependencies>() .AddOutgoingGrainCallFilter(async ctx => { if (ctx.InterfaceMethod?.Name == "Echo") { // Concatenate the input to itself. var orig = (string)ctx.Arguments[0]; ctx.Arguments[0] = orig + orig; } await ctx.Invoke(); }) .AddSimpleMessageStreamProvider("SMSProvider") .AddMemoryGrainStorageAsDefault() .AddMemoryGrainStorage("PubSubStore"); } } private class ClientConfigurator : IClientBuilderConfigurator { public void Configure(IConfiguration configuration, IClientBuilder clientBuilder) { clientBuilder .AddOutgoingGrainCallFilter(RetryCertainCalls) .AddOutgoingGrainCallFilter(async ctx => { if (ctx.InterfaceMethod?.DeclaringType == typeof(IOutgoingMethodInterceptionGrain) && ctx.InterfaceMethod?.Name == nameof(IOutgoingMethodInterceptionGrain.EchoViaOtherGrain)) { ctx.Arguments[1] = ((string)ctx.Arguments[1]).ToUpperInvariant(); } await ctx.Invoke(); if (ctx.InterfaceMethod?.DeclaringType == typeof(IOutgoingMethodInterceptionGrain) && ctx.InterfaceMethod?.Name == nameof(IOutgoingMethodInterceptionGrain.EchoViaOtherGrain)) { var result = (Dictionary<string, object>)ctx.Result; result["orig"] = result["result"]; result["result"] = "intercepted!"; } }) .AddSimpleMessageStreamProvider("SMSProvider"); static async Task RetryCertainCalls(IOutgoingGrainCallContext ctx) { var attemptsRemaining = 2; while (attemptsRemaining > 0) { try { await ctx.Invoke(); return; } catch (ArgumentOutOfRangeException) when (attemptsRemaining > 1 && ctx.Grain is IOutgoingMethodInterceptionGrain) { if (string.Equals(ctx.InterfaceMethod?.Name, nameof(IOutgoingMethodInterceptionGrain.ThrowIfGreaterThanZero)) && ctx.Arguments[0] is int value) { ctx.Arguments[0] = value - 1; } --attemptsRemaining; } } } } } } [SuppressMessage("ReSharper", "NotAccessedField.Local")] public class GrainCallFilterWithDependencies : IIncomingGrainCallFilter { private readonly SerializationManager serializationManager; private readonly Silo silo; private readonly IGrainFactory grainFactory; public GrainCallFilterWithDependencies(SerializationManager serializationManager, Silo silo, IGrainFactory grainFactory) { this.serializationManager = serializationManager; this.silo = silo; this.grainFactory = grainFactory; } public Task Invoke(IIncomingGrainCallContext context) { if (string.Equals(context.ImplementationMethod?.Name, nameof(IGrainCallFilterTestGrain.GetRequestContext))) { if (RequestContext.Get(GrainCallFilterTestConstants.Key) is string value) { RequestContext.Set(GrainCallFilterTestConstants.Key, value + '2'); } } return context.Invoke(); } } private readonly Fixture fixture; public GrainCallFilterTests(Fixture fixture) { this.fixture = fixture; } /// <summary> /// Ensures that grain call filters are invoked around method calls in the correct order. /// </summary> /// <returns>A <see cref="Task"/> representing the work performed.</returns> [Fact] public async Task GrainCallFilter_Outgoing_Test() { var grain = this.fixture.GrainFactory.GetGrain<IOutgoingMethodInterceptionGrain>(random.Next()); var grain2 = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next()); // This grain method reads the context and returns it var result = await grain.EchoViaOtherGrain(grain2, "ab"); // Original arg should have been: // 1. Converted to upper case on the way out of the client: ab -> AB. // 2. Doubled on the way out of grain1: AB -> ABAB. // 3. Reversed on the wya in to grain2: ABAB -> BABA. Assert.Equal("BABA", result["orig"] as string); Assert.NotNull(result["result"]); Assert.Equal("intercepted!", result["result"]); } /// <summary> /// Ensures that grain call filters are invoked around method calls in the correct order. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_Order_Test() { var grain = this.fixture.GrainFactory.GetGrain<IGrainCallFilterTestGrain>(random.Next()); // This grain method reads the context and returns it var context = await grain.GetRequestContext(); Assert.NotNull(context); Assert.Equal("1234", context); } /// <summary> /// Ensures that the invocation interceptor is invoked for stream subscribers. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_Stream_Test() { var streamProvider = this.fixture.Client.GetStreamProvider("SMSProvider"); var id = Guid.NewGuid(); var stream = streamProvider.GetStream<int>(id, "InterceptedStream"); var grain = this.fixture.GrainFactory.GetGrain<IStreamInterceptionGrain>(id); // The intercepted grain should double the value passed to the stream. const int testValue = 43; await stream.OnNextAsync(testValue); var actual = await grain.GetLastStreamValue(); Assert.Equal(testValue * 2, actual); } /// <summary> /// Tests that an incoming call filter can retry calls. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_Retry_Test() { var grain = this.fixture.GrainFactory.GetGrain<IGrainCallFilterTestGrain>(0); var result = await grain.ThrowIfGreaterThanZero(1); Assert.Equal("Thanks for nothing", result); await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => grain.ThrowIfGreaterThanZero(2)); } /// <summary> /// Tests that an incoming call filter works with HashSet. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_HashSet_Test() { var grain = this.fixture.GrainFactory.GetGrain<IGrainCallFilterTestGrain>(0); var result = await grain.SumSet(new HashSet<int> { 1, 2, 3 }); Assert.Equal(6, result); } /// <summary> /// Tests that an ougoing call filter can retry calls. /// </summary> [Fact] public async Task GrainCallFilter_Outgoing_Retry_Test() { var grain = this.fixture.GrainFactory.GetGrain<IOutgoingMethodInterceptionGrain>(0); var result = await grain.ThrowIfGreaterThanZero(1); Assert.Equal("Thanks for nothing", result); await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => grain.ThrowIfGreaterThanZero(2)); } /// <summary> /// Tests filters on just the grain level. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_GrainLevel_Test() { var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(0); var result = await grain.One(); Assert.Equal("intercepted one with no args", result); result = await grain.Echo("stao erom tae"); Assert.Equal("eat more oats", result);// Grain interceptors should receive the MethodInfo of the implementation, not the interface. result = await grain.NotIntercepted(); Assert.Equal("not intercepted", result); result = await grain.SayHello(); Assert.Equal("Hello", result); } /// <summary> /// Tests filters on generic grains. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_GenericGrain_Test() { var grain = this.fixture.GrainFactory.GetGrain<IGenericMethodInterceptionGrain<int>>(0); var result = await grain.GetInputAsString(679); Assert.Contains("Hah!", result); Assert.Contains("679", result); result = await grain.SayHello(); Assert.Equal("Hello", result); } /// <summary> /// Tests filters on grains which implement multiple of the same generic interface. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_ConstructedGenericInheritance_Test() { var grain = this.fixture.GrainFactory.GetGrain<ITrickyMethodInterceptionGrain>(0); var result = await grain.GetInputAsString("2014-12-19T14:32:50Z"); Assert.Contains("Hah!", result); Assert.Contains("2014-12-19T14:32:50Z", result); result = await grain.SayHello(); Assert.Equal("Hello", result); var bestNumber = await grain.GetBestNumber(); Assert.Equal(38, bestNumber); result = await grain.GetInputAsString(true); Assert.Contains(true.ToString(CultureInfo.InvariantCulture), result); } /// <summary> /// Tests that grain call filters can handle exceptions. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_ExceptionHandling_Test() { var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next()); // This grain method throws, but the exception should be handled by one of the filters and converted // into a specific message. var result = await grain.Throw(); Assert.NotNull(result); Assert.Equal("EXCEPTION! Oi!", result); } /// <summary> /// Tests that grain call filters can throw exceptions. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_FilterThrows_Test() { var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next()); var exception = await Assert.ThrowsAsync<MethodInterceptionGrain.MyDomainSpecificException>(() => grain.FilterThrows()); Assert.NotNull(exception); Assert.Equal("Filter THROW!", exception.Message); } /// <summary> /// Tests that if a grain call filter sets an incorrect result type for <see cref="Orleans.IGrainCallContext.Result"/>, /// an exception is thrown on the caller. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_SetIncorrectResultType_Test() { var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next()); // This grain method throws, but the exception should be handled by one of the filters and converted // into a specific message. await Assert.ThrowsAsync<InvalidCastException>(() => grain.IncorrectResultType()); } /// <summary> /// Tests that <see cref="IIncomingGrainCallContext.ImplementationMethod"/> and <see cref="IGrainCallContext.InterfaceMethod"/> are non-null /// for a call made to a grain and that they match the correct methods. /// </summary> [Fact] public async Task GrainCallFilter_Incoming_GenericInterface_ConcreteGrain_Test() { var id = random.Next(); var hungry = this.fixture.GrainFactory.GetGrain<IHungryGrain<Apple>>(id); var caterpillar = this.fixture.GrainFactory.GetGrain<ICaterpillarGrain>(id); var omnivore = this.fixture.GrainFactory.GetGrain<IOmnivoreGrain>(id); RequestContext.Set("tag", "hungry-eat"); await hungry.Eat(new Apple()); await ((IHungryGrain<Apple>)caterpillar).Eat(new Apple()); RequestContext.Set("tag", "omnivore-eat"); await omnivore.Eat("string"); await ((IOmnivoreGrain)caterpillar).Eat("string"); RequestContext.Set("tag", "caterpillar-eat"); await caterpillar.Eat("string"); RequestContext.Set("tag", "hungry-eatwith"); await caterpillar.EatWith(new Apple(), "butter"); await hungry.EatWith(new Apple(), "butter"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Internal; using System.Reflection.Metadata; namespace System.Reflection.PortableExecutable { public abstract class PEBuilder { public PEHeaderBuilder Header { get; } public Func<IEnumerable<Blob>, BlobContentId> IdProvider { get; } public bool IsDeterministic { get; } private readonly Lazy<ImmutableArray<Section>> _lazySections; protected struct Section { public readonly string Name; public readonly SectionCharacteristics Characteristics; public Section(string name, SectionCharacteristics characteristics) { if (name == null) { Throw.ArgumentNull(nameof(name)); } Name = name; Characteristics = characteristics; } } private struct SerializedSection { public readonly BlobBuilder Builder; public readonly string Name; public readonly SectionCharacteristics Characteristics; public readonly int RelativeVirtualAddress; public readonly int SizeOfRawData; public readonly int PointerToRawData; public SerializedSection(BlobBuilder builder, string name, SectionCharacteristics characteristics, int relativeVirtualAddress, int sizeOfRawData, int pointerToRawData) { Name = name; Characteristics = characteristics; Builder = builder; RelativeVirtualAddress = relativeVirtualAddress; SizeOfRawData = sizeOfRawData; PointerToRawData = pointerToRawData; } public int VirtualSize => Builder.Count; } protected PEBuilder(PEHeaderBuilder header, Func<IEnumerable<Blob>, BlobContentId> deterministicIdProvider) { if (header == null) { Throw.ArgumentNull(nameof(header)); } IdProvider = deterministicIdProvider ?? BlobContentId.GetTimeBasedProvider(); IsDeterministic = deterministicIdProvider != null; Header = header; _lazySections = new Lazy<ImmutableArray<Section>>(CreateSections); } protected ImmutableArray<Section> GetSections() { var sections = _lazySections.Value; if (sections.IsDefault) { throw new InvalidOperationException(SR.Format(SR.MustNotReturnNull, nameof(CreateSections))); } return sections; } protected abstract ImmutableArray<Section> CreateSections(); protected abstract BlobBuilder SerializeSection(string name, SectionLocation location); internal protected abstract PEDirectoriesBuilder GetDirectories(); public void Serialize(BlobBuilder builder, out BlobContentId contentId) { // Define and serialize sections in two steps. // We need to know about all sections before serializing them. var serializedSections = SerializeSections(); // The positions and sizes of directories are calculated during section serialization. var directories = GetDirectories(); Blob stampFixup; WritePESignature(builder); WriteCoffHeader(builder, serializedSections, out stampFixup); WritePEHeader(builder, directories, serializedSections); WriteSectionHeaders(builder, serializedSections); builder.Align(Header.FileAlignment); foreach (var section in serializedSections) { builder.LinkSuffix(section.Builder); builder.Align(Header.FileAlignment); } contentId = IdProvider(builder.GetBlobs()); // patch timestamp in COFF header: var stampWriter = new BlobWriter(stampFixup); stampWriter.WriteUInt32(contentId.Stamp); Debug.Assert(stampWriter.RemainingBytes == 0); } private ImmutableArray<SerializedSection> SerializeSections() { var sections = GetSections(); var result = ImmutableArray.CreateBuilder<SerializedSection>(sections.Length); int sizeOfPeHeaders = Header.ComputeSizeOfPeHeaders(sections.Length); var nextRva = BitArithmetic.Align(sizeOfPeHeaders, Header.SectionAlignment); var nextPointer = BitArithmetic.Align(sizeOfPeHeaders, Header.FileAlignment); foreach (var section in sections) { var builder = SerializeSection(section.Name, new SectionLocation(nextRva, nextPointer)); var serialized = new SerializedSection( builder, section.Name, section.Characteristics, relativeVirtualAddress: nextRva, sizeOfRawData: BitArithmetic.Align(builder.Count, Header.FileAlignment), pointerToRawData: nextPointer); result.Add(serialized); nextRva = BitArithmetic.Align(serialized.RelativeVirtualAddress + serialized.VirtualSize, Header.SectionAlignment); nextPointer = serialized.PointerToRawData + serialized.SizeOfRawData; } return result.MoveToImmutable(); } private void WritePESignature(BlobBuilder builder) { // MS-DOS stub (128 bytes) builder.WriteBytes(s_dosHeader); // PE Signature "PE\0\0" builder.WriteUInt32(0x00004550); } private static readonly byte[] s_dosHeader = new byte[] { 0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; private void WriteCoffHeader(BlobBuilder builder, ImmutableArray<SerializedSection> sections, out Blob stampFixup) { // Machine builder.WriteUInt16((ushort)(Header.Machine == 0 ? Machine.I386 : Header.Machine)); // NumberOfSections builder.WriteUInt16((ushort)sections.Length); // TimeDateStamp: stampFixup = builder.ReserveBytes(sizeof(uint)); // PointerToSymbolTable (TODO: not supported): // The file pointer to the COFF symbol table, or zero if no COFF symbol table is present. // This value should be zero for a PE image. builder.WriteUInt32(0); // NumberOfSymbols (TODO: not supported): // The number of entries in the symbol table. This data can be used to locate the string table, // which immediately follows the symbol table. This value should be zero for a PE image. builder.WriteUInt32(0); // SizeOfOptionalHeader: // The size of the optional header, which is required for executable files but not for object files. // This value should be zero for an object file (TODO). builder.WriteUInt16((ushort)(Header.Is32Bit ? 224 : 240)); // Characteristics builder.WriteUInt16((ushort)Header.ImageCharacteristics); } private void WritePEHeader(BlobBuilder builder, PEDirectoriesBuilder directories, ImmutableArray<SerializedSection> sections) { builder.WriteUInt16((ushort)(Header.Is32Bit ? PEMagic.PE32 : PEMagic.PE32Plus)); builder.WriteByte(Header.MajorLinkerVersion); builder.WriteByte(Header.MinorLinkerVersion); // SizeOfCode: builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsCode)); // SizeOfInitializedData: builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsInitializedData)); // SizeOfUninitializedData: builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsUninitializedData)); // AddressOfEntryPoint: builder.WriteUInt32((uint)directories.AddressOfEntryPoint); // BaseOfCode: int codeSectionIndex = IndexOfSection(sections, SectionCharacteristics.ContainsCode); builder.WriteUInt32((uint)(codeSectionIndex != -1 ? sections[codeSectionIndex].RelativeVirtualAddress : 0)); if (Header.Is32Bit) { // BaseOfData: int dataSectionIndex = IndexOfSection(sections, SectionCharacteristics.ContainsInitializedData); builder.WriteUInt32((uint)(dataSectionIndex != -1 ? sections[dataSectionIndex].RelativeVirtualAddress : 0)); builder.WriteUInt32((uint)Header.ImageBase); } else { builder.WriteUInt64(Header.ImageBase); } // NT additional fields: builder.WriteUInt32((uint)Header.SectionAlignment); builder.WriteUInt32((uint)Header.FileAlignment); builder.WriteUInt16(Header.MajorOperatingSystemVersion); builder.WriteUInt16(Header.MinorOperatingSystemVersion); builder.WriteUInt16(Header.MajorImageVersion); builder.WriteUInt16(Header.MinorImageVersion); builder.WriteUInt16(Header.MajorSubsystemVersion); builder.WriteUInt16(Header.MinorSubsystemVersion); // Win32VersionValue (reserved, should be 0) builder.WriteUInt32(0); // SizeOfImage: var lastSection = sections[sections.Length - 1]; builder.WriteUInt32((uint)BitArithmetic.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, Header.SectionAlignment)); // SizeOfHeaders: builder.WriteUInt32((uint)BitArithmetic.Align(Header.ComputeSizeOfPeHeaders(sections.Length), Header.FileAlignment)); // Checksum: // Shall be zero for strong name signing. builder.WriteUInt32(0); builder.WriteUInt16((ushort)Header.Subsystem); builder.WriteUInt16((ushort)Header.DllCharacteristics); if (Header.Is32Bit) { builder.WriteUInt32((uint)Header.SizeOfStackReserve); builder.WriteUInt32((uint)Header.SizeOfStackCommit); builder.WriteUInt32((uint)Header.SizeOfHeapReserve); builder.WriteUInt32((uint)Header.SizeOfHeapCommit); } else { builder.WriteUInt64(Header.SizeOfStackReserve); builder.WriteUInt64(Header.SizeOfStackCommit); builder.WriteUInt64(Header.SizeOfHeapReserve); builder.WriteUInt64(Header.SizeOfHeapCommit); } // LoaderFlags builder.WriteUInt32(0); // The number of data-directory entries in the remainder of the header. builder.WriteUInt32(16); // directory entries: builder.WriteUInt32((uint)directories.ExportTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.ExportTable.Size); builder.WriteUInt32((uint)directories.ImportTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.ImportTable.Size); builder.WriteUInt32((uint)directories.ResourceTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.ResourceTable.Size); builder.WriteUInt32((uint)directories.ExceptionTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.ExceptionTable.Size); // Authenticode CertificateTable directory. Shall be zero before the PE is signed. builder.WriteUInt32(0); builder.WriteUInt32(0); builder.WriteUInt32((uint)directories.BaseRelocationTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.BaseRelocationTable.Size); builder.WriteUInt32((uint)directories.DebugTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.DebugTable.Size); builder.WriteUInt32((uint)directories.CopyrightTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.CopyrightTable.Size); builder.WriteUInt32((uint)directories.GlobalPointerTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.GlobalPointerTable.Size); builder.WriteUInt32((uint)directories.ThreadLocalStorageTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.ThreadLocalStorageTable.Size); builder.WriteUInt32((uint)directories.LoadConfigTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.LoadConfigTable.Size); builder.WriteUInt32((uint)directories.BoundImportTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.BoundImportTable.Size); builder.WriteUInt32((uint)directories.ImportAddressTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.ImportAddressTable.Size); builder.WriteUInt32((uint)directories.DelayImportTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.DelayImportTable.Size); builder.WriteUInt32((uint)directories.CorHeaderTable.RelativeVirtualAddress); builder.WriteUInt32((uint)directories.CorHeaderTable.Size); // Reserved, should be 0 builder.WriteUInt64(0); } private void WriteSectionHeaders(BlobBuilder builder, ImmutableArray<SerializedSection> serializedSections) { foreach (var serializedSection in serializedSections) { WriteSectionHeader(builder, serializedSection); } } private static void WriteSectionHeader(BlobBuilder builder, SerializedSection serializedSection) { if (serializedSection.VirtualSize == 0) { return; } for (int j = 0, m = serializedSection.Name.Length; j < 8; j++) { if (j < m) { builder.WriteByte((byte)serializedSection.Name[j]); } else { builder.WriteByte(0); } } builder.WriteUInt32((uint)serializedSection.VirtualSize); builder.WriteUInt32((uint)serializedSection.RelativeVirtualAddress); builder.WriteUInt32((uint)serializedSection.SizeOfRawData); builder.WriteUInt32((uint)serializedSection.PointerToRawData); // PointerToRelocations (TODO: not supported): builder.WriteUInt32(0); // PointerToLinenumbers (TODO: not supported): builder.WriteUInt32(0); // NumberOfRelocations (TODO: not supported): builder.WriteUInt16(0); // NumberOfLinenumbers (TODO: not supported): builder.WriteUInt16(0); builder.WriteUInt32((uint)serializedSection.Characteristics); } private static int IndexOfSection(ImmutableArray<SerializedSection> sections, SectionCharacteristics characteristics) { for (int i = 0; i < sections.Length; i++) { if ((sections[i].Characteristics & characteristics) == characteristics) { return i; } } return -1; } private static int SumRawDataSizes(ImmutableArray<SerializedSection> sections,SectionCharacteristics characteristics) { int result = 0; for (int i = 0; i < sections.Length; i++) { if ((sections[i].Characteristics & characteristics) == characteristics) { result += sections[i].SizeOfRawData; } } return result; } } }
// 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.ComponentModel; //Component using System.Data.Common; using System.Diagnostics; using System.Runtime.CompilerServices; // todo: // There may be two ways to improve performance: // 1. pool statements on the connection object // 2. Do not create a datareader object for non-datareader returning command execution. // // We do not want to do the effort unless we have to squeze performance. namespace System.Data.Odbc { public sealed class OdbcCommand : DbCommand, ICloneable { private static int s_objectTypeCount; // Bid counter internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); private string _commandText; private CommandType _commandType; private int _commandTimeout = ADP.DefaultCommandTimeout; private UpdateRowSource _updatedRowSource = UpdateRowSource.Both; private bool _designTimeInvisible; private bool _isPrepared; // true if the command is prepared private OdbcConnection _connection; private OdbcTransaction _transaction; private WeakReference _weakDataReaderReference; private CMDWrapper _cmdWrapper; private OdbcParameterCollection _parameterCollection; // Parameter collection private ConnectionState _cmdState; public OdbcCommand() : base() { GC.SuppressFinalize(this); } public OdbcCommand(string cmdText) : this() { // note: arguments are assigned to properties so we do not have to trace them. // We still need to include them into the argument list of the definition! CommandText = cmdText; } public OdbcCommand(string cmdText, OdbcConnection connection) : this() { CommandText = cmdText; Connection = connection; } public OdbcCommand(string cmdText, OdbcConnection connection, OdbcTransaction transaction) : this() { CommandText = cmdText; Connection = connection; Transaction = transaction; } private void DisposeDeadDataReader() { if (ConnectionState.Fetching == _cmdState) { if (null != _weakDataReaderReference && !_weakDataReaderReference.IsAlive) { if (_cmdWrapper != null) { _cmdWrapper.FreeKeyInfoStatementHandle(ODBC32.STMT.CLOSE); _cmdWrapper.FreeStatementHandle(ODBC32.STMT.CLOSE); } CloseFromDataReader(); } } } private void DisposeDataReader() { if (null != _weakDataReaderReference) { IDisposable reader = (IDisposable)_weakDataReaderReference.Target; if ((null != reader) && _weakDataReaderReference.IsAlive) { ((IDisposable)reader).Dispose(); } CloseFromDataReader(); } } internal void DisconnectFromDataReaderAndConnection() { // get a reference to the datareader if it is alive OdbcDataReader liveReader = null; if (_weakDataReaderReference != null) { OdbcDataReader reader; reader = (OdbcDataReader)_weakDataReaderReference.Target; if (_weakDataReaderReference.IsAlive) { liveReader = reader; } } // remove reference to this from the live datareader if (liveReader != null) { liveReader.Command = null; } _transaction = null; if (null != _connection) { _connection.RemoveWeakReference(this); _connection = null; } // if the reader is dead we have to dismiss the statement if (liveReader == null) { CloseCommandWrapper(); } // else DataReader now has exclusive ownership _cmdWrapper = null; } protected override void Dispose(bool disposing) { // MDAC 65459 if (disposing) { // release mananged objects // in V1.0, V1.1 the Connection,Parameters,CommandText,Transaction where reset this.DisconnectFromDataReaderAndConnection(); _parameterCollection = null; CommandText = null; } _cmdWrapper = null; // let go of the CommandWrapper _isPrepared = false; base.Dispose(disposing); // notify base classes } internal bool Canceling { get { return _cmdWrapper.Canceling; } } public override string CommandText { get { string value = _commandText; return ((null != value) ? value : ADP.StrEmpty); } set { if (_commandText != value) { PropertyChanging(); _commandText = value; } } } public override int CommandTimeout { // V1.2.3300, XXXCommand V1.0.5000 get { return _commandTimeout; } set { if (value < 0) { throw ADP.InvalidCommandTimeout(value); } if (value != _commandTimeout) { PropertyChanging(); _commandTimeout = value; } } } public void ResetCommandTimeout() { // V1.2.3300 if (ADP.DefaultCommandTimeout != _commandTimeout) { PropertyChanging(); _commandTimeout = ADP.DefaultCommandTimeout; } } private bool ShouldSerializeCommandTimeout() { // V1.2.3300 return (ADP.DefaultCommandTimeout != _commandTimeout); } [ DefaultValue(System.Data.CommandType.Text), ] public override CommandType CommandType { get { CommandType cmdType = _commandType; return ((0 != cmdType) ? cmdType : CommandType.Text); } set { switch (value) { // @perfnote: Enum.IsDefined case CommandType.Text: case CommandType.StoredProcedure: PropertyChanging(); _commandType = value; break; case CommandType.TableDirect: throw ODBC.NotSupportedCommandType(value); default: throw ADP.InvalidCommandType(value); } } } public new OdbcConnection Connection { get { return _connection; } set { if (value != _connection) { PropertyChanging(); this.DisconnectFromDataReaderAndConnection(); Debug.Assert(null == _cmdWrapper, "has CMDWrapper when setting connection"); _connection = value; //OnSchemaChanged(); } } } protected override DbConnection DbConnection { // V1.2.3300 get { return Connection; } set { Connection = (OdbcConnection)value; } } protected override DbParameterCollection DbParameterCollection { // V1.2.3300 get { return Parameters; } } protected override DbTransaction DbTransaction { // V1.2.3300 get { return Transaction; } set { Transaction = (OdbcTransaction)value; } } // @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray) // to limit the number of components that clutter the design surface, // when the DataAdapter design wizard generates the insert/update/delete commands it will // set the DesignTimeVisible property to false so that cmds won't appear as individual objects [ DefaultValue(true), DesignOnly(true), Browsable(false), EditorBrowsableAttribute(EditorBrowsableState.Never), ] public override bool DesignTimeVisible { // V1.2.3300, XXXCommand V1.0.5000 get { return !_designTimeInvisible; } set { _designTimeInvisible = !value; TypeDescriptor.Refresh(this); // VS7 208845 } } internal bool HasParameters { get { return (null != _parameterCollection); } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Content), ] public new OdbcParameterCollection Parameters { get { if (null == _parameterCollection) { _parameterCollection = new OdbcParameterCollection(); } return _parameterCollection; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public new OdbcTransaction Transaction { get { if ((null != _transaction) && (null == _transaction.Connection)) { _transaction = null; // Dawn of the Dead } return _transaction; } set { if (_transaction != value) { PropertyChanging(); // fire event before value is validated _transaction = value; } } } [ DefaultValue(System.Data.UpdateRowSource.Both), ] public override UpdateRowSource UpdatedRowSource { // V1.2.3300, XXXCommand V1.0.5000 get { return _updatedRowSource; } set { switch (value) { // @perfnote: Enum.IsDefined case UpdateRowSource.None: case UpdateRowSource.OutputParameters: case UpdateRowSource.FirstReturnedRecord: case UpdateRowSource.Both: _updatedRowSource = value; break; default: throw ADP.InvalidUpdateRowSource(value); } } } internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute) { return _cmdWrapper.GetDescriptorHandle(attribute); } // GetStatementHandle // ------------------ // Try to return a cached statement handle. // // Creates a CmdWrapper object if necessary // If no handle is available a handle will be allocated. // Bindings will be unbound if a handle is cached and the bindings are invalid. // internal CMDWrapper GetStatementHandle() { // update the command wrapper object, allocate buffer // create reader object // if (_cmdWrapper == null) { _cmdWrapper = new CMDWrapper(_connection); Debug.Assert(null != _connection, "GetStatementHandle without connection?"); _connection.AddWeakReference(this, OdbcReferenceCollection.CommandTag); } if (_cmdWrapper._dataReaderBuf == null) { _cmdWrapper._dataReaderBuf = new CNativeBuffer(4096); } // if there is already a statement handle we need to do some cleanup // if (null == _cmdWrapper.StatementHandle) { _isPrepared = false; _cmdWrapper.CreateStatementHandle(); } else if ((null != _parameterCollection) && _parameterCollection.RebindCollection) { _cmdWrapper.FreeStatementHandle(ODBC32.STMT.RESET_PARAMS); } return _cmdWrapper; } // OdbcCommand.Cancel() // // In ODBC3.0 ... a call to SQLCancel when no processing is done has no effect at all // (ODBC Programmer's Reference ...) // public override void Cancel() { CMDWrapper wrapper = _cmdWrapper; if (null != wrapper) { wrapper.Canceling = true; OdbcStatementHandle stmt = wrapper.StatementHandle; if (null != stmt) { lock (stmt) { // Cancel the statement ODBC32.RetCode retcode = stmt.Cancel(); // copy of StatementErrorHandler, because stmt may become null switch (retcode) { case ODBC32.RetCode.SUCCESS: case ODBC32.RetCode.SUCCESS_WITH_INFO: // don't fire info message events on cancel break; default: throw wrapper.Connection.HandleErrorNoThrow(stmt, retcode); } } } } } object ICloneable.Clone() { OdbcCommand clone = new OdbcCommand(); clone.CommandText = CommandText; clone.CommandTimeout = this.CommandTimeout; clone.CommandType = CommandType; clone.Connection = this.Connection; clone.Transaction = this.Transaction; clone.UpdatedRowSource = UpdatedRowSource; if ((null != _parameterCollection) && (0 < Parameters.Count)) { OdbcParameterCollection parameters = clone.Parameters; foreach (ICloneable parameter in Parameters) { parameters.Add(parameter.Clone()); } } return clone; } internal bool RecoverFromConnection() { DisposeDeadDataReader(); return (ConnectionState.Closed == _cmdState); } private void CloseCommandWrapper() { CMDWrapper wrapper = _cmdWrapper; if (null != wrapper) { try { wrapper.Dispose(); if (null != _connection) { _connection.RemoveWeakReference(this); } } finally { _cmdWrapper = null; } } } internal void CloseFromConnection() { if (null != _parameterCollection) { _parameterCollection.RebindCollection = true; } DisposeDataReader(); CloseCommandWrapper(); _isPrepared = false; _transaction = null; } internal void CloseFromDataReader() { _weakDataReaderReference = null; _cmdState = ConnectionState.Closed; } public new OdbcParameter CreateParameter() { return new OdbcParameter(); } protected override DbParameter CreateDbParameter() { return CreateParameter(); } protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { return ExecuteReader(behavior); } public override int ExecuteNonQuery() { using (OdbcDataReader reader = ExecuteReaderObject(0, ADP.ExecuteNonQuery, false)) { reader.Close(); return reader.RecordsAffected; } } public new OdbcDataReader ExecuteReader() { return ExecuteReader(0/*CommandBehavior*/); } public new OdbcDataReader ExecuteReader(CommandBehavior behavior) { return ExecuteReaderObject(behavior, ADP.ExecuteReader, true); } internal OdbcDataReader ExecuteReaderFromSQLMethod(object[] methodArguments, ODBC32.SQL_API method) { return ExecuteReaderObject(CommandBehavior.Default, method.ToString(), true, methodArguments, method); } private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader) { // MDAC 68324 if ((CommandText == null) || (CommandText.Length == 0)) { throw (ADP.CommandTextRequired(method)); } // using all functions to tell ExecuteReaderObject that return ExecuteReaderObject(behavior, method, needReader, null, ODBC32.SQL_API.SQLEXECDIRECT); } private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader, object[] methodArguments, ODBC32.SQL_API odbcApiMethod) { // MDAC 68324 OdbcDataReader localReader = null; try { DisposeDeadDataReader(); // this is a no-op if cmdState is not Fetching ValidateConnectionAndTransaction(method); // cmdState will change to Executing if (0 != (CommandBehavior.SingleRow & behavior)) { // CommandBehavior.SingleRow implies CommandBehavior.SingleResult behavior |= CommandBehavior.SingleResult; } ODBC32.RetCode retcode; OdbcStatementHandle stmt = GetStatementHandle().StatementHandle; _cmdWrapper.Canceling = false; if (null != _weakDataReaderReference) { if (_weakDataReaderReference.IsAlive) { object target = _weakDataReaderReference.Target; if (null != target && _weakDataReaderReference.IsAlive) { if (!((OdbcDataReader)target).IsClosed) { throw ADP.OpenReaderExists(); // MDAC 66411 } } } } localReader = new OdbcDataReader(this, _cmdWrapper, behavior); //Set command properties //Not all drivers support timeout. So fail silently if error if (!Connection.ProviderInfo.NoQueryTimeout) { TrySetStatementAttribute(stmt, ODBC32.SQL_ATTR.QUERY_TIMEOUT, (IntPtr)this.CommandTimeout); } // todo: If we remember the state we can omit a lot of SQLSetStmtAttrW calls ... // if we do not create a reader we do not even need to do that if (needReader) { if (Connection.IsV3Driver) { if (!Connection.ProviderInfo.NoSqlSoptSSNoBrowseTable && !Connection.ProviderInfo.NoSqlSoptSSHiddenColumns) { // Need to get the metadata information //SQLServer actually requires browse info turned on ahead of time... //Note: We ignore any failures, since this is SQLServer specific //We won't specialcase for SQL Server but at least for non-V3 drivers if (localReader.IsBehavior(CommandBehavior.KeyInfo)) { if (!_cmdWrapper._ssKeyInfoModeOn) { TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE, (IntPtr)ODBC32.SQL_NB.ON); TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS, (IntPtr)ODBC32.SQL_HC.ON); _cmdWrapper._ssKeyInfoModeOff = false; _cmdWrapper._ssKeyInfoModeOn = true; } } else { if (!_cmdWrapper._ssKeyInfoModeOff) { TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE, (IntPtr)ODBC32.SQL_NB.OFF); TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS, (IntPtr)ODBC32.SQL_HC.OFF); _cmdWrapper._ssKeyInfoModeOff = true; _cmdWrapper._ssKeyInfoModeOn = false; } } } } } if (localReader.IsBehavior(CommandBehavior.KeyInfo) || localReader.IsBehavior(CommandBehavior.SchemaOnly)) { retcode = stmt.Prepare(CommandText); if (ODBC32.RetCode.SUCCESS != retcode) { _connection.HandleError(stmt, retcode); } } bool mustRelease = false; CNativeBuffer parameterBuffer = _cmdWrapper._nativeParameterBuffer; RuntimeHelpers.PrepareConstrainedRegions(); try { //Handle Parameters //Note: We use the internal variable as to not instante a new object collection, //for the common case of using no parameters. if ((null != _parameterCollection) && (0 < _parameterCollection.Count)) { int parameterBufferSize = _parameterCollection.CalcParameterBufferSize(this); if (null == parameterBuffer || parameterBuffer.Length < parameterBufferSize) { if (null != parameterBuffer) { parameterBuffer.Dispose(); } parameterBuffer = new CNativeBuffer(parameterBufferSize); _cmdWrapper._nativeParameterBuffer = parameterBuffer; } else { parameterBuffer.ZeroMemory(); } parameterBuffer.DangerousAddRef(ref mustRelease); _parameterCollection.Bind(this, _cmdWrapper, parameterBuffer); } if (!localReader.IsBehavior(CommandBehavior.SchemaOnly)) { // Can't get the KeyInfo after command execution (SQL Server only since it does not support multiple // results on the same connection). Stored procedures (SP) do not return metadata before actual execution // Need to check the column count since the command type may not be set to SP for a SP. if ((localReader.IsBehavior(CommandBehavior.KeyInfo) || localReader.IsBehavior(CommandBehavior.SchemaOnly)) && (CommandType != CommandType.StoredProcedure)) { Int16 cColsAffected; retcode = stmt.NumberOfResultColumns(out cColsAffected); if (retcode == ODBC32.RetCode.SUCCESS || retcode == ODBC32.RetCode.SUCCESS_WITH_INFO) { if (cColsAffected > 0) { localReader.GetSchemaTable(); } } else if (retcode == ODBC32.RetCode.NO_DATA) { // do nothing } else { // any other returncode indicates an error _connection.HandleError(stmt, retcode); } } switch (odbcApiMethod) { case ODBC32.SQL_API.SQLEXECDIRECT: if (localReader.IsBehavior(CommandBehavior.KeyInfo) || _isPrepared) { //Already prepared, so use SQLExecute retcode = stmt.Execute(); // Build metadata here // localReader.GetSchemaTable(); } else { #if DEBUG //if (AdapterSwitches.OleDbTrace.TraceInfo) { // ADP.DebugWriteLine("SQLExecDirectW: " + CommandText); //} #endif //SQLExecDirect retcode = stmt.ExecuteDirect(CommandText); } break; case ODBC32.SQL_API.SQLTABLES: retcode = stmt.Tables((string)methodArguments[0], //TableCatalog (string)methodArguments[1], //TableSchema, (string)methodArguments[2], //TableName (string)methodArguments[3]); //TableType break; case ODBC32.SQL_API.SQLCOLUMNS: retcode = stmt.Columns((string)methodArguments[0], //TableCatalog (string)methodArguments[1], //TableSchema (string)methodArguments[2], //TableName (string)methodArguments[3]); //ColumnName break; case ODBC32.SQL_API.SQLPROCEDURES: retcode = stmt.Procedures((string)methodArguments[0], //ProcedureCatalog (string)methodArguments[1], //ProcedureSchema (string)methodArguments[2]); //procedureName break; case ODBC32.SQL_API.SQLPROCEDURECOLUMNS: retcode = stmt.ProcedureColumns((string)methodArguments[0], //ProcedureCatalog (string)methodArguments[1], //ProcedureSchema (string)methodArguments[2], //procedureName (string)methodArguments[3]); //columnName break; case ODBC32.SQL_API.SQLSTATISTICS: retcode = stmt.Statistics((string)methodArguments[0], //TableCatalog (string)methodArguments[1], //TableSchema (string)methodArguments[2], //TableName (Int16)methodArguments[3], //IndexTrpe (Int16)methodArguments[4]); //Accuracy break; case ODBC32.SQL_API.SQLGETTYPEINFO: retcode = stmt.GetTypeInfo((Int16)methodArguments[0]); //SQL Type break; default: // this should NEVER happen Debug.Assert(false, "ExecuteReaderObjectcalled with unsupported ODBC API method."); throw ADP.InvalidOperation(method.ToString()); } //Note: Execute will return NO_DATA for Update/Delete non-row returning queries if ((ODBC32.RetCode.SUCCESS != retcode) && (ODBC32.RetCode.NO_DATA != retcode)) { _connection.HandleError(stmt, retcode); } } // end SchemaOnly } finally { if (mustRelease) { parameterBuffer.DangerousRelease(); } } _weakDataReaderReference = new WeakReference(localReader); // XXXCommand.Execute should position reader on first row returning result // any exceptions in the initial non-row returning results should be thrown // from from ExecuteXXX not the DataReader if (!localReader.IsBehavior(CommandBehavior.SchemaOnly)) { localReader.FirstResult(); } _cmdState = ConnectionState.Fetching; } finally { if (ConnectionState.Fetching != _cmdState) { if (null != localReader) { // clear bindings so we don't grab output parameters on a failed execute if (null != _parameterCollection) { _parameterCollection.ClearBindings(); } ((IDisposable)localReader).Dispose(); } if (ConnectionState.Closed != _cmdState) { _cmdState = ConnectionState.Closed; } } } return localReader; } public override object ExecuteScalar() { object value = null; using (IDataReader reader = ExecuteReaderObject(0, ADP.ExecuteScalar, false)) { if (reader.Read() && (0 < reader.FieldCount)) { value = reader.GetValue(0); } reader.Close(); } return value; } internal string GetDiagSqlState() { return _cmdWrapper.GetDiagSqlState(); } private void PropertyChanging() { _isPrepared = false; } // Prepare // // if the CommandType property is set to TableDirect Prepare does nothing. // if the CommandType property is set to StoredProcedure Prepare should succeed but result // in a no-op // // throw InvalidOperationException // if the connection is not set // if the connection is not open // public override void Prepare() { ODBC32.RetCode retcode; ValidateOpenConnection(ADP.Prepare); if (0 != (ConnectionState.Fetching & _connection.InternalState)) { throw ADP.OpenReaderExists(); } if (CommandType == CommandType.TableDirect) { return; // do nothing } DisposeDeadDataReader(); GetStatementHandle(); OdbcStatementHandle stmt = _cmdWrapper.StatementHandle; retcode = stmt.Prepare(CommandText); if (ODBC32.RetCode.SUCCESS != retcode) { _connection.HandleError(stmt, retcode); } _isPrepared = true; } private void TrySetStatementAttribute(OdbcStatementHandle stmt, ODBC32.SQL_ATTR stmtAttribute, IntPtr value) { ODBC32.RetCode retcode = stmt.SetStatementAttribute( stmtAttribute, value, ODBC32.SQL_IS.UINTEGER); if (retcode == ODBC32.RetCode.ERROR) { string sqlState; stmt.GetDiagnosticField(out sqlState); if ((sqlState == "HYC00") || (sqlState == "HY092")) { Connection.FlagUnsupportedStmtAttr(stmtAttribute); } else { // now what? Should we throw? } } } private void ValidateOpenConnection(string methodName) { // see if we have a connection OdbcConnection connection = Connection; if (null == connection) { throw ADP.ConnectionRequired(methodName); } // must have an open and available connection ConnectionState state = connection.State; if (ConnectionState.Open != state) { throw ADP.OpenConnectionRequired(methodName, state); } } private void ValidateConnectionAndTransaction(string method) { if (null == _connection) { throw ADP.ConnectionRequired(method); } _transaction = _connection.SetStateExecuting(method, Transaction); _cmdState = ConnectionState.Executing; } } internal sealed class CMDWrapper { private OdbcStatementHandle _stmt; // hStmt private OdbcStatementHandle _keyinfostmt; // hStmt for keyinfo internal OdbcDescriptorHandle _hdesc; // hDesc internal CNativeBuffer _nativeParameterBuffer; // Native memory for internal memory management // (Performance optimization) internal CNativeBuffer _dataReaderBuf; // Reusable DataReader buffer private readonly OdbcConnection _connection; // Connection private bool _canceling; // true if the command is canceling internal bool _hasBoundColumns; internal bool _ssKeyInfoModeOn; // tells us if the SqlServer specific options are on internal bool _ssKeyInfoModeOff; // a tri-state value would be much better ... internal CMDWrapper(OdbcConnection connection) { _connection = connection; } internal bool Canceling { get { return _canceling; } set { _canceling = value; } } internal OdbcConnection Connection { get { return _connection; } } internal bool HasBoundColumns { // get { // return _hasBoundColumns; // } set { _hasBoundColumns = value; } } internal OdbcStatementHandle StatementHandle { get { return _stmt; } } internal OdbcStatementHandle KeyInfoStatement { get { return _keyinfostmt; } } internal void CreateKeyInfoStatementHandle() { DisposeKeyInfoStatementHandle(); _keyinfostmt = _connection.CreateStatementHandle(); } internal void CreateStatementHandle() { DisposeStatementHandle(); _stmt = _connection.CreateStatementHandle(); } internal void Dispose() { if (null != _dataReaderBuf) { _dataReaderBuf.Dispose(); _dataReaderBuf = null; } DisposeStatementHandle(); CNativeBuffer buffer = _nativeParameterBuffer; _nativeParameterBuffer = null; if (null != buffer) { buffer.Dispose(); } _ssKeyInfoModeOn = false; _ssKeyInfoModeOff = false; } private void DisposeDescriptorHandle() { OdbcDescriptorHandle handle = _hdesc; if (null != handle) { _hdesc = null; handle.Dispose(); } } internal void DisposeStatementHandle() { DisposeKeyInfoStatementHandle(); DisposeDescriptorHandle(); OdbcStatementHandle handle = _stmt; if (null != handle) { _stmt = null; handle.Dispose(); } } internal void DisposeKeyInfoStatementHandle() { OdbcStatementHandle handle = _keyinfostmt; if (null != handle) { _keyinfostmt = null; handle.Dispose(); } } internal void FreeStatementHandle(ODBC32.STMT stmt) { DisposeDescriptorHandle(); OdbcStatementHandle handle = _stmt; if (null != handle) { try { ODBC32.RetCode retcode; retcode = handle.FreeStatement(stmt); StatementErrorHandler(retcode); } catch (Exception e) { // if (ADP.IsCatchableExceptionType(e)) { _stmt = null; handle.Dispose(); } throw; } } } internal void FreeKeyInfoStatementHandle(ODBC32.STMT stmt) { OdbcStatementHandle handle = _keyinfostmt; if (null != handle) { try { handle.FreeStatement(stmt); } catch (Exception e) { // if (ADP.IsCatchableExceptionType(e)) { _keyinfostmt = null; handle.Dispose(); } throw; } } } // Get the Descriptor Handle for the current statement // internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute) { OdbcDescriptorHandle hdesc = _hdesc; if (null == _hdesc) { _hdesc = hdesc = new OdbcDescriptorHandle(_stmt, attribute); } return hdesc; } internal string GetDiagSqlState() { string sqlstate; _stmt.GetDiagnosticField(out sqlstate); return sqlstate; } internal void StatementErrorHandler(ODBC32.RetCode retcode) { switch (retcode) { case ODBC32.RetCode.SUCCESS: case ODBC32.RetCode.SUCCESS_WITH_INFO: _connection.HandleErrorNoThrow(_stmt, retcode); break; default: throw _connection.HandleErrorNoThrow(_stmt, retcode); } } internal void UnbindStmtColumns() { if (_hasBoundColumns) { FreeStatementHandle(ODBC32.STMT.UNBIND); _hasBoundColumns = false; } } } }
namespace java.text { [global::MonoJavaBridge.JavaClass(typeof(global::java.text.NumberFormat_))] public abstract partial class NumberFormat : java.text.Format { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected NumberFormat(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public new partial class Field : java.text.Format.Field { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Field(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; protected override global::java.lang.Object readResolve() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.text.NumberFormat.Field.staticClass, "readResolve", "()Ljava/lang/Object;", ref global::java.text.NumberFormat.Field._m0) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m1; protected Field(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat.Field._m1.native == global::System.IntPtr.Zero) global::java.text.NumberFormat.Field._m1 = @__env.GetMethodIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "<init>", "(Ljava/lang/String;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.text.NumberFormat.Field.staticClass, global::java.text.NumberFormat.Field._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _INTEGER6736; public static global::java.text.NumberFormat.Field INTEGER { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _INTEGER6736)) as java.text.NumberFormat.Field; } } internal static global::MonoJavaBridge.FieldId _FRACTION6737; public static global::java.text.NumberFormat.Field FRACTION { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _FRACTION6737)) as java.text.NumberFormat.Field; } } internal static global::MonoJavaBridge.FieldId _EXPONENT6738; public static global::java.text.NumberFormat.Field EXPONENT { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _EXPONENT6738)) as java.text.NumberFormat.Field; } } internal static global::MonoJavaBridge.FieldId _DECIMAL_SEPARATOR6739; public static global::java.text.NumberFormat.Field DECIMAL_SEPARATOR { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _DECIMAL_SEPARATOR6739)) as java.text.NumberFormat.Field; } } internal static global::MonoJavaBridge.FieldId _SIGN6740; public static global::java.text.NumberFormat.Field SIGN { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _SIGN6740)) as java.text.NumberFormat.Field; } } internal static global::MonoJavaBridge.FieldId _GROUPING_SEPARATOR6741; public static global::java.text.NumberFormat.Field GROUPING_SEPARATOR { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _GROUPING_SEPARATOR6741)) as java.text.NumberFormat.Field; } } internal static global::MonoJavaBridge.FieldId _EXPONENT_SYMBOL6742; public static global::java.text.NumberFormat.Field EXPONENT_SYMBOL { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _EXPONENT_SYMBOL6742)) as java.text.NumberFormat.Field; } } internal static global::MonoJavaBridge.FieldId _PERCENT6743; public static global::java.text.NumberFormat.Field PERCENT { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _PERCENT6743)) as java.text.NumberFormat.Field; } } internal static global::MonoJavaBridge.FieldId _PERMILLE6744; public static global::java.text.NumberFormat.Field PERMILLE { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _PERMILLE6744)) as java.text.NumberFormat.Field; } } internal static global::MonoJavaBridge.FieldId _CURRENCY6745; public static global::java.text.NumberFormat.Field CURRENCY { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _CURRENCY6745)) as java.text.NumberFormat.Field; } } internal static global::MonoJavaBridge.FieldId _EXPONENT_SIGN6746; public static global::java.text.NumberFormat.Field EXPONENT_SIGN { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.text.NumberFormat.Field.staticClass, _EXPONENT_SIGN6746)) as java.text.NumberFormat.Field; } } static Field() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.text.NumberFormat.Field.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/text/NumberFormat$Field")); global::java.text.NumberFormat.Field._INTEGER6736 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "INTEGER", "Ljava/text/NumberFormat$Field;"); global::java.text.NumberFormat.Field._FRACTION6737 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "FRACTION", "Ljava/text/NumberFormat$Field;"); global::java.text.NumberFormat.Field._EXPONENT6738 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "EXPONENT", "Ljava/text/NumberFormat$Field;"); global::java.text.NumberFormat.Field._DECIMAL_SEPARATOR6739 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "DECIMAL_SEPARATOR", "Ljava/text/NumberFormat$Field;"); global::java.text.NumberFormat.Field._SIGN6740 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "SIGN", "Ljava/text/NumberFormat$Field;"); global::java.text.NumberFormat.Field._GROUPING_SEPARATOR6741 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "GROUPING_SEPARATOR", "Ljava/text/NumberFormat$Field;"); global::java.text.NumberFormat.Field._EXPONENT_SYMBOL6742 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "EXPONENT_SYMBOL", "Ljava/text/NumberFormat$Field;"); global::java.text.NumberFormat.Field._PERCENT6743 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "PERCENT", "Ljava/text/NumberFormat$Field;"); global::java.text.NumberFormat.Field._PERMILLE6744 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "PERMILLE", "Ljava/text/NumberFormat$Field;"); global::java.text.NumberFormat.Field._CURRENCY6745 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "CURRENCY", "Ljava/text/NumberFormat$Field;"); global::java.text.NumberFormat.Field._EXPONENT_SIGN6746 = @__env.GetStaticFieldIDNoThrow(global::java.text.NumberFormat.Field.staticClass, "EXPONENT_SIGN", "Ljava/text/NumberFormat$Field;"); } } private static global::MonoJavaBridge.MethodId _m0; public override bool equals(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.text.NumberFormat.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::java.text.NumberFormat._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public override int hashCode() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.text.NumberFormat.staticClass, "hashCode", "()I", ref global::java.text.NumberFormat._m1); } private static global::MonoJavaBridge.MethodId _m2; public override global::java.lang.Object clone() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.text.NumberFormat.staticClass, "clone", "()Ljava/lang/Object;", ref global::java.text.NumberFormat._m2) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m3; public virtual global::java.lang.String format(long arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.text.NumberFormat.staticClass, "format", "(J)Ljava/lang/String;", ref global::java.text.NumberFormat._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m4; public abstract global::java.lang.StringBuffer format(double arg0, java.lang.StringBuffer arg1, java.text.FieldPosition arg2); private static global::MonoJavaBridge.MethodId _m5; public abstract global::java.lang.StringBuffer format(long arg0, java.lang.StringBuffer arg1, java.text.FieldPosition arg2); private static global::MonoJavaBridge.MethodId _m6; public override global::java.lang.StringBuffer format(java.lang.Object arg0, java.lang.StringBuffer arg1, java.text.FieldPosition arg2) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.StringBuffer>(this, global::java.text.NumberFormat.staticClass, "format", "(Ljava/lang/Object;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", ref global::java.text.NumberFormat._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.lang.StringBuffer; } private static global::MonoJavaBridge.MethodId _m7; public virtual global::java.lang.String format(double arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.text.NumberFormat.staticClass, "format", "(D)Ljava/lang/String;", ref global::java.text.NumberFormat._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m8; public static global::java.text.NumberFormat getInstance() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m8.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m8 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getInstance", "()Ljava/text/NumberFormat;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m8)) as java.text.NumberFormat; } private static global::MonoJavaBridge.MethodId _m9; public static global::java.text.NumberFormat getInstance(java.util.Locale arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m9.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m9 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getInstance", "(Ljava/util/Locale;)Ljava/text/NumberFormat;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.text.NumberFormat; } private static global::MonoJavaBridge.MethodId _m10; public virtual global::java.lang.Number parse(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.text.NumberFormat.staticClass, "parse", "(Ljava/lang/String;)Ljava/lang/Number;", ref global::java.text.NumberFormat._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Number; } private static global::MonoJavaBridge.MethodId _m11; public abstract global::java.lang.Number parse(java.lang.String arg0, java.text.ParsePosition arg1); private static global::MonoJavaBridge.MethodId _m12; public static global::java.util.Locale[] getAvailableLocales() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m12.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m12 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getAvailableLocales", "()[Ljava/util/Locale;"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.util.Locale>(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m12)) as java.util.Locale[]; } private static global::MonoJavaBridge.MethodId _m13; public sealed override global::java.lang.Object parseObject(java.lang.String arg0, java.text.ParsePosition arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.text.NumberFormat.staticClass, "parseObject", "(Ljava/lang/String;Ljava/text/ParsePosition;)Ljava/lang/Object;", ref global::java.text.NumberFormat._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m14; public virtual global::java.math.RoundingMode getRoundingMode() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.math.RoundingMode>(this, global::java.text.NumberFormat.staticClass, "getRoundingMode", "()Ljava/math/RoundingMode;", ref global::java.text.NumberFormat._m14) as java.math.RoundingMode; } private static global::MonoJavaBridge.MethodId _m15; public virtual bool isParseIntegerOnly() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.text.NumberFormat.staticClass, "isParseIntegerOnly", "()Z", ref global::java.text.NumberFormat._m15); } private static global::MonoJavaBridge.MethodId _m16; public virtual void setParseIntegerOnly(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.NumberFormat.staticClass, "setParseIntegerOnly", "(Z)V", ref global::java.text.NumberFormat._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m17; public static global::java.text.NumberFormat getNumberInstance(java.util.Locale arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m17.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m17 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getNumberInstance", "(Ljava/util/Locale;)Ljava/text/NumberFormat;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.text.NumberFormat; } private static global::MonoJavaBridge.MethodId _m18; public static global::java.text.NumberFormat getNumberInstance() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m18.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m18 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getNumberInstance", "()Ljava/text/NumberFormat;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m18)) as java.text.NumberFormat; } private static global::MonoJavaBridge.MethodId _m19; public static global::java.text.NumberFormat getIntegerInstance(java.util.Locale arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m19.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m19 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getIntegerInstance", "(Ljava/util/Locale;)Ljava/text/NumberFormat;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.text.NumberFormat; } private static global::MonoJavaBridge.MethodId _m20; public static global::java.text.NumberFormat getIntegerInstance() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m20.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m20 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getIntegerInstance", "()Ljava/text/NumberFormat;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m20)) as java.text.NumberFormat; } private static global::MonoJavaBridge.MethodId _m21; public static global::java.text.NumberFormat getCurrencyInstance(java.util.Locale arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m21.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m21 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getCurrencyInstance", "(Ljava/util/Locale;)Ljava/text/NumberFormat;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.text.NumberFormat; } private static global::MonoJavaBridge.MethodId _m22; public static global::java.text.NumberFormat getCurrencyInstance() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m22.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m22 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getCurrencyInstance", "()Ljava/text/NumberFormat;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m22)) as java.text.NumberFormat; } private static global::MonoJavaBridge.MethodId _m23; public static global::java.text.NumberFormat getPercentInstance(java.util.Locale arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m23.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m23 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getPercentInstance", "(Ljava/util/Locale;)Ljava/text/NumberFormat;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.text.NumberFormat; } private static global::MonoJavaBridge.MethodId _m24; public static global::java.text.NumberFormat getPercentInstance() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m24.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m24 = @__env.GetStaticMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "getPercentInstance", "()Ljava/text/NumberFormat;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m24)) as java.text.NumberFormat; } private static global::MonoJavaBridge.MethodId _m25; public virtual bool isGroupingUsed() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.text.NumberFormat.staticClass, "isGroupingUsed", "()Z", ref global::java.text.NumberFormat._m25); } private static global::MonoJavaBridge.MethodId _m26; public virtual void setGroupingUsed(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.NumberFormat.staticClass, "setGroupingUsed", "(Z)V", ref global::java.text.NumberFormat._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m27; public virtual int getMaximumIntegerDigits() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.text.NumberFormat.staticClass, "getMaximumIntegerDigits", "()I", ref global::java.text.NumberFormat._m27); } private static global::MonoJavaBridge.MethodId _m28; public virtual void setMaximumIntegerDigits(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.NumberFormat.staticClass, "setMaximumIntegerDigits", "(I)V", ref global::java.text.NumberFormat._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m29; public virtual int getMinimumIntegerDigits() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.text.NumberFormat.staticClass, "getMinimumIntegerDigits", "()I", ref global::java.text.NumberFormat._m29); } private static global::MonoJavaBridge.MethodId _m30; public virtual void setMinimumIntegerDigits(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.NumberFormat.staticClass, "setMinimumIntegerDigits", "(I)V", ref global::java.text.NumberFormat._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; public virtual int getMaximumFractionDigits() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.text.NumberFormat.staticClass, "getMaximumFractionDigits", "()I", ref global::java.text.NumberFormat._m31); } private static global::MonoJavaBridge.MethodId _m32; public virtual void setMaximumFractionDigits(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.NumberFormat.staticClass, "setMaximumFractionDigits", "(I)V", ref global::java.text.NumberFormat._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m33; public virtual int getMinimumFractionDigits() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.text.NumberFormat.staticClass, "getMinimumFractionDigits", "()I", ref global::java.text.NumberFormat._m33); } private static global::MonoJavaBridge.MethodId _m34; public virtual void setMinimumFractionDigits(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.NumberFormat.staticClass, "setMinimumFractionDigits", "(I)V", ref global::java.text.NumberFormat._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m35; public virtual global::java.util.Currency getCurrency() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.util.Currency>(this, global::java.text.NumberFormat.staticClass, "getCurrency", "()Ljava/util/Currency;", ref global::java.text.NumberFormat._m35) as java.util.Currency; } private static global::MonoJavaBridge.MethodId _m36; public virtual void setCurrency(java.util.Currency arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.NumberFormat.staticClass, "setCurrency", "(Ljava/util/Currency;)V", ref global::java.text.NumberFormat._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m37; public virtual void setRoundingMode(java.math.RoundingMode arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.NumberFormat.staticClass, "setRoundingMode", "(Ljava/math/RoundingMode;)V", ref global::java.text.NumberFormat._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m38; protected NumberFormat() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.text.NumberFormat._m38.native == global::System.IntPtr.Zero) global::java.text.NumberFormat._m38 = @__env.GetMethodIDNoThrow(global::java.text.NumberFormat.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.text.NumberFormat.staticClass, global::java.text.NumberFormat._m38); Init(@__env, handle); } public static int INTEGER_FIELD { get { return 0; } } public static int FRACTION_FIELD { get { return 1; } } static NumberFormat() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.text.NumberFormat.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/text/NumberFormat")); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.text.NumberFormat))] internal sealed partial class NumberFormat_ : java.text.NumberFormat { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal NumberFormat_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override global::java.lang.StringBuffer format(double arg0, java.lang.StringBuffer arg1, java.text.FieldPosition arg2) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.StringBuffer>(this, global::java.text.NumberFormat_.staticClass, "format", "(DLjava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", ref global::java.text.NumberFormat_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.lang.StringBuffer; } private static global::MonoJavaBridge.MethodId _m1; public override global::java.lang.StringBuffer format(long arg0, java.lang.StringBuffer arg1, java.text.FieldPosition arg2) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.StringBuffer>(this, global::java.text.NumberFormat_.staticClass, "format", "(JLjava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", ref global::java.text.NumberFormat_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.lang.StringBuffer; } private static global::MonoJavaBridge.MethodId _m2; public override global::java.lang.Number parse(java.lang.String arg0, java.text.ParsePosition arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.text.NumberFormat_.staticClass, "parse", "(Ljava/lang/String;Ljava/text/ParsePosition;)Ljava/lang/Number;", ref global::java.text.NumberFormat_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.Number; } static NumberFormat_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.text.NumberFormat_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/text/NumberFormat")); } } }
using System; using System.IO; using System.Linq; using System.Net; using Newtonsoft.Json; using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Craft.Net.Client { public class Session { public static Session DoLogin(string username, string password) { var serializer = new JsonSerializer(); try { var request = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate"); request.ContentType = "application/json"; request.Method = "POST"; var token = Guid.NewGuid().ToString(); var blob = new AuthenticationBlob(username, password, token); var json = JsonConvert.SerializeObject(blob); var stream = request.GetRequestStream(); using (var writer = new StreamWriter(stream)) writer.Write(json); var response = request.GetResponse(); stream = response.GetResponseStream(); var session = serializer.Deserialize<Session>(new JsonTextReader(new StreamReader(stream))); session.UserName = username; return session; } catch (WebException e) { var stream = e.Response.GetResponseStream(); var json = new StreamReader(stream).ReadToEnd(); stream.Close(); throw JsonConvert.DeserializeObject<MinecraftAuthenticationException>(json); } } private class AuthenticationBlob { public AuthenticationBlob(string username, string password, string token) { Username = username; Password = password; ClientToken = token; Agent = new AgentBlob(); RequestUser = true; } public class AgentBlob { public AgentBlob() { // TODO: Update if needed, per https://twitter.com/sircmpwn/status/365306166638690304 Name = "Minecraft"; Version = 1; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("version")] public int Version { get; set; } } [JsonProperty("agent")] public AgentBlob Agent { get; set; } [JsonProperty("username")] public string Username { get; set; } [JsonProperty("password")] public string Password { get; set; } [JsonProperty("clientToken")] public string ClientToken { get; set; } [JsonProperty("requestUser")] public bool RequestUser { get; set; } } private class RefreshBlob { public RefreshBlob(Session session) { AccessToken = session.AccessToken; ClientToken = session.ClientToken; SelectedProfile = session.SelectedProfile; RequestUser = true; } [JsonProperty("accessToken")] public string AccessToken { get; set; } [JsonProperty("clientToken")] public string ClientToken { get; set; } [JsonProperty("selectedProfile")] public Profile SelectedProfile { get; set; } [JsonProperty("requestUser")] public bool RequestUser { get; set; } [JsonProperty("user")] public MojangUser User { get; set; } } public class MinecraftAuthenticationException : Exception { public MinecraftAuthenticationException() { } [JsonProperty("error")] public string Error { get; set; } [JsonProperty("errorMessage")] public string ErrorMessage { get; set; } [JsonProperty("cause")] public string Cause { get; set; } } public class Profile { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("name")] public string Name { get; set; } } public class MojangUser { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("properties")] public IList<Userproperty> Properties { get; set; } } public class Userproperty { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("value")] public string Value { get; set; } } public Session(string userName) { AvailableProfiles = new Profile[] { new Profile { Name = userName, Id = Guid.NewGuid().ToString() } }; SelectedProfile = AvailableProfiles[0]; } /// <summary> /// Refreshes this session, so it may be used again. You will need to re-save it if you've /// saved it to disk. /// </summary> public void Refresh() { if (!OnlineMode) throw new InvalidOperationException("This is an offline-mode session."); var serializer = new JsonSerializer(); try { var request = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/refresh"); request.ContentType = "application/json"; request.Method = "POST"; var blob = new RefreshBlob(this); var stream = request.GetRequestStream(); serializer.Serialize(new StreamWriter(stream), blob); stream.Close(); var response = request.GetResponse(); stream = response.GetResponseStream(); blob = serializer.Deserialize<RefreshBlob>(new JsonTextReader(new StreamReader(stream))); this.AccessToken = blob.AccessToken; this.ClientToken = blob.ClientToken; this.User = blob.User; this.SelectedProfile = blob.SelectedProfile; // TODO: Add profile to available profiles if need be } catch (WebException e) { var stream = e.Response.GetResponseStream(); throw serializer.Deserialize<WebException>(new JsonTextReader(new StreamReader(stream))); } } [JsonProperty("availableProfiles")] public Profile[] AvailableProfiles { get; set; } [JsonProperty("selectedProfile")] public Profile SelectedProfile { get; set; } [JsonProperty("accessToken")] public string AccessToken { get; set; } [JsonProperty("clientToken")] public string ClientToken { get; set; } /// <summary> /// This is NOT the name of the player, which can be found in SelectedProfile. This is the username /// the user logged in with. /// </summary> [JsonIgnore] public string UserName { get; set; } [JsonIgnore] public string SessionId { get { return "token:" + AccessToken + ":" + SelectedProfile.Id; } } [JsonIgnore] public bool OnlineMode { get { return AccessToken != null; } } [JsonProperty("user")] public MojangUser User { get; set; } public static IList<ServiceStatus> ServiceStatuses() { using (WebClient wc = new WebClient()) { string status = wc.DownloadString("http://status.mojang.com/check"); JArray ja = JArray.Parse(status); IList<ServiceStatus> list = new List<ServiceStatus>(); foreach (JObject item in ja) { ServiceStatus statusItem = new ServiceStatus(); statusItem.Name = item.Properties().Select(p => p.Name).First(); statusItem.Status = item.Value<string>(statusItem.Name); list.Add(statusItem); } return list; } } public class ServiceStatus { public ServiceStatus() { } public string Name { get; set; } public string Status { get; set; } } } }
using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Runtime.Serialization; namespace Alchemy4Tridion.Plugins.Clients.CoreService { [GeneratedCode("System.Runtime.Serialization", "4.0.0.0"), DebuggerStepThrough, DataContract(Name = "PublicationData", Namespace = "http://www.sdltridion.com/ContentManager/R6"), KnownType(typeof(BluePrintNodeData))] public class PublicationData : RepositoryData { private LinkToComponentTemplateData ComponentSnapshotTemplateField; private LinkToProcessDefinitionData ComponentTemplateProcessField; private LinkToComponentTemplateData DefaultComponentTemplateField; private LinkToPageTemplateData DefaultPageTemplateField; private LinkToTemplateBuildingBlockData DefaultTemplateBuildingBlockField; private string MultimediaPathField; private string MultimediaUrlField; private LinkToPageTemplateData PageSnapshotTemplateField; private LinkToProcessDefinitionData PageTemplateProcessField; private string PublicationPathField; private string PublicationTypeField; private string PublicationUrlField; private LinkToStructureGroupData RootStructureGroupField; private bool? ShareProcessAssociationsField; private LinkToProcessDefinitionData TemplateBundleProcessField; [DataMember(EmitDefaultValue = false)] public LinkToComponentTemplateData ComponentSnapshotTemplate { get { return this.ComponentSnapshotTemplateField; } set { this.ComponentSnapshotTemplateField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToProcessDefinitionData ComponentTemplateProcess { get { return this.ComponentTemplateProcessField; } set { this.ComponentTemplateProcessField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToComponentTemplateData DefaultComponentTemplate { get { return this.DefaultComponentTemplateField; } set { this.DefaultComponentTemplateField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToPageTemplateData DefaultPageTemplate { get { return this.DefaultPageTemplateField; } set { this.DefaultPageTemplateField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToTemplateBuildingBlockData DefaultTemplateBuildingBlock { get { return this.DefaultTemplateBuildingBlockField; } set { this.DefaultTemplateBuildingBlockField = value; } } [DataMember(EmitDefaultValue = false)] public string MultimediaPath { get { return this.MultimediaPathField; } set { this.MultimediaPathField = value; } } [DataMember(EmitDefaultValue = false)] public string MultimediaUrl { get { return this.MultimediaUrlField; } set { this.MultimediaUrlField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToPageTemplateData PageSnapshotTemplate { get { return this.PageSnapshotTemplateField; } set { this.PageSnapshotTemplateField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToProcessDefinitionData PageTemplateProcess { get { return this.PageTemplateProcessField; } set { this.PageTemplateProcessField = value; } } [DataMember(EmitDefaultValue = false)] public string PublicationPath { get { return this.PublicationPathField; } set { this.PublicationPathField = value; } } [DataMember(EmitDefaultValue = false)] public string PublicationType { get { return this.PublicationTypeField; } set { this.PublicationTypeField = value; } } [DataMember(EmitDefaultValue = false)] public string PublicationUrl { get { return this.PublicationUrlField; } set { this.PublicationUrlField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToStructureGroupData RootStructureGroup { get { return this.RootStructureGroupField; } set { this.RootStructureGroupField = value; } } [DataMember(EmitDefaultValue = false)] public bool? ShareProcessAssociations { get { return this.ShareProcessAssociationsField; } set { this.ShareProcessAssociationsField = value; } } [DataMember(EmitDefaultValue = false)] public LinkToProcessDefinitionData TemplateBundleProcess { get { return this.TemplateBundleProcessField; } set { this.TemplateBundleProcessField = value; } } } }
//////////////////////////////////////////////////////////////////////////////// // // @module Android Native Plugin for Unity3D // @author Osipov Stanislav (Stan's Assets) // @support stans.assets@gmail.com // //////////////////////////////////////////////////////////////////////////////// using UnityEngine; using System.Collections; using System.Collections.Generic; public class GooglePlayManager : SA_Singleton<GooglePlayManager> { public const string SCORE_SUBMITED = "score_submited"; public const string LEADERBOARDS_LOEADED = "leaderboards_loeaded"; public const string FRIENDS_LOADED = "players_loaded"; public const string ACHIEVEMENT_UPDATED = "achievement_updated"; public const string ACHIEVEMENTS_LOADED = "achievements_loaded"; public const string SCORE_REQUEST_RECEIVED = "score_request_received"; public const string SEND_GIFT_RESULT_RECEIVED = "send_gift_result_received"; public const string REQUESTS_INBOX_DIALOG_DISMISSED = "requests_inbox_dialog_dismissed"; public const string PENDING_GAME_REQUESTS_DETECTED = "pending_game_requests_detected"; public const string GAME_REQUESTS_ACCEPTED = "game_requests_accepted"; public const string AVALIABLE_DEVICE_ACCOUNT_LOADED = "avaliable_device_account_loaded"; public const string OAUTH_TOCKEN_LOADED = "oauth_tocken_loaded"; private GooglePlayerTemplate _player = null ; private Dictionary<string, GPLeaderBoard> _leaderBoards = new Dictionary<string, GPLeaderBoard>(); private Dictionary<string, GPAchievement> _achievements = new Dictionary<string, GPAchievement>(); private Dictionary<string, GooglePlayerTemplate> _players = new Dictionary<string, GooglePlayerTemplate>(); private List<string> _friendsList = new List<string>(); private List<string> _deviceGoogleAccountList = new List<string>(); private List<GPGameRequest> _gameRequests = new List<GPGameRequest>(); private string _loadedAuthTocken = ""; //-------------------------------------- // INITIALIZE //-------------------------------------- void Awake() { DontDestroyOnLoad(gameObject); } public void Create() { Debug.Log ("GooglePlayManager was created"); //Creating sub managers GooglePlayQuests.instance.Init(); } //-------------------------------------- // PUBLIC API CALL METHODS //-------------------------------------- public void RetriveDeviceGoogleAccounts() { AndroidNative.loadGoogleAccountNames(); } public void LoadTocken(string accountName, string scopes) { AndroidNative.loadToken(accountName, scopes); } public void LoadTocken() { AndroidNative.loadToken(); } public void InvalidateToken(string token) { AndroidNative.invalidateToken(token); } public void showAchievementsUI() { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.showAchivmentsUI (); } public void showLeaderBoardsUI() { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.showLeaderBoardsUI (); } public void showLeaderBoard(string leaderboardName) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.showLeaderBoard (leaderboardName); } public void showLeaderBoardById(string leaderboardId) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.showLeaderBoardById (leaderboardId); } public void submitScore(string leaderboardName, int score) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.submitScore (leaderboardName, score); } public void submitScoreById(string leaderboardId, int score) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.submitScoreById (leaderboardId, score); } public void loadLeaderBoards() { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.loadLeaderBoards (); } public void loadPlayerCenteredScores(string leaderboardId, GPBoardTimeSpan span, GPCollectionType collection, int maxResults) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.loadPlayerCenteredScores(leaderboardId, (int) span, (int) collection, maxResults); } public void loadTopScores(string leaderboardId, GPBoardTimeSpan span, GPCollectionType collection, int maxResults) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.loadTopScores(leaderboardId, (int) span, (int) collection, maxResults); } public void reportAchievement(string achievementName) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.reportAchievement (achievementName); } public void reportAchievementById(string achievementId) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.reportAchievementById (achievementId); } public void revealAchievement(string achievementName) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.revealAchievement (achievementName); } public void revealAchievementById(string achievementId) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.revealAchievementById (achievementId); } public void incrementAchievement(string achievementName, int numsteps) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.incrementAchievement (achievementName, numsteps.ToString()); } public void incrementAchievementById(string achievementId, int numsteps) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.incrementAchievementById (achievementId, numsteps.ToString()); } public void loadAchievements() { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.loadAchievements (); } public void resetAchievement(string achievementId) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.resetAchievement(achievementId); } public void resetLeaderBoard(string leaderboardId) { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.resetLeaderBoard(leaderboardId); } public void loadConnectedPlayers() { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.loadConnectedPlayers (); } //-------------------------------------- // GIFTS //-------------------------------------- public void SendGiftRequest(GPGameRequestType type, int requestLifetimeDays, Texture2D icon, string description, string playload = "") { if (!GooglePlayConnection.CheckState ()) { return; } byte[] val = icon.EncodeToPNG(); string bytesString = System.Convert.ToBase64String (val); AndroidNative.sendGiftRequest((int) type, playload, requestLifetimeDays, bytesString, description); } public void ShowRequestsAccepDialog() { if (!GooglePlayConnection.CheckState ()) { return; } AndroidNative.showRequestAccepDialog(); } public void AcceptRequests(params string[] ids) { if (!GooglePlayConnection.CheckState ()) { return; } if(ids.Length == 0) { return; } AndroidNative.acceptRequests(string.Join(AndroidNative.DATA_SPLITTER, ids)); } public void DismissRequest(params string[] ids) { if (!GooglePlayConnection.CheckState ()) { return; } if(ids.Length == 0) { return; } AndroidNative.dismissRequest(string.Join(AndroidNative.DATA_SPLITTER, ids)); } //-------------------------------------- // PUBLIC METHODS //-------------------------------------- public GPLeaderBoard GetLeaderBoard(string leaderboardId) { if(_leaderBoards.ContainsKey(leaderboardId)) { return _leaderBoards[leaderboardId]; } else { return null; } } public GPAchievement GetAchievement(string achievementId) { if(_achievements.ContainsKey(achievementId)) { return _achievements[achievementId]; } else { return null; } } public GooglePlayerTemplate GetPlayerById(string playerId) { if(players.ContainsKey(playerId)) { return players[playerId]; } else { return null; } } public GPGameRequest GetGameRequestById(string id) { foreach(GPGameRequest r in _gameRequests) { if(r.id.Equals(id)) { return r; } } return null; } //-------------------------------------- // GET / SET //-------------------------------------- public GooglePlayerTemplate player { get { return _player; } } public Dictionary<string, GooglePlayerTemplate> players { get { return _players; } } public Dictionary<string, GPLeaderBoard> leaderBoards { get { return _leaderBoards; } } public Dictionary<string, GPAchievement> achievements { get { return _achievements; } } public List<string> friendsList { get { return _friendsList; } } public List<GPGameRequest> gameRequests { get { return _gameRequests; } } public List<string> deviceGoogleAccountList { get { return _deviceGoogleAccountList; } } public string loadedAuthTocken { get { return _loadedAuthTocken; } } //-------------------------------------- // EVENTS //-------------------------------------- private void OnGiftSendResult(string data) { Debug.Log("OnGiftSendResult"); string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); GooglePlayGiftRequestResult result = new GooglePlayGiftRequestResult(storeData [0]); dispatch(SEND_GIFT_RESULT_RECEIVED, result); } private void OnRequestsInboxDialogDismissed(string data) { dispatch(REQUESTS_INBOX_DIALOG_DISMISSED); } private void OnAchievementsLoaded(string data) { string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); GooglePlayResult result = new GooglePlayResult (storeData [0]); if(result.isSuccess) { _achievements.Clear (); for(int i = 1; i < storeData.Length; i+=7) { if(storeData[i] == AndroidNative.DATA_EOF) { break; } GPAchievement ach = new GPAchievement (storeData[i], storeData[i + 1], storeData[i + 2], storeData[i + 3], storeData[i + 4], storeData[i + 5], storeData[i + 6] ); Debug.Log (ach.name); Debug.Log (ach.type); _achievements.Add (ach.id, ach); } Debug.Log ("Loaded: " + _achievements.Count + " Achievements"); } dispatch (ACHIEVEMENTS_LOADED, result); } private void OnAchievementUpdated(string data) { string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); GP_GamesResult result = new GP_GamesResult (storeData [0]); result.achievementId = storeData [1]; dispatch (ACHIEVEMENT_UPDATED, result); } private void OnScoreDataRecevide(string data) { Debug.Log("OnScoreDataRecevide"); string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); GooglePlayResult result = new GooglePlayResult (storeData [0]); if(result.isSuccess) { GPBoardTimeSpan timeSpan = (GPBoardTimeSpan) System.Convert.ToInt32(storeData[1]); GPCollectionType collection = (GPCollectionType) System.Convert.ToInt32(storeData[2]); string leaderboardId = storeData[3]; string leaderboardName = storeData[4]; GPLeaderBoard lb; if(_leaderBoards.ContainsKey(leaderboardId)) { lb = _leaderBoards[leaderboardId]; } else { lb = new GPLeaderBoard (leaderboardId, leaderboardName); Debug.Log("Added: " + leaderboardId); _leaderBoards.Add(leaderboardId, lb); } for(int i = 5; i < storeData.Length; i+=8) { if(storeData[i] == AndroidNative.DATA_EOF) { break; } int score = System.Convert.ToInt32(storeData[i]); int rank = System.Convert.ToInt32(storeData[i + 1]); string playerId = storeData[i + 2]; if(!players.ContainsKey(playerId)) { GooglePlayerTemplate p = new GooglePlayerTemplate (playerId, storeData[i + 3], storeData[i + 4], storeData[i + 5], storeData[i + 6], storeData[i + 7]); AddPlayer(p); } GPScore s = new GPScore(score, rank, timeSpan, collection, lb.id, playerId); lb.UpdateScore(s); if(playerId.Equals(player.playerId)) { lb.UpdateCurrentPlayerRank(rank, timeSpan, collection); } } } dispatch (SCORE_REQUEST_RECEIVED, result); } private void OnLeaderboardDataLoaded(string data) { string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); GooglePlayResult result = new GooglePlayResult (storeData [0]); if(result.isSuccess) { for(int i = 1; i < storeData.Length; i+=26) { if(storeData[i] == AndroidNative.DATA_EOF) { break; } string leaderboardId = storeData[i]; string leaderboardName = storeData [i + 1]; GPLeaderBoard lb; if(_leaderBoards.ContainsKey(leaderboardId)) { lb = _leaderBoards[leaderboardId]; } else { lb = new GPLeaderBoard (leaderboardId, leaderboardName); _leaderBoards.Add(leaderboardId, lb); } int start = i + 2; for(int j = 0; j < 6; j++) { int score = System.Convert.ToInt32(storeData[start]); int rank = System.Convert.ToInt32(storeData[start + 1]); GPBoardTimeSpan timeSpan = (GPBoardTimeSpan) System.Convert.ToInt32(storeData[start + 2]); GPCollectionType collection = (GPCollectionType) System.Convert.ToInt32(storeData[start + 3]); GPScore variant = new GPScore(score, rank, timeSpan, collection, lb.id, player.playerId); start = start + 4; lb.UpdateScore(variant); lb.UpdateCurrentPlayerRank(rank, timeSpan, collection); } } Debug.Log ("Loaded: " + _leaderBoards.Count + " Leaderboards"); } dispatch (LEADERBOARDS_LOEADED, result); } private void OnScoreSubmitted(string data) { if(data.Equals(string.Empty)) { Debug.Log("GooglePlayManager OnScoreSubmitted, no data avaiable"); return; } string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); GP_GamesResult result = new GP_GamesResult (storeData [0]); result.leaderboardId = storeData [1]; dispatch (SCORE_SUBMITED, result); } private void OnPlayerDataLoaded(string data) { Debug.Log("OnPlayerDataLoaded"); if(data.Equals(string.Empty)) { Debug.Log("GooglePlayManager OnPlayerLoaded, no data avaiable"); return; } string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); _player = new GooglePlayerTemplate (storeData [0], storeData [1], storeData [2], storeData [3], storeData [4], storeData [5]); AddPlayer(_player); } private void OnPlayersLoaded(string data) { string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); GooglePlayResult result = new GooglePlayResult (storeData [0]); if(result.isSuccess) { for(int i = 1; i < storeData.Length; i+=6) { if(storeData[i] == AndroidNative.DATA_EOF) { break; } GooglePlayerTemplate p = new GooglePlayerTemplate (storeData[i], storeData[i + 1], storeData[i + 2], storeData[i + 3], storeData[i + 4], storeData[i + 5]); AddPlayer(p); if(!_friendsList.Contains(p.playerId)) { _friendsList.Add(p.playerId); } } } Debug.Log ("OnPlayersLoaded, total:" + players.Count.ToString()); dispatch (FRIENDS_LOADED, result); } private void OnGameRequestsLoaded(string data) { _gameRequests = new List<GPGameRequest>(); if(data.Length == 0) { return; } string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); for(int i = 0; i < storeData.Length; i+=6) { if(storeData[i] == AndroidNative.DATA_EOF) { break; } GPGameRequest r = new GPGameRequest(); r.id = storeData[i]; r.playload = storeData[i +1]; r.expirationTimestamp = System.Convert.ToInt64(storeData[i + 2]); r.creationTimestamp = System.Convert.ToInt64(storeData[i + 3]); r.sender = storeData[i +4]; r.type = (GPGameRequestType) System.Convert.ToInt32(storeData[i + 5]); _gameRequests.Add(r); } dispatch(PENDING_GAME_REQUESTS_DETECTED, _gameRequests); } private void OnGameRequestsAccepted(string data) { List<GPGameRequest> acceptedList = new List<GPGameRequest>(); string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); for(int i = 0; i < storeData.Length; i+=6) { if(storeData[i] == AndroidNative.DATA_EOF) { break; } GPGameRequest r = new GPGameRequest(); r.id = storeData[i]; r.playload = storeData[i +1]; r.expirationTimestamp = System.Convert.ToInt64(storeData[i + 2]); r.creationTimestamp = System.Convert.ToInt64(storeData[i + 3]); r.sender = storeData[i + 4]; r.type = (GPGameRequestType) System.Convert.ToInt32(storeData[i + 5]); acceptedList.Add(r); } dispatch(GAME_REQUESTS_ACCEPTED, acceptedList); } private void OnAccountsLoaded(string data) { string[] storeData; storeData = data.Split(AndroidNative.DATA_SPLITTER [0]); _deviceGoogleAccountList.Clear(); foreach(string acc in storeData) { if(acc != AndroidNative.DATA_EOF) { _deviceGoogleAccountList.Add(acc); } } dispatch(AVALIABLE_DEVICE_ACCOUNT_LOADED); } private void OnTockenLoaded(string tocken) { _loadedAuthTocken = tocken; dispatch(OAUTH_TOCKEN_LOADED); } //-------------------------------------- // PRIVATE METHODS //-------------------------------------- private void AddPlayer(GooglePlayerTemplate p) { if(!_players.ContainsKey(p.playerId)) { _players.Add(p.playerId, p); } } }
using UnityEditor; using UnityEngine; using System.Linq; using System.Collections.Generic; [CustomEditor(typeof(tk2dStaticSpriteBatcher))] class tk2dStaticSpriteBatcherEditor : Editor { tk2dStaticSpriteBatcher batcher { get { return (tk2dStaticSpriteBatcher)target; } } void DrawEditorGUI() { if (GUILayout.Button("Commit")) { // Select all children, EXCLUDING self Transform[] allTransforms = batcher.transform.GetComponentsInChildren<Transform>(); allTransforms = (from t in allTransforms where t != batcher.transform select t).ToArray(); // sort sprites, smaller to larger z allTransforms = (from t in allTransforms orderby t.position.z descending select t).ToArray(); // and within the z sort by material if (allTransforms.Length == 0) { EditorUtility.DisplayDialog("StaticSpriteBatcher", "Error: No child objects found", "Ok"); return; } Dictionary<Transform, int> batchedSpriteLookup = new Dictionary<Transform, int>(); batchedSpriteLookup[batcher.transform] = -1; Matrix4x4 batcherWorldToLocal = batcher.transform.worldToLocalMatrix; batcher.spriteCollection = null; batcher.batchedSprites = new tk2dBatchedSprite[allTransforms.Length]; List<tk2dTextMeshData> allTextMeshData = new List<tk2dTextMeshData>(); int currBatchedSprite = 0; foreach (var t in allTransforms) { tk2dBaseSprite baseSprite = t.GetComponent<tk2dBaseSprite>(); tk2dTextMesh textmesh = t.GetComponent<tk2dTextMesh>(); tk2dBatchedSprite bs = new tk2dBatchedSprite(); bs.name = t.gameObject.name; bs.position = t.localPosition; bs.rotation = t.localRotation; bs.relativeMatrix = batcherWorldToLocal * t.localToWorldMatrix; if (baseSprite) { bs.baseScale = Vector3.one; bs.localScale = new Vector3(t.localScale.x * baseSprite.scale.x, t.localScale.y * baseSprite.scale.y, t.localScale.z * baseSprite.scale.z); FillBatchedSprite(bs, t.gameObject); // temp redundant - just incase batcher expects to point to a valid one, somewhere we've missed batcher.spriteCollection = baseSprite.Collection; } else if (textmesh) { bs.spriteCollection = null; bs.type = tk2dBatchedSprite.Type.TextMesh; bs.color = textmesh.color; bs.baseScale = textmesh.scale; bs.localScale = new Vector3(t.localScale.x * textmesh.scale.x, t.localScale.y * textmesh.scale.y, t.localScale.z * textmesh.scale.z); bs.FormattedText = textmesh.FormattedText; tk2dTextMeshData tmd = new tk2dTextMeshData(); tmd.font = textmesh.font; tmd.text = textmesh.text; tmd.color = textmesh.color; tmd.color2 = textmesh.color2; tmd.useGradient = textmesh.useGradient; tmd.textureGradient = textmesh.textureGradient; tmd.anchor = textmesh.anchor; tmd.kerning = textmesh.kerning; tmd.maxChars = textmesh.maxChars; tmd.inlineStyling = textmesh.inlineStyling; tmd.formatting = textmesh.formatting; tmd.wordWrapWidth = textmesh.wordWrapWidth; tmd.spacing = textmesh.Spacing; tmd.lineSpacing = textmesh.LineSpacing; bs.xRefId = allTextMeshData.Count; allTextMeshData.Add(tmd); } else { // Empty GameObject bs.spriteId = -1; bs.baseScale = Vector3.one; bs.localScale = t.localScale; bs.type = tk2dBatchedSprite.Type.EmptyGameObject; } batchedSpriteLookup[t] = currBatchedSprite; batcher.batchedSprites[currBatchedSprite++] = bs; } batcher.allTextMeshData = allTextMeshData.ToArray(); int idx = 0; foreach (var t in allTransforms) { var bs = batcher.batchedSprites[idx]; bs.parentId = batchedSpriteLookup[t.parent]; t.parent = batcher.transform; // unparent ++idx; } Transform[] directChildren = (from t in allTransforms where t.parent == batcher.transform select t).ToArray(); foreach (var t in directChildren) { GameObject.DestroyImmediate(t.gameObject); } Vector3 inverseScale = new Vector3(1.0f / batcher.scale.x, 1.0f / batcher.scale.y, 1.0f / batcher.scale.z); batcher.transform.localScale = Vector3.Scale( batcher.transform.localScale, inverseScale ); batcher.Build(); EditorUtility.SetDirty(target); } } static void RestoreBoxColliderSettings( GameObject go, float offset, float extents ) { BoxCollider boxCollider = go.GetComponent<BoxCollider>(); if (boxCollider != null) { Vector3 p = boxCollider.center; p.z = offset; boxCollider.center = p; p = boxCollider.extents; p.z = extents; boxCollider.extents = p; } } public static void FillBatchedSprite(tk2dBatchedSprite bs, GameObject go) { tk2dSprite srcSprite = go.transform.GetComponent<tk2dSprite>(); tk2dTiledSprite srcTiledSprite = go.transform.GetComponent<tk2dTiledSprite>(); tk2dSlicedSprite srcSlicedSprite = go.transform.GetComponent<tk2dSlicedSprite>(); tk2dClippedSprite srcClippedSprite = go.transform.GetComponent<tk2dClippedSprite>(); tk2dBaseSprite baseSprite = go.GetComponent<tk2dBaseSprite>(); bs.spriteId = baseSprite.spriteId; bs.spriteCollection = baseSprite.Collection; bs.baseScale = baseSprite.scale; bs.color = baseSprite.color; if (baseSprite.boxCollider != null) { bs.BoxColliderOffsetZ = baseSprite.boxCollider.center.z; bs.BoxColliderExtentZ = baseSprite.boxCollider.extents.z; } else { bs.BoxColliderOffsetZ = 0.0f; bs.BoxColliderExtentZ = 1.0f; } if (srcSprite) { bs.type = tk2dBatchedSprite.Type.Sprite; } else if (srcTiledSprite) { bs.type = tk2dBatchedSprite.Type.TiledSprite; bs.Dimensions = srcTiledSprite.dimensions; bs.anchor = srcTiledSprite.anchor; bs.SetFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider, srcTiledSprite.CreateBoxCollider); } else if (srcSlicedSprite) { bs.type = tk2dBatchedSprite.Type.SlicedSprite; bs.Dimensions = srcSlicedSprite.dimensions; bs.anchor = srcSlicedSprite.anchor; bs.SetFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider, srcSlicedSprite.CreateBoxCollider); bs.SetFlag(tk2dBatchedSprite.Flags.SlicedSprite_BorderOnly, srcSlicedSprite.BorderOnly); bs.SlicedSpriteBorderBottomLeft = new Vector2(srcSlicedSprite.borderLeft, srcSlicedSprite.borderBottom); bs.SlicedSpriteBorderTopRight = new Vector2(srcSlicedSprite.borderRight, srcSlicedSprite.borderTop); } else if (srcClippedSprite) { bs.type = tk2dBatchedSprite.Type.ClippedSprite; bs.ClippedSpriteRegionBottomLeft = srcClippedSprite.clipBottomLeft; bs.ClippedSpriteRegionTopRight = srcClippedSprite.clipTopRight; bs.SetFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider, srcClippedSprite.CreateBoxCollider); } } // This is used by other parts of code public static void RestoreBatchedSprite(GameObject go, tk2dBatchedSprite bs) { tk2dBaseSprite baseSprite = null; switch (bs.type) { case tk2dBatchedSprite.Type.EmptyGameObject: { break; } case tk2dBatchedSprite.Type.Sprite: { tk2dSprite s = tk2dBaseSprite.AddComponent<tk2dSprite>(go, bs.spriteCollection, bs.spriteId); baseSprite = s; break; } case tk2dBatchedSprite.Type.TiledSprite: { tk2dTiledSprite s = tk2dBaseSprite.AddComponent<tk2dTiledSprite>(go, bs.spriteCollection, bs.spriteId); baseSprite = s; s.dimensions = bs.Dimensions; s.anchor = bs.anchor; s.CreateBoxCollider = bs.CheckFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider); RestoreBoxColliderSettings(s.gameObject, bs.BoxColliderOffsetZ, bs.BoxColliderExtentZ); break; } case tk2dBatchedSprite.Type.SlicedSprite: { tk2dSlicedSprite s = tk2dBaseSprite.AddComponent<tk2dSlicedSprite>(go, bs.spriteCollection, bs.spriteId); baseSprite = s; s.dimensions = bs.Dimensions; s.anchor = bs.anchor; s.BorderOnly = bs.CheckFlag(tk2dBatchedSprite.Flags.SlicedSprite_BorderOnly); s.SetBorder(bs.SlicedSpriteBorderBottomLeft.x, bs.SlicedSpriteBorderBottomLeft.y, bs.SlicedSpriteBorderTopRight.x, bs.SlicedSpriteBorderTopRight.y); s.CreateBoxCollider = bs.CheckFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider); RestoreBoxColliderSettings(s.gameObject, bs.BoxColliderOffsetZ, bs.BoxColliderExtentZ); break; } case tk2dBatchedSprite.Type.ClippedSprite: { tk2dClippedSprite s = tk2dBaseSprite.AddComponent<tk2dClippedSprite>(go, bs.spriteCollection, bs.spriteId); baseSprite = s; s.clipBottomLeft = bs.ClippedSpriteRegionBottomLeft; s.clipTopRight = bs.ClippedSpriteRegionTopRight; s.CreateBoxCollider = bs.CheckFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider); RestoreBoxColliderSettings(s.gameObject, bs.BoxColliderOffsetZ, bs.BoxColliderExtentZ); break; } } baseSprite.scale = bs.baseScale; baseSprite.color = bs.color; } void DrawInstanceGUI() { if (GUILayout.Button("Edit")) { Vector3 batcherPos = batcher.transform.position; Quaternion batcherRotation = batcher.transform.rotation; batcher.transform.position = Vector3.zero; batcher.transform.rotation = Quaternion.identity; batcher.transform.localScale = Vector3.Scale(batcher.transform.localScale, batcher.scale); Dictionary<int, Transform> parents = new Dictionary<int, Transform>(); List<Transform> children = new List<Transform>(); List<GameObject> gos = new List<GameObject>(); int id; id = 0; foreach (var bs in batcher.batchedSprites) { GameObject go = new GameObject(bs.name); parents[id++] = go.transform; children.Add(go.transform); gos.Add (go); } id = 0; foreach (var bs in batcher.batchedSprites) { Transform parent = batcher.transform; if (bs.parentId != -1) parents.TryGetValue(bs.parentId, out parent); children[id++].parent = parent; } id = 0; foreach (var bs in batcher.batchedSprites) { GameObject go = gos[id]; go.transform.localPosition = bs.position; go.transform.localRotation = bs.rotation; { float sx = bs.localScale.x / ((Mathf.Abs (bs.baseScale.x) > Mathf.Epsilon) ? bs.baseScale.x : 1.0f); float sy = bs.localScale.y / ((Mathf.Abs (bs.baseScale.y) > Mathf.Epsilon) ? bs.baseScale.y : 1.0f); float sz = bs.localScale.z / ((Mathf.Abs (bs.baseScale.z) > Mathf.Epsilon) ? bs.baseScale.z : 1.0f); go.transform.localScale = new Vector3(sx, sy, sz); } if (bs.type == tk2dBatchedSprite.Type.TextMesh) { tk2dTextMesh s = go.AddComponent<tk2dTextMesh>(); if (batcher.allTextMeshData == null || bs.xRefId == -1) { Debug.LogError("Unable to find text mesh ref"); } else { tk2dTextMeshData tmd = batcher.allTextMeshData[bs.xRefId]; s.scale = bs.baseScale; s.font = tmd.font; s.text = tmd.text; s.color = bs.color; s.color2 = tmd.color2; s.useGradient = tmd.useGradient; s.textureGradient = tmd.textureGradient; s.anchor = tmd.anchor; s.scale = bs.baseScale; s.kerning = tmd.kerning; s.maxChars = tmd.maxChars; s.inlineStyling = tmd.inlineStyling; s.formatting = tmd.formatting; s.wordWrapWidth = tmd.wordWrapWidth; s.Spacing = tmd.spacing; s.LineSpacing = tmd.lineSpacing; s.Commit(); } } else { RestoreBatchedSprite(go, bs); } ++id; } batcher.batchedSprites = null; batcher.Build(); EditorUtility.SetDirty(target); batcher.transform.position = batcherPos; batcher.transform.rotation = batcherRotation; } batcher.scale = EditorGUILayout.Vector3Field("Scale", batcher.scale); batcher.SetFlag(tk2dStaticSpriteBatcher.Flags.GenerateCollider, EditorGUILayout.Toggle("Generate Collider", batcher.CheckFlag(tk2dStaticSpriteBatcher.Flags.GenerateCollider))); batcher.SetFlag(tk2dStaticSpriteBatcher.Flags.FlattenDepth, EditorGUILayout.Toggle("Flatten Depth", batcher.CheckFlag(tk2dStaticSpriteBatcher.Flags.FlattenDepth))); MeshFilter meshFilter = batcher.GetComponent<MeshFilter>(); MeshRenderer meshRenderer = batcher.GetComponent<MeshRenderer>(); if (meshFilter != null && meshFilter.sharedMesh != null && meshRenderer != null) { GUILayout.Label("Stats", EditorStyles.boldLabel); int numIndices = 0; Mesh mesh = meshFilter.sharedMesh; for (int i = 0; i < mesh.subMeshCount; ++i) { numIndices += mesh.GetTriangles(i).Length; } GUILayout.Label(string.Format("Triangles: {0}\nMaterials: {1}", numIndices / 3, meshRenderer.sharedMaterials.Length )); } } public override void OnInspectorGUI() { if (batcher.batchedSprites == null || batcher.batchedSprites.Length == 0) { DrawEditorGUI(); } else { DrawInstanceGUI(); } } [MenuItem("GameObject/Create Other/tk2d/Static Sprite Batcher", false, 13849)] static void DoCreateSpriteObject() { GameObject go = tk2dEditorUtility.CreateGameObjectInScene("Static Sprite Batcher"); tk2dStaticSpriteBatcher batcher = go.AddComponent<tk2dStaticSpriteBatcher>(); batcher.version = tk2dStaticSpriteBatcher.CURRENT_VERSION; Selection.activeGameObject = go; Undo.RegisterCreatedObjectUndo(go, "Create Static Sprite Batcher"); } }
using System; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.Graphics.Animation; using HandballWars.DataTypes; using FlatRedBall.Glue.StateInterpolation; using StateInterpolationPlugin; using FlatRedBall.Instructions; using FlatRedBall.Screens; using Microsoft.Xna.Framework; namespace HandballWars.Entities { #region Enums public enum MovementType { Ground, Air, AfterDoubleJump } public enum HorizontalDirection { Left, Right } #endregion public abstract partial class PlatformerCharacterBase : IInstructable { #region Fields /// <summary> /// Whether the character has hit its head on a solid /// collision this frame. This typically occurs when the /// character is moving up in the air. It is used to prevent /// upward velocity from being applied while the player is /// holding down the jump button. /// </summary> bool mHitHead = false; /// <summary> /// Whether the character is in the air and has double-jumped. /// This is used to determine which movement variables are active, /// effectively preventing multiple double-jumps. /// </summary> bool mHasDoubleJumped = false; /// <summary> /// The time when the jump button was last pushed. This is used to /// determine if upward velocity should be applied while the user /// holds the jump button down. /// </summary> double mTimeJumpPushed = double.NegativeInfinity; bool squishing = false; /// <summary> /// The MovementValues which were active when the user last jumped. /// These are used to determine the upward velocity to apply while /// the user holds the jump button. /// </summary> MovementValues mValuesJumpedWith; /// <summary> /// See property for information. /// </summary> MovementValues mCurrentMovement; /// <summary> /// See property for information. /// </summary> HorizontalDirection mDirectionFacing; /// <summary> /// See property for information. /// </summary> MovementType mMovementType; #endregion #region Properties /// <summary> /// Returns the current time, considering whether a Screen is active. /// This is used to control how long a user can hold the jump button during /// a jump to apply upward velocity. /// </summary> double CurrentTime { get { if (ScreenManager.CurrentScreen != null) { return ScreenManager.CurrentScreen.PauseAdjustedCurrentTime; } else { return TimeManager.CurrentTime; } } } /// <summary> /// The current movement variables used for horizontal movement and jumping. /// These automatically get set according to the default platformer logic and should /// not be manually adjusted. /// </summary> protected MovementValues CurrentMovement { get { return mCurrentMovement; } } /// <summary> /// Which direciton the character is facing. /// </summary> public HorizontalDirection DirectionFacing { get { return mDirectionFacing; } } /// <summary> /// The input object which controls whether the jump was pressed. /// Common examples include a button or keyboard key. /// </summary> public FlatRedBall.Input.IPressableInput JumpInput { get; set; } public IPressableInput FallThroughInput { get; set; } /// <summary> /// The input object which controls the horizontal movement of the character. /// Common examples include a d-pad, analog stick, or keyboard keys. /// </summary> public FlatRedBall.Input.I1DInput HorizontalInput { get; set; } public I2DInput ThrowTrajectoryInput { get; set; } public IPressableInput ThrowInput { get; set; } /// <summary> /// The ratio that the horizontal input is being held. /// -1 represents full left, 0 is neutral, +1 is full right. /// </summary> protected virtual float HorizontalRatio { get { if(!InputEnabled) { return 0; } else { return HorizontalInput.Value; } } } /// <summary> /// The current movement type. This is set by the default platformer logic and /// is used to assign the mCurrentMovement variable. /// </summary> public MovementType CurrentMovementType { get { return mMovementType; } set { mMovementType = value; switch (mMovementType) { case MovementType.Ground: mCurrentMovement = GroundMovement; break; case MovementType.Air: mCurrentMovement = AirMovement; break; case MovementType.AfterDoubleJump: mCurrentMovement = AfterDoubleJump; break; } if(CurrentMovement != null) { this.YAcceleration = CurrentMovement.Gravity; } } } /// <summary> /// Whether input is read to control the movement of the character. /// This can be turned off if the player should not be able to control /// the character. /// </summary> public bool InputEnabled { get; set; } public Ball BallHeld { get; set; } #endregion /// <summary> /// Action for when the character executes a jump. /// </summary> public Action JumpAction; private void CustomInitialize() { InitializeInput(); InitializeActions(); CurrentMovementType = MovementType.Ground; } private void InitializeActions() { var maxheight = MainSprite.Height; var relativeY = MainSprite.RelativeY; JumpAction = LandedAction = () => { if (!squishing) { squishing = true; var tweener = new Tweener(maxheight / 5.0f, maxheight, .35f, InterpolationType.Bounce, Easing.Out) { Owner = this }; var tweener2 = new Tweener(relativeY - (maxheight / 2.0f), relativeY, .35f, InterpolationType.Bounce, Easing.Out) { Owner = this }; tweener.PositionChanged += height => MainSprite.Height = height; tweener2.PositionChanged += relativey => MainSprite.RelativeY = relativey; TweenerManager.Self.Add(tweener); TweenerManager.Self.Add(tweener2); tweener.Start(); tweener2.Start(); tweener.Ended += () => squishing = false; } }; } /// <summary> /// Sets the HorizontalInput and JumpInput instances to either the keyboard or /// Xbox360GamePad index 0. This can be overridden by base classes to default /// to different input devices. /// </summary> protected abstract void InitializeInput(); private void CustomActivity() { ApplyInput(); DetermineMovementValues(); ApplyAnimation(); } private void ApplyAnimation() { if (CurrentMovementType == MovementType.Ground) { if (Math.Abs(this.XVelocity) < .00001f) { this.CurrentAnimationState = DirectionFacing == HorizontalDirection.Right ? Animation.StandRight : Animation.StandLeft; } else { this.CurrentAnimationState = DirectionFacing == HorizontalDirection.Right ? Animation.WalkRight : Animation.WalkLeft; } } else { this.CurrentAnimationState = DirectionFacing == HorizontalDirection.Right ? Animation.StandRight : Animation.StandLeft; } } /// <summary> /// Reads all input and applies the read-in values to control /// velocity and character state. /// </summary> private void ApplyInput() { ApplyHorizontalInput(); ApplyJumpInput(); ApplyFallThroughInput(); ApplyThrowInput(); } private void ApplyThrowInput() { if (this.ThrowInput.WasJustPressed && this.BallHeld != null) { this.BallHeld.Velocity = new Vector3(ThrowTrajectoryInput.X, ThrowTrajectoryInput.Y, 0); this.BallHeld.Velocity *= this.ThrowSpeed; this.BallHeld.Held = null; this.BallHeld = null; } } private void ApplyFallThroughInput() { if (FallThroughInput.IsDown) { IsFallingThroughClouds = true; } } /// <summary> /// Applies the horizontal input to control horizontal movement and state. /// </summary> private void ApplyHorizontalInput() { float horizontalRatio = HorizontalRatio; if(horizontalRatio > 0) { mDirectionFacing = HorizontalDirection.Right; } else if(horizontalRatio < 0) { mDirectionFacing = HorizontalDirection.Left; } if (this.CurrentMovement.AccelerationTimeX <= 0) { this.XVelocity = horizontalRatio * CurrentMovement.MaxSpeedX; } else { float acceleration = CurrentMovement.MaxSpeedX / CurrentMovement.AccelerationTimeX; float sign = Math.Sign(horizontalRatio); float magnitude = Math.Abs(horizontalRatio); if(sign == 0) { sign = -Math.Sign(XVelocity); magnitude = 1; } if (XVelocity == 0 || sign == Math.Sign(XVelocity)) { this.XAcceleration = sign * magnitude * CurrentMovement.MaxSpeedX / CurrentMovement.AccelerationTimeX; } else { float accelerationValue = magnitude * CurrentMovement.MaxSpeedX / CurrentMovement.DecelerationTimeX; if (Math.Abs(XVelocity) < accelerationValue * TimeManager.SecondDifference) { this.XAcceleration = 0; this.XVelocity = 0; } else { // slowing down this.XAcceleration = sign * accelerationValue; } } XVelocity = Math.Min(XVelocity, CurrentMovement.MaxSpeedX); XVelocity = Math.Max(XVelocity, -CurrentMovement.MaxSpeedX); } } /// <summary> /// Applies the jump input to control vertical velocity and state. /// </summary> private void ApplyJumpInput() { bool jumpPushed = JumpInput.WasJustPressed && InputEnabled; bool jumpDown = JumpInput.IsDown && InputEnabled; if (jumpPushed && CurrentMovement.JumpVelocity > 0 && (IsOnGround || AfterDoubleJump == null || (AfterDoubleJump != null && mHasDoubleJumped == false) || (AfterDoubleJump != null && AfterDoubleJump.JumpVelocity > 0) ) ) { mTimeJumpPushed = CurrentTime; this.YVelocity = CurrentMovement.JumpVelocity; mValuesJumpedWith = CurrentMovement; if (JumpAction != null) { JumpAction(); } if (CurrentMovementType == MovementType.Air) { mHasDoubleJumped = true ; } } double secondsSincePush = CurrentTime - mTimeJumpPushed; if (mValuesJumpedWith != null && secondsSincePush < mValuesJumpedWith.JumpApplyLength && (mValuesJumpedWith.JumpApplyByButtonHold == false || JumpInput.IsDown) ) { this.YVelocity = mValuesJumpedWith.JumpVelocity; } if (mValuesJumpedWith != null && mValuesJumpedWith.JumpApplyByButtonHold && (!JumpInput.IsDown || mHitHead) ) { mValuesJumpedWith = null; } this.YVelocity = Math.Max(-CurrentMovement.MaxFallSpeed, this.YVelocity); } private void CustomDestroy() { } private static void CustomLoadStaticContent(string contentManagerName) { } /// <summary> /// Assigns the current movement values based off of whether the user is on ground and has double-jumped or not. /// This is called automatically, but it can be overridden in derived classes to perform custom assignment of /// movement types. /// </summary> protected virtual void DetermineMovementValues() { if (IsOnGround) { mHasDoubleJumped = false; if (CurrentMovementType == MovementType.Air || CurrentMovementType == MovementType.AfterDoubleJump) { CurrentMovementType = MovementType.Ground; } } else { if (CurrentMovementType == MovementType.Ground) { CurrentMovementType = MovementType.Air; } } if (CurrentMovementType == MovementType.Air && mHasDoubleJumped) { CurrentMovementType = MovementType.AfterDoubleJump; } } /// <summary> /// Assigns animations based on the current movement values. This must be explicitly called or else /// animations won't be assigned. /// </summary> /// <param name="animations">The AnimationChainList containing all of the character's animations.</param> public virtual void SetAnimations(AnimationChainList animations) { if(this.MainSprite != null) { string chainToSet = GetChainToSet(); if(!string.IsNullOrEmpty(chainToSet)) { bool differs = MainSprite.CurrentChainName == null || MainSprite.CurrentChainName != chainToSet; if(differs) { this.MainSprite.SetAnimationChain(animations[chainToSet]); } } } } /// <summary> /// Returns the name of the animation chain to use. This contains standard /// behavior for walking, jumping, falling, and standing. This can be overridden /// in derived classes to support more types of animation. This is called by SetAnimation. /// </summary> /// <returns>The name of the animation to use.</returns> protected virtual string GetChainToSet() { string chainToSet = null; if (IsOnGround == false) { if (mDirectionFacing == HorizontalDirection.Right) { if (this.YVelocity > 0) { chainToSet = "JumpRight"; } else { chainToSet = "FallRight"; } } else { if (this.YVelocity > 0) { chainToSet = "JumpLeft"; } else { chainToSet = "FallLeft"; } } } else if (HorizontalRatio != 0) { if (mDirectionFacing == HorizontalDirection.Right) { chainToSet = "WalkRight"; } else { chainToSet = "WalkLeft"; } } else { if (mDirectionFacing == HorizontalDirection.Right) { chainToSet = "StandRight"; } else { chainToSet = "StandLeft"; } } return chainToSet; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Formats.Alembic.Sdk; using UnityEngine.Rendering; namespace UnityEngine.Formats.Alembic.Importer { internal class AlembicMesh : AlembicElement { internal class Submesh : IDisposable { public PinnedList<int> indexes = new PinnedList<int>(); public bool update = true; public void Dispose() { if (indexes != null) indexes.Dispose(); } } internal class Split : IDisposable { public PinnedList<Vector3> points = new PinnedList<Vector3>(); public PinnedList<Vector3> velocities = new PinnedList<Vector3>(); public PinnedList<Vector3> normals = new PinnedList<Vector3>(); public PinnedList<Vector4> tangents = new PinnedList<Vector4>(); public PinnedList<Vector2> uv0 = new PinnedList<Vector2>(); public PinnedList<Vector2> uv1 = new PinnedList<Vector2>(); public PinnedList<Color> rgba = new PinnedList<Color>(); public PinnedList<Color> rgb = new PinnedList<Color>(); public Mesh mesh; public GameObject host; public bool active = true; public Vector3 center = Vector3.zero; public Vector3 size = Vector3.zero; public void Dispose() { if (points != null) points.Dispose(); if (velocities != null) velocities.Dispose(); if (normals != null) normals.Dispose(); if (tangents != null) tangents.Dispose(); if (uv0 != null) uv0.Dispose(); if (uv1 != null) uv1.Dispose(); if (rgba != null) rgba.Dispose(); if (rgb != null) rgb.Dispose(); if ((mesh.hideFlags & HideFlags.DontSave) != 0) { #if UNITY_EDITOR Object.DestroyImmediate(mesh); #else Object.Destroy(mesh); #endif mesh = null; } } } aiPolyMesh m_abcSchema; aiMeshSummary m_summary; aiMeshSampleSummary m_sampleSummary; PinnedList<aiMeshSplitSummary> m_splitSummaries = new PinnedList<aiMeshSplitSummary>(); PinnedList<aiSubmeshSummary> m_submeshSummaries = new PinnedList<aiSubmeshSummary>(); PinnedList<aiPolyMeshData> m_splitData = new PinnedList<aiPolyMeshData>(); PinnedList<aiSubmeshData> m_submeshData = new PinnedList<aiSubmeshData>(); List<Split> m_splits = new List<Split>(); List<Submesh> m_submeshes = new List<Submesh>(); internal override aiSchema abcSchema { get { return m_abcSchema; } } public override bool visibility { get { return m_sampleSummary.visibility; } } public aiMeshSummary summary { get { return m_summary; } } public aiMeshSampleSummary sampleSummary { get { return m_sampleSummary; } } protected override void Dispose(bool v) { base.Dispose(v); foreach (var split in m_splits) { split.Dispose(); } } void UpdateSplits(int numSplits) { Split split = null; if (m_summary.topologyVariance == aiTopologyVariance.Heterogeneous || numSplits > 1) { for (int i = 0; i < numSplits; ++i) { if (i >= m_splits.Count) m_splits.Add(new Split()); else m_splits[i].active = true; } } else { if (m_splits.Count == 0) { split = new Split { host = abcTreeNode.gameObject, }; m_splits.Add(split); } else { m_splits[0].active = true; } } for (int i = numSplits; i < m_splits.Count; ++i) m_splits[i].active = false; } internal override void AbcSetup(aiObject abcObj, aiSchema abcSchema) { base.AbcSetup(abcObj, abcSchema); m_abcSchema = (aiPolyMesh)abcSchema; m_abcSchema.GetSummary(ref m_summary); } public override void AbcSyncDataBegin() { if (!m_abcSchema.schema.isDataUpdated) return; var sample = m_abcSchema.sample; sample.GetSummary(ref m_sampleSummary); int splitCount = m_sampleSummary.splitCount; int submeshCount = m_sampleSummary.submeshCount; m_splitSummaries.ResizeDiscard(splitCount); m_splitData.ResizeDiscard(splitCount); m_submeshSummaries.ResizeDiscard(submeshCount); m_submeshData.ResizeDiscard(submeshCount); sample.GetSplitSummaries(m_splitSummaries); sample.GetSubmeshSummaries(m_submeshSummaries); UpdateSplits(splitCount); bool topologyChanged = m_sampleSummary.topologyChanged; // setup buffers var vertexData = default(aiPolyMeshData); for (int spi = 0; spi < splitCount; ++spi) { var split = m_splits[spi]; split.active = true; int vertexCount = m_splitSummaries[spi].vertexCount; if (!m_summary.constantPoints || topologyChanged) split.points.ResizeDiscard(vertexCount); else split.points.ResizeDiscard(0); vertexData.positions = split.points; if (m_summary.hasVelocities && (!m_summary.constantVelocities || topologyChanged)) split.velocities.ResizeDiscard(vertexCount); else split.velocities.ResizeDiscard(0); vertexData.velocities = split.velocities; if (m_summary.hasNormals && (!m_summary.constantNormals || topologyChanged)) split.normals.ResizeDiscard(vertexCount); else split.normals.ResizeDiscard(0); vertexData.normals = split.normals; if (m_summary.hasTangents && (!m_summary.constantTangents || topologyChanged)) split.tangents.ResizeDiscard(vertexCount); else split.tangents.ResizeDiscard(0); vertexData.tangents = split.tangents; if (m_summary.hasUV0 && (!m_summary.constantUV0 || topologyChanged)) split.uv0.ResizeDiscard(vertexCount); else split.uv0.ResizeDiscard(0); vertexData.uv0 = split.uv0; if (m_summary.hasUV1 && (!m_summary.constantUV1 || topologyChanged)) split.uv1.ResizeDiscard(vertexCount); else split.uv1.ResizeDiscard(0); vertexData.uv1 = split.uv1; if (m_summary.hasRgba && (!m_summary.constantRgba || topologyChanged)) split.rgba.ResizeDiscard(vertexCount); else split.rgba.ResizeDiscard(0); vertexData.rgba = split.rgba; if (m_summary.hasRgb && (!m_summary.constantRgb || topologyChanged)) { split.rgb.ResizeDiscard(vertexCount); } else { split.rgb.ResizeDiscard(0); } vertexData.rgb = split.rgb; m_splitData[spi] = vertexData; } { if (m_submeshes.Count > submeshCount) m_submeshes.RemoveRange(submeshCount, m_submeshes.Count - submeshCount); while (m_submeshes.Count < submeshCount) m_submeshes.Add(new Submesh()); var submeshData = default(aiSubmeshData); for (int smi = 0; smi < submeshCount; ++smi) { var submesh = m_submeshes[smi]; m_submeshes[smi].update = true; submesh.indexes.ResizeDiscard(m_submeshSummaries[smi].indexCount); submeshData.indexes = submesh.indexes; m_submeshData[smi] = submeshData; } } // kick async copy sample.FillVertexBuffer(m_splitData, m_submeshData); } public override void AbcSyncDataEnd() { #if UNITY_EDITOR for (int s = 0; s < m_splits.Count; ++s) { var split = m_splits[s]; if (split.host == null) continue; var mf = split.host.GetComponent<MeshFilter>(); if (mf != null) mf.sharedMesh = split.mesh; } #endif if (!m_abcSchema.schema.isDataUpdated) return; // wait async copy complete var sample = m_abcSchema.sample; sample.Sync(); bool topologyChanged = m_sampleSummary.topologyChanged; if (abcTreeNode.stream.streamDescriptor.Settings.ImportVisibility) { var visible = m_sampleSummary.visibility; abcTreeNode.gameObject.SetActive(visible); if (!visible && !topologyChanged) return; } bool useSubObjects = m_sampleSummary.splitCount > 1; for (int s = 0; s < m_splits.Count; ++s) { var split = m_splits[s]; if (split.active) { // Feshly created splits may not have their host set yet if (split.host == null) { if (useSubObjects) { string name = abcTreeNode.gameObject.name + "_split_" + s; Transform trans = abcTreeNode.gameObject.transform.Find(name); if (trans == null) { GameObject go = new GameObject(); go.name = name; trans = go.GetComponent<Transform>(); trans.parent = abcTreeNode.gameObject.transform; trans.localPosition = Vector3.zero; trans.localEulerAngles = Vector3.zero; trans.localScale = Vector3.one; } split.host = trans.gameObject; } else { split.host = abcTreeNode.gameObject; } } // Feshly created splits may not have their mesh set yet if (split.mesh == null) split.mesh = AddMeshComponents(split.host); if (topologyChanged) { split.mesh.Clear(); split.mesh.subMeshCount = m_splitSummaries[s].submeshCount; } if (split.points.Count > 0) split.mesh.SetVertices(split.points.List); if (split.normals.Count > 0) split.mesh.SetNormals(split.normals.List); if (split.tangents.Count > 0) split.mesh.SetTangents(split.tangents.List); if (split.uv0.Count > 0) split.mesh.SetUVs(0, split.uv0.List); if (split.uv1.Count > 0) split.mesh.SetUVs(1, split.uv1.List); if (split.velocities.Count > 0) { #if UNITY_2019_2_OR_NEWER split.mesh.SetUVs(5, split.velocities.List); #else split.mesh.SetUVs(3, split.velocities.List); #endif } if (split.rgba.Count > 0) split.mesh.SetColors(split.rgba.List); else if (split.rgb.Count > 0) split.mesh.SetColors(split.rgb.List); // update the bounds var data = m_splitData[s]; split.mesh.bounds = new Bounds(data.center, data.extents); split.host.SetActive(true); } else { split.host.SetActive(false); } } for (int smi = 0; smi < m_sampleSummary.submeshCount; ++smi) { var submesh = m_submeshes[smi]; if (submesh.update) { var sum = m_submeshSummaries[smi]; var split = m_splits[sum.splitIndex]; if (sum.topology == aiTopology.Triangles) split.mesh.SetTriangles(submesh.indexes.List, sum.submeshIndex, false); else if (sum.topology == aiTopology.Lines) split.mesh.SetIndices(submesh.indexes.GetArray(), MeshTopology.Lines, sum.submeshIndex, false); else if (sum.topology == aiTopology.Points) split.mesh.SetIndices(submesh.indexes.GetArray(), MeshTopology.Points, sum.submeshIndex, false); else if (sum.topology == aiTopology.Quads) split.mesh.SetIndices(submesh.indexes.GetArray(), MeshTopology.Quads, sum.submeshIndex, false); } } } Mesh AddMeshComponents(GameObject go) { Mesh mesh = null; var meshFilter = go.GetComponent<MeshFilter>(); bool hasMesh = meshFilter != null && meshFilter.sharedMesh != null && meshFilter.sharedMesh.name.IndexOf("dyn: ") == 0; if (!hasMesh) { mesh = new Mesh { name = "dyn: " + go.name }; #if UNITY_2017_3_OR_NEWER mesh.indexFormat = IndexFormat.UInt32; #endif mesh.MarkDynamic(); if (meshFilter == null) meshFilter = go.AddComponent<MeshFilter>(); meshFilter.sharedMesh = mesh; var renderer = go.GetComponent<MeshRenderer>(); if (renderer == null) { renderer = go.AddComponent<MeshRenderer>(); var material = go.transform.parent.GetComponentInChildren<MeshRenderer>(true).sharedMaterial; renderer.sharedMaterial = material; } } else { mesh = UnityEngine.Object.Instantiate(meshFilter.sharedMesh); meshFilter.sharedMesh = mesh; mesh.name = "dyn: " + go.name; } return mesh; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** Class: AsyncStreamReader ** ** Purpose: For reading text from streams using a particular ** encoding in an asynchronous manner used by the process class ** ** ===========================================================*/ using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Diagnostics { internal sealed class AsyncStreamReader : IDisposable { internal const int DefaultBufferSize = 1024; // Byte buffer size private const int MinBufferSize = 128; private Stream _stream; private Encoding _encoding; private Decoder _decoder; private byte[] _byteBuffer; private char[] _charBuffer; // Record the number of valid bytes in the byteBuffer, for a few checks. // This is the maximum number of chars we can get from one call to // ReadBuffer. Used so ReadBuffer can tell when to copy data into // a user's char[] directly, instead of our internal char[]. private int _maxCharsPerBuffer; // Store a backpointer to the process class, to check for user callbacks private readonly Process _process; // Delegate to call user function. private Action<string> _userCallBack; // Internal Cancel operation private bool _cancelOperation; private ManualResetEvent _eofEvent; private Queue<string> _messageQueue; private StringBuilder _sb; private bool _bLastCarriageReturn; // Cache the last position scanned in sb when searching for lines. private int _currentLinePos; internal AsyncStreamReader(Process process, Stream stream, Action<string> callback, Encoding encoding) : this(process, stream, callback, encoding, DefaultBufferSize) { } // Creates a new AsyncStreamReader for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // internal AsyncStreamReader(Process process, Stream stream, Action<string> callback, Encoding encoding, int bufferSize) { Debug.Assert(process != null && stream != null && encoding != null && callback != null, "Invalid arguments!"); Debug.Assert(stream.CanRead, "Stream must be readable!"); Debug.Assert(bufferSize > 0, "Invalid buffer size!"); _process = process; _stream = stream; _userCallBack = callback; _encoding = encoding; _decoder = encoding.GetDecoder(); if (bufferSize < MinBufferSize) bufferSize = MinBufferSize; _byteBuffer = new byte[bufferSize]; _maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize); _charBuffer = new char[_maxCharsPerBuffer]; _eofEvent = new ManualResetEvent(false); _messageQueue = new Queue<string>(); } public void Close() { Dispose(true); } void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { if (_stream != null) _stream.Dispose(); } if (_stream != null) { _stream = null; _encoding = null; _decoder = null; _byteBuffer = null; _charBuffer = null; } if (_eofEvent != null) { _eofEvent.Dispose(); _eofEvent = null; } } public Encoding CurrentEncoding { get { return _encoding; } } public Stream BaseStream { get { return _stream; } } // User calls BeginRead to start the asynchronous read internal void BeginReadLine() { if (_cancelOperation) { _cancelOperation = false; } if (_sb == null) { _sb = new StringBuilder(DefaultBufferSize); _stream.ReadAsync(_byteBuffer, 0, _byteBuffer.Length).ContinueWith(ReadBuffer, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); } else { FlushMessageQueue(); } } internal void CancelOperation() { _cancelOperation = true; } // This is the async callback function. Only one thread could/should call this. private void ReadBuffer(Task<int> t) { int byteLen; try { byteLen = t.GetAwaiter().GetResult(); } catch (IOException) { // We should ideally consume errors from operations getting cancelled // so that we don't crash the unsuspecting parent with an unhandled exc. // This seems to come in 2 forms of exceptions (depending on platform and scenario), // namely OperationCanceledException and IOException (for errorcode that we don't // map explicitly). byteLen = 0; // Treat this as EOF } catch (OperationCanceledException) { // We should consume any OperationCanceledException from child read here // so that we don't crash the parent with an unhandled exc byteLen = 0; // Treat this as EOF } if (byteLen == 0) { // We're at EOF, we won't call this function again from here on. lock (_messageQueue) { if (_sb.Length != 0) { _messageQueue.Enqueue(_sb.ToString()); _sb.Length = 0; } _messageQueue.Enqueue(null); } try { // UserCallback could throw, we should still set the eofEvent FlushMessageQueue(); } finally { _eofEvent.Set(); } } else { int charLen = _decoder.GetChars(_byteBuffer, 0, byteLen, _charBuffer, 0); _sb.Append(_charBuffer, 0, charLen); GetLinesFromStringBuilder(); _stream.ReadAsync(_byteBuffer, 0, _byteBuffer.Length).ContinueWith(ReadBuffer, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); } } // Read lines stored in StringBuilder and the buffer we just read into. // A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // private void GetLinesFromStringBuilder() { int currentIndex = _currentLinePos; int lineStart = 0; int len = _sb.Length; // skip a beginning '\n' character of new block if last block ended // with '\r' if (_bLastCarriageReturn && (len > 0) && _sb[0] == '\n') { currentIndex = 1; lineStart = 1; _bLastCarriageReturn = false; } while (currentIndex < len) { char ch = _sb[currentIndex]; // Note the following common line feed chars: // \n - UNIX \r\n - DOS \r - Mac if (ch == '\r' || ch == '\n') { string s = _sb.ToString(lineStart, currentIndex - lineStart); lineStart = currentIndex + 1; // skip the "\n" character following "\r" character if ((ch == '\r') && (lineStart < len) && (_sb[lineStart] == '\n')) { lineStart++; currentIndex++; } lock (_messageQueue) { _messageQueue.Enqueue(s); } } currentIndex++; } if ((len > 0) && _sb[len - 1] == '\r') { _bLastCarriageReturn = true; } // Keep the rest characters which can't form a new line in string builder. if (lineStart < len) { if (lineStart == 0) { // we found no breaklines, in this case we cache the position // so next time we don't have to restart from the beginning _currentLinePos = currentIndex; } else { _sb.Remove(0, lineStart); _currentLinePos = 0; } } else { _sb.Length = 0; _currentLinePos = 0; } FlushMessageQueue(); } private void FlushMessageQueue() { while (true) { // When we call BeginReadLine, we also need to flush the queue // So there could be a race between the ReadBuffer and BeginReadLine // We need to take lock before DeQueue. if (_messageQueue.Count > 0) { lock (_messageQueue) { if (_messageQueue.Count > 0) { string s = (string)_messageQueue.Dequeue(); // skip if the read is the read is cancelled // this might happen inside UserCallBack // However, continue to drain the queue if (!_cancelOperation) { _userCallBack(s); } } } } else { break; } } } // Wait until we hit EOF. This is called from Process.WaitForExit // We will lose some information if we don't do this. internal void WaitUtilEOF() { if (_eofEvent != null) { _eofEvent.WaitOne(); _eofEvent.Dispose(); _eofEvent = null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Text; using System.Threading; using System.Security; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.Diagnostics { // READ ME: // Modifying the order or fields of this object may require other changes // to the unmanaged definition of the StackFrameHelper class, in // VM\DebugDebugger.h. The binder will catch some of these layout problems. internal class StackFrameHelper : IDisposable { [NonSerialized] private Thread targetThread; private int[] rgiOffset; private int[] rgiILOffset; // this field is here only for backwards compatibility of serialization format private MethodBase[] rgMethodBase; #pragma warning disable 414 // dynamicMethods is an array of System.Resolver objects, used to keep // DynamicMethodDescs alive for the lifetime of StackFrameHelper. private Object dynamicMethods; // Field is not used from managed. [NonSerialized] private IntPtr[] rgMethodHandle; private String[] rgAssemblyPath; private IntPtr[] rgLoadedPeAddress; private int[] rgiLoadedPeSize; private IntPtr[] rgInMemoryPdbAddress; private int[] rgiInMemoryPdbSize; // if rgiMethodToken[i] == 0, then don't attempt to get the portable PDB source/info private int[] rgiMethodToken; private String[] rgFilename; private int[] rgiLineNumber; private int[] rgiColumnNumber; [OptionalField] private bool[] rgiLastFrameFromForeignExceptionStackTrace; private GetSourceLineInfoDelegate getSourceLineInfo; private int iFrameCount; #pragma warning restore 414 private delegate void GetSourceLineInfoDelegate(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset, out string sourceFile, out int sourceLine, out int sourceColumn); private static Type s_symbolsType = null; private static MethodInfo s_symbolsMethodInfo = null; [ThreadStatic] private static int t_reentrancy = 0; public StackFrameHelper(Thread target) { targetThread = target; rgMethodBase = null; rgMethodHandle = null; rgiMethodToken = null; rgiOffset = null; rgiILOffset = null; rgAssemblyPath = null; rgLoadedPeAddress = null; rgiLoadedPeSize = null; rgInMemoryPdbAddress = null; rgiInMemoryPdbSize = null; dynamicMethods = null; rgFilename = null; rgiLineNumber = null; rgiColumnNumber = null; getSourceLineInfo = null; rgiLastFrameFromForeignExceptionStackTrace = null; // 0 means capture all frames. For StackTraces from an Exception, the EE always // captures all frames. For other uses of StackTraces, we can abort stack walking after // some limit if we want to by setting this to a non-zero value. In Whidbey this was // hard-coded to 512, but some customers complained. There shouldn't be any need to limit // this as memory/CPU is no longer allocated up front. If there is some reason to provide a // limit in the future, then we should expose it in the managed API so applications can // override it. iFrameCount = 0; } // // Initializes the stack trace helper. If fNeedFileInfo is true, initializes rgFilename, // rgiLineNumber and rgiColumnNumber fields using the portable PDB reader if not already // done by GetStackFramesInternal (on Windows for old PDB format). // internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception exception) { StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception); if (!fNeedFileInfo) return; // Check if this function is being reentered because of an exception in the code below if (t_reentrancy > 0) return; t_reentrancy++; try { if (s_symbolsMethodInfo == null) { s_symbolsType = Type.GetType( "System.Diagnostics.StackTraceSymbols, System.Diagnostics.StackTrace, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); if (s_symbolsType == null) return; s_symbolsMethodInfo = s_symbolsType.GetMethod("GetSourceLineInfo", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (s_symbolsMethodInfo == null) return; } if (getSourceLineInfo == null) { // Create an instance of System.Diagnostics.Stacktrace.Symbols object target = Activator.CreateInstance(s_symbolsType); // Create an instance delegate for the GetSourceLineInfo method getSourceLineInfo = (GetSourceLineInfoDelegate)s_symbolsMethodInfo.CreateDelegate(typeof(GetSourceLineInfoDelegate), target); } for (int index = 0; index < iFrameCount; index++) { // If there was some reason not to try get the symbols from the portable PDB reader like the module was // ENC or the source/line info was already retrieved, the method token is 0. if (rgiMethodToken[index] != 0) { getSourceLineInfo(rgAssemblyPath[index], rgLoadedPeAddress[index], rgiLoadedPeSize[index], rgInMemoryPdbAddress[index], rgiInMemoryPdbSize[index], rgiMethodToken[index], rgiILOffset[index], out rgFilename[index], out rgiLineNumber[index], out rgiColumnNumber[index]); } } } catch { } finally { t_reentrancy--; } } void IDisposable.Dispose() { if (getSourceLineInfo != null) { IDisposable disposable = getSourceLineInfo.Target as IDisposable; if (disposable != null) { disposable.Dispose(); } } } public virtual MethodBase GetMethodBase(int i) { // There may be a better way to do this. // we got RuntimeMethodHandles here and we need to go to MethodBase // but we don't know whether the reflection info has been initialized // or not. So we call GetMethods and GetConstructors on the type // and then we fetch the proper MethodBase!! IntPtr mh = rgMethodHandle[i]; if (mh.IsNull()) return null; IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this)); return RuntimeType.GetMethodBase(mhReal); } public virtual int GetOffset(int i) { return rgiOffset[i]; } public virtual int GetILOffset(int i) { return rgiILOffset[i]; } public virtual String GetFilename(int i) { return rgFilename == null ? null : rgFilename[i]; } public virtual int GetLineNumber(int i) { return rgiLineNumber == null ? 0 : rgiLineNumber[i]; } public virtual int GetColumnNumber(int i) { return rgiColumnNumber == null ? 0 : rgiColumnNumber[i]; } public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i) { return (rgiLastFrameFromForeignExceptionStackTrace == null) ? false : rgiLastFrameFromForeignExceptionStackTrace[i]; } public virtual int GetNumberOfFrames() { return iFrameCount; } // // serialization implementation // [OnSerializing] private void OnSerializing(StreamingContext context) { // this is called in the process of serializing this object. // For compatibility with Everett we need to assign the rgMethodBase field as that is the field // that will be serialized rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length]; if (rgMethodHandle != null) { for (int i = 0; i < rgMethodHandle.Length; i++) { if (!rgMethodHandle[i].IsNull()) rgMethodBase[i] = RuntimeType.GetMethodBase(new RuntimeMethodInfoStub(rgMethodHandle[i], this)); } } } [OnSerialized] private void OnSerialized(StreamingContext context) { // after we are done serializing null the rgMethodBase field rgMethodBase = null; } [OnDeserialized] private void OnDeserialized(StreamingContext context) { // after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle rgMethodHandle = (rgMethodBase == null) ? null : new IntPtr[rgMethodBase.Length]; if (rgMethodBase != null) { for (int i = 0; i < rgMethodBase.Length; i++) { if (rgMethodBase[i] != null) rgMethodHandle[i] = rgMethodBase[i].MethodHandle.Value; } } rgMethodBase = null; } } // Class which represents a description of a stack trace // There is no good reason for the methods of this class to be virtual. // In order to ensure trusted code can trust the data it gets from a // StackTrace, we use an InheritanceDemand to prevent partially-trusted // subclasses. public class StackTrace { private StackFrame[] frames; private int m_iNumOfFrames; public const int METHODS_TO_SKIP = 0; private int m_iMethodsToSkip; // Constructs a stack trace from the current location. public StackTrace() { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, false, null, null); } // Constructs a stack trace from the current location. // public StackTrace(bool fNeedFileInfo) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, null); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(int skipFrames) { if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, false, null, null); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(int skipFrames, bool fNeedFileInfo) { if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, null); } // Constructs a stack trace from the current location. public StackTrace(Exception e) { if (e == null) throw new ArgumentNullException(nameof(e)); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, false, null, e); } // Constructs a stack trace from the current location. // public StackTrace(Exception e, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException(nameof(e)); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, e); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(Exception e, int skipFrames) { if (e == null) throw new ArgumentNullException(nameof(e)); if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, false, null, e); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException(nameof(e)); if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, e); } // Constructs a "fake" stack trace, just containing a single frame. // Does not have the overhead of a full stack trace. // public StackTrace(StackFrame frame) { frames = new StackFrame[1]; frames[0] = frame; m_iMethodsToSkip = 0; m_iNumOfFrames = 1; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception e); internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames) { int iRetVal = 0; String PackageName = "System.Diagnostics"; // Check if this method is part of the System.Diagnostics // package. If so, increment counter keeping track of // System.Diagnostics functions for (int i = 0; i < iNumFrames; i++) { MethodBase mb = StackF.GetMethodBase(i); if (mb != null) { Type t = mb.DeclaringType; if (t == null) break; String ns = t.Namespace; if (ns == null) break; if (String.Compare(ns, PackageName, StringComparison.Ordinal) != 0) break; } iRetVal++; } return iRetVal; } // Retrieves an object with stack trace information encoded. // It leaves out the first "iSkip" lines of the stacktrace. // private void CaptureStackTrace(int iSkip, bool fNeedFileInfo, Thread targetThread, Exception e) { m_iMethodsToSkip += iSkip; using (StackFrameHelper StackF = new StackFrameHelper(targetThread)) { StackF.InitializeSourceInfo(0, fNeedFileInfo, e); m_iNumOfFrames = StackF.GetNumberOfFrames(); if (m_iMethodsToSkip > m_iNumOfFrames) m_iMethodsToSkip = m_iNumOfFrames; if (m_iNumOfFrames != 0) { frames = new StackFrame[m_iNumOfFrames]; for (int i = 0; i < m_iNumOfFrames; i++) { bool fDummy1 = true; bool fDummy2 = true; StackFrame sfTemp = new StackFrame(fDummy1, fDummy2); sfTemp.SetMethodBase(StackF.GetMethodBase(i)); sfTemp.SetOffset(StackF.GetOffset(i)); sfTemp.SetILOffset(StackF.GetILOffset(i)); sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i)); if (fNeedFileInfo) { sfTemp.SetFileName(StackF.GetFilename(i)); sfTemp.SetLineNumber(StackF.GetLineNumber(i)); sfTemp.SetColumnNumber(StackF.GetColumnNumber(i)); } frames[i] = sfTemp; } // CalculateFramesToSkip skips all frames in the System.Diagnostics namespace, // but this is not desired if building a stack trace from an exception. if (e == null) m_iMethodsToSkip += CalculateFramesToSkip(StackF, m_iNumOfFrames); m_iNumOfFrames -= m_iMethodsToSkip; if (m_iNumOfFrames < 0) { m_iNumOfFrames = 0; } } // In case this is the same object being re-used, set frames to null else frames = null; } } // Property to get the number of frames in the stack trace // public virtual int FrameCount { get { return m_iNumOfFrames; } } // Returns a given stack frame. Stack frames are numbered starting at // zero, which is the last stack frame pushed. // public virtual StackFrame GetFrame(int index) { if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0)) return frames[index + m_iMethodsToSkip]; return null; } // Returns an array of all stack frames for this stacktrace. // The array is ordered and sized such that GetFrames()[i] == GetFrame(i) // The nth element of this array is the same as GetFrame(n). // The length of the array is the same as FrameCount. // public virtual StackFrame[] GetFrames() { if (frames == null || m_iNumOfFrames <= 0) return null; // We have to return a subset of the array. Unfortunately this // means we have to allocate a new array and copy over. StackFrame[] array = new StackFrame[m_iNumOfFrames]; Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames); return array; } // Builds a readable representation of the stack trace // public override String ToString() { // Include a trailing newline for backwards compatibility return ToString(TraceFormat.TrailingNewLine); } // TraceFormat is Used to specify options for how the // string-representation of a StackTrace should be generated. internal enum TraceFormat { Normal, TrailingNewLine, // include a trailing new line character NoResourceLookup // to prevent infinite resource recusion } // Builds a readable representation of the stack trace, specifying // the format for backwards compatibility. internal String ToString(TraceFormat traceFormat) { bool displayFilenames = true; // we'll try, but demand may fail String word_At = "at"; String inFileLineNum = "in {0}:line {1}"; if (traceFormat != TraceFormat.NoResourceLookup) { word_At = SR.Word_At; inFileLineNum = SR.StackTrace_InFileLineNumber; } bool fFirstFrame = true; StringBuilder sb = new StringBuilder(255); for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++) { StackFrame sf = GetFrame(iFrameIndex); MethodBase mb = sf.GetMethod(); if (mb != null) { // We want a newline at the end of every line except for the last if (fFirstFrame) fFirstFrame = false; else sb.Append(Environment.NewLine); sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At); Type t = mb.DeclaringType; // if there is a type (non global method) print it if (t != null) { // Append t.FullName, replacing '+' with '.' string fullName = t.FullName; for (int i = 0; i < fullName.Length; i++) { char ch = fullName[i]; sb.Append(ch == '+' ? '.' : ch); } sb.Append('.'); } sb.Append(mb.Name); // deal with the generic portion of the method if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod) { Type[] typars = ((MethodInfo)mb).GetGenericArguments(); sb.Append('['); int k = 0; bool fFirstTyParam = true; while (k < typars.Length) { if (fFirstTyParam == false) sb.Append(','); else fFirstTyParam = false; sb.Append(typars[k].Name); k++; } sb.Append(']'); } ParameterInfo[] pi = null; try { pi = mb.GetParameters(); } catch { // The parameter info cannot be loaded, so we don't // append the parameter list. } if (pi != null) { // arguments printing sb.Append('('); bool fFirstParam = true; for (int j = 0; j < pi.Length; j++) { if (fFirstParam == false) sb.Append(", "); else fFirstParam = false; String typeName = "<UnknownType>"; if (pi[j].ParameterType != null) typeName = pi[j].ParameterType.Name; sb.Append(typeName); sb.Append(' '); sb.Append(pi[j].Name); } sb.Append(')'); } // source location printing if (displayFilenames && (sf.GetILOffset() != -1)) { // If we don't have a PDB or PDB-reading is disabled for the module, // then the file name will be null. String fileName = null; // Getting the filename from a StackFrame is a privileged operation - we won't want // to disclose full path names to arbitrarily untrusted code. Rather than just omit // this we could probably trim to just the filename so it's still mostly usefull. try { fileName = sf.GetFileName(); } catch (SecurityException) { // If the demand for displaying filenames fails, then it won't // succeed later in the loop. Avoid repeated exceptions by not trying again. displayFilenames = false; } if (fileName != null) { // tack on " in c:\tmp\MyFile.cs:line 5" sb.Append(' '); sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber()); } } if (sf.GetIsLastFrameFromForeignExceptionStackTrace()) { sb.Append(Environment.NewLine); sb.Append(SR.Exception_EndStackTraceFromPreviousThrow); } } } if (traceFormat == TraceFormat.TrailingNewLine) sb.Append(Environment.NewLine); return sb.ToString(); } // This helper is called from within the EE to construct a string representation // of the current stack trace. private static String GetManagedStackTraceStringHelper(bool fNeedFileInfo) { // Note all the frames in System.Diagnostics will be skipped when capturing // a normal stack trace (not from an exception) so we don't need to explicitly // skip the GetManagedStackTraceStringHelper frame. StackTrace st = new StackTrace(0, fNeedFileInfo); return st.ToString(); } } }
// Copyright (c) 2021 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License using System; using System.IO; using System.Text; using System.Collections; using Alachisoft.NCache.Caching; using System.Collections.Generic; using Alachisoft.NCache.Common; using Alachisoft.NCache.Caching.AutoExpiration; using Alachisoft.NCache.Caching.Messaging; using Alachisoft.NCache.Common.Caching; using Alachisoft.NCache.Util; using Alachisoft.NCache.Runtime.Events; using Alachisoft.NCache.Runtime.Exceptions; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Common.DataStructures.Clustered; namespace Alachisoft.NCache.SocketServer.Util { internal sealed class KeyPackageBuilder { private static Caching.Cache _cache = null; private static NCache _ncache = null; /// <summary> /// Cache Object used for deciding which Data Format mode current cache have. /// </summary> internal static Caching.Cache Cache { get { return KeyPackageBuilder._cache; } set { KeyPackageBuilder._cache = value; } } /// <summary> /// Make a package containing quote separated keys from list /// </summary> /// <param name="keysList">list of keys to be packaged</param> /// <returns>key package being constructed</returns> internal static string PackageKeys(ArrayList keyList) { StringBuilder keyPackage = new StringBuilder(keyList.Count * 256); for (int i = 0; i < keyList.Count; i++) keyPackage.Append((string)keyList[i] + "\""); return keyPackage.ToString(); } /// <summary> /// Make a package containing quote separated keys from list /// </summary> /// <param name="keysList">list of keys to be packaged</param> /// <returns>key package being constructed</returns> internal static string PackageKeys(ICollection keyList) { string packagedKeys = ""; if (keyList != null && keyList.Count > 0) { StringBuilder keyPackage = new StringBuilder(keyList.Count * 256); IEnumerator ie = keyList.GetEnumerator(); while(ie.MoveNext()) keyPackage.Append((string)ie.Current + "\""); packagedKeys = keyPackage.ToString(); } return packagedKeys; } internal static void PackageKeys(IDictionaryEnumerator dicEnu, out string keyPackage, out int keyCount) { StringBuilder keys = new StringBuilder(1024); keyCount = 0; while (dicEnu.MoveNext()) { keys.Append(dicEnu.Key + "\""); keyCount++; } keyPackage = keys.ToString(); } internal static void PackageKeys(IEnumerator enumerator, System.Collections.Generic.List<string> keys) { if (enumerator is IDictionaryEnumerator) { IDictionaryEnumerator ide = enumerator as IDictionaryEnumerator; while (ide.MoveNext()) { keys.Add((ide.Key).ToString()); } } else { while (enumerator.MoveNext()) { keys.Add((enumerator.Current).ToString()); } } } internal static IList PackageKeys(IEnumerator enumerator) { int estimatedSize = 0; IList ListOfKeyPackage = new ClusteredArrayList(); IList<string> keysChunkList = new ClusteredList<string>(); if (enumerator is IDictionaryEnumerator) { IDictionaryEnumerator ide = enumerator as IDictionaryEnumerator; while (ide.MoveNext()) { keysChunkList.Add((string)ide.Key); estimatedSize = estimatedSize + (((string)ide.Key).Length * sizeof(Char)); if (estimatedSize >= ServiceConfiguration.ResponseDataSize) //If size is greater than specified size then add it and create new chunck { ListOfKeyPackage.Add(keysChunkList); keysChunkList = new ClusteredList<string>(); estimatedSize = 0; } } if (estimatedSize != 0) { ListOfKeyPackage.Add(keysChunkList); } } else { while (enumerator.MoveNext()) { keysChunkList.Add((string)enumerator.Current); estimatedSize = estimatedSize + (((string)enumerator.Current).Length * sizeof(Char)); if (estimatedSize >= ServiceConfiguration.ResponseDataSize) //If size is greater than specified size then add it and create new chunck { ListOfKeyPackage.Add(keysChunkList); keysChunkList = new ClusteredList<string>(); estimatedSize = 0; } } if (estimatedSize != 0) { ListOfKeyPackage.Add(keysChunkList); } } if (ListOfKeyPackage.Count <= 0) { ListOfKeyPackage.Add(keysChunkList); } return ListOfKeyPackage; } /// <summary> /// Makes a key and data package form the keys and values of hashtable /// </summary> /// <param name="dic">Hashtable containing the keys and values to be packaged</param> /// <param name="keys">Contains packaged keys after execution</param> /// <param name="data">Contains packaged data after execution</param> /// <param name="currentContext">Current cache</param> internal static IList PackageKeysValues(IDictionary dic) { int estimatedSize = 0; IList ListOfKeyPackageResponse = new ClusteredArrayList(); if (dic != null && dic.Count > 0) { Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse keyPackageResponse = new Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse(); IDictionaryEnumerator enu = dic.GetEnumerator(); while (enu.MoveNext()) { Alachisoft.NCache.Common.Protobuf.Value value = new Alachisoft.NCache.Common.Protobuf.Value(); CompressedValueEntry cmpEntry= (CompressedValueEntry)enu.Value; UserBinaryObject ubObject = null; if (cmpEntry != null) { if (cmpEntry.Value is UserBinaryObject) ubObject = (UserBinaryObject)cmpEntry.Value; else { var flag = cmpEntry.Flag; ubObject = (UserBinaryObject)Cache.SocketServerDataService.GetClientData(cmpEntry.Value, ref flag, LanguageContext.DOTNET); } } //UserBinaryObject ubObject = Cache.SocketServerDataService.GetClientData(cmpEntry.Value, ref cmpEntry.Flag, LanguageContext.DOTNET) as UserBinaryObject; value.data.AddRange(ubObject.DataList); keyPackageResponse.keys.Add((string)enu.Key); keyPackageResponse.flag.Add(cmpEntry.Flag.Data); keyPackageResponse.values.Add(value); keyPackageResponse.itemType.Add(MiscUtil.EntryTypeToProtoItemType(cmpEntry.Type) );// (Alachisoft.NCache.Common.Protobuf.CacheItemType.ItemType)); estimatedSize = estimatedSize + ubObject.Size + (((string)enu.Key).Length * sizeof(Char)); if (estimatedSize >= ServiceConfiguration.ResponseDataSize) //If size is greater than specified size then add it and create new chunck { ListOfKeyPackageResponse.Add(keyPackageResponse); keyPackageResponse = new Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse(); estimatedSize = 0; } } if (estimatedSize != 0) { ListOfKeyPackageResponse.Add(keyPackageResponse); } } else { ListOfKeyPackageResponse.Add(new Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse()); } return ListOfKeyPackageResponse; } /// <summary> /// Makes a key and data package form the keys and values of hashtable /// </summary> /// <param name="dic">Hashtable containing the keys and values to be packaged</param> /// <param name="keys">Contains packaged keys after execution</param> /// <param name="data">Contains packaged data after execution</param> /// <param name="currentContext">Current cache</param> internal static Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse PackageKeysValues(IDictionary dic, Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse keyPackageResponse) { if (dic != null && dic.Count > 0) { if (keyPackageResponse == null) keyPackageResponse = new Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse(); ; IDictionaryEnumerator enu = dic.GetEnumerator(); while (enu.MoveNext()) { keyPackageResponse.keys.Add((string)enu.Key); CompressedValueEntry cmpEntry= (CompressedValueEntry)enu.Value; BitSet flag = cmpEntry.Flag; UserBinaryObject ubObject = Cache.SocketServerDataService.GetClientData(cmpEntry.Value, ref flag, LanguageContext.DOTNET) as UserBinaryObject; Alachisoft.NCache.Common.Protobuf.Value value = new Alachisoft.NCache.Common.Protobuf.Value(); value.data.AddRange(ubObject.DataList); keyPackageResponse.flag.Add(cmpEntry.Flag.Data); keyPackageResponse.values.Add(value); keyPackageResponse.itemType.Add(MiscUtil.EntryTypeToProtoItemType(cmpEntry.Type)); } } return keyPackageResponse; } /// <summary> /// Makes a key and data package form the keys and values of hashtable, for bulk operations /// </summary> /// <param name="dic">Hashtable containing the keys and values to be packaged</param> /// <param name="keys">Contains packaged keys after execution</param> /// <param name="data">Contains packaged data after execution</param> internal static void PackageKeysExceptions(Hashtable dic, Alachisoft.NCache.Common.Protobuf.KeyExceptionPackageResponse keyExceptionPackage) { int errorCode = -1; if (dic != null && dic.Count > 0) { IDictionaryEnumerator enu = dic.GetEnumerator(); while (enu.MoveNext()) { CacheException cacheException = enu.Value as CacheException; if (cacheException != null) { errorCode = cacheException.ErrorCode; } Exception ex = enu.Value as Exception; if (ex != null) { keyExceptionPackage.keys.Add((string)enu.Key); Alachisoft.NCache.Common.Protobuf.Exception exc = new Alachisoft.NCache.Common.Protobuf.Exception(); exc.message = ex.Message; exc.exception = ex.ToString(); exc.type = Alachisoft.NCache.Common.Protobuf.Exception.Type.GENERALFAILURE; exc.errorCode = errorCode; keyExceptionPackage.exceptions.Add(exc); } } } } /// <summary> /// /// </summary> /// <param name="dic"></param> /// <param name="keyVersionPackage"></param> internal static void PackageKeysVersion(IDictionary dic, Alachisoft.NCache.Common.Protobuf.KeyVersionPackageResponse keyVersionPackage) { if (dic != null && dic.Count > 0) { IDictionaryEnumerator enu = dic.GetEnumerator(); while (enu.MoveNext()) { ulong ver = Convert.ToUInt64(enu.Value.ToString()); if (ver != null) { keyVersionPackage.keys.Add((string)enu.Key); keyVersionPackage.versions.Add(ver); } } } } internal static ClusteredList<List<Common.Protobuf.Message>> GetMessages(IList<object> result, NCache nCache, string clientId) { int estimatedSize = 0; var listOfMessages = new ClusteredList<List<Common.Protobuf.Message>>(); if (result != null && result.Count > 0) { var messagesList = new List<Common.Protobuf.Message>(); var enu = result.GetEnumerator(); while (enu.MoveNext()) { if (enu.Current == null) continue; var cachingMessage = (Message)enu.Current; var protobufMessage = new Common.Protobuf.Message(); if (cachingMessage.PayLoad != null) // Message is a user'smessage and not an event message { var value = new Common.Protobuf.Value(); var ubObject = default(UserBinaryObject); var binaryObject = cachingMessage.PayLoad as UserBinaryObject; if (binaryObject != null) ubObject = binaryObject; if (ubObject != default(UserBinaryObject)) { value.data.AddRange(ubObject.DataList); estimatedSize = ubObject.Size + cachingMessage.MessageId.Length * sizeof(char); } protobufMessage.payload = value; } else // Message is an event message and not a user's message { protobufMessage.internalPayload = new Common.Protobuf.InternalPayload(); estimatedSize = estimatedSize + cachingMessage.MessageId.Length * sizeof(char); if (cachingMessage is EventMessage) { var cachingEventMessage = (EventMessage)cachingMessage; var protobufEventMessage = CreateProtobufEventMessage(nCache, cachingEventMessage, clientId); protobufMessage.internalPayload.eventMessage = protobufEventMessage; protobufMessage.internalPayload.payloadType = Common.Protobuf.InternalPayload.PayloadType.CACHE_ITEM_EVENTS; } } protobufMessage.flag = cachingMessage.FlagMap.Data; protobufMessage.messageId = cachingMessage.MessageId; protobufMessage.creationTime = cachingMessage.CreationTime.Ticks; protobufMessage.expirationTime = cachingMessage.MessageMetaData.ExpirationTime; protobufMessage.deliveryOption = (int)cachingMessage.MessageMetaData.DeliveryOption; protobufMessage.subscriptionType = (int)cachingMessage.MessageMetaData.SubscriptionType; protobufMessage.messageRemoveReason = (int)cachingMessage.MessageMetaData.MessgeFailureReason; if (cachingMessage.MessageMetaData.RecepientList != null) protobufMessage.recipientList.AddRange(cachingMessage.MessageMetaData.RecepientList); if (cachingMessage.MessageMetaData.SubscriptionIdentifierList != null) protobufMessage.subscriptionIdentifiers.AddRange(GetSubscriptionIds(cachingMessage.MessageMetaData.SubscriptionIdentifierList)); messagesList.Add(protobufMessage); if (estimatedSize >= ServiceConfiguration.ResponseDataSize) // If size is greater than specified size then add it and create new chunk { listOfMessages.Add(messagesList); messagesList = new List<Common.Protobuf.Message>(); estimatedSize = 0; } } if (estimatedSize != 0) { listOfMessages.Add(messagesList); } } else { listOfMessages.Add(new List<Common.Protobuf.Message>()); } return listOfMessages; } private static List<Common.Protobuf.SubscriptionIdRecepientList> GetSubscriptionIds(List<SubscriptionIdentifier> subscriptionIdentifiers) { List<Common.Protobuf.SubscriptionIdRecepientList> reciepientIdList = new List<Common.Protobuf.SubscriptionIdRecepientList>(); if (subscriptionIdentifiers != null) { foreach (var subscription in subscriptionIdentifiers) { var subId = new Common.Protobuf.SubscriptionIdRecepientList(); subId.subscriptionName = subscription.SubscriptionName; subId.policy = (int)subscription.SubscriptionPolicy; reciepientIdList.Add(subId); } } return reciepientIdList; } private static Common.Protobuf.MessageKeyValueResponse GetKeyValue(Message entry) { Common.Protobuf.MessageKeyValueResponse messageKeyValue = new Common.Protobuf.MessageKeyValueResponse(); Common.Protobuf.KeyValuePair keyValue = new Common.Protobuf.KeyValuePair(); keyValue.key = TopicConstant.DeliveryOption; int deliveryOption = (int)entry.MessageMetaData.DeliveryOption; keyValue.value = deliveryOption.ToString(); messageKeyValue.keyValuePair.Add(keyValue); return messageKeyValue; } private static Common.Protobuf.EventMessage CreateProtobufEventMessage(NCache nCache, EventMessage cachingEventMessage, string _clientId) { var protobufEventMessage = new Common.Protobuf.EventMessage(); protobufEventMessage.@event = new Common.Protobuf.EventId(); protobufEventMessage.@event.eventUniqueId = cachingEventMessage.EventID.EventUniqueID; protobufEventMessage.key = cachingEventMessage.Key; if (cachingEventMessage.CallbackInfos != null) // Item Level Events { foreach (CallbackInfo cbInfo in cachingEventMessage.CallbackInfos) { if (cbInfo.Client == _clientId) { protobufEventMessage.callbackIds.Add((short)cbInfo.Callback); protobufEventMessage.dataFilters.Add((short)cbInfo.DataFilter); } if (cachingEventMessage.EventID.EventType == Persistence.EventType.ITEM_UPDATED_CALLBACK || cachingEventMessage.EventID.EventType == Persistence.EventType.ITEM_UPDATED_EVENT) { protobufEventMessage.@event.item = EventHelper.ConvertToEventItem(cachingEventMessage.Item, cbInfo.DataFilter); protobufEventMessage.@event.oldItem = EventHelper.ConvertToEventItem(cachingEventMessage.OldItem, cbInfo.DataFilter); protobufEventMessage.eventType = Common.Protobuf.EventMessage.EventType.ITEM_UPDATED_CALLBACK; } else if (cachingEventMessage.EventID.EventType == Persistence.EventType.ITEM_REMOVED_CALLBACK || cachingEventMessage.EventID.EventType == Persistence.EventType.ITEM_REMOVED_EVENT) { protobufEventMessage.@event.item = EventHelper.ConvertToEventItem(cachingEventMessage.Item, cbInfo.DataFilter); protobufEventMessage.eventType = Common.Protobuf.EventMessage.EventType.ITEM_REMOVED_CALLBACK; switch (cachingEventMessage.RemoveReason) { case ItemRemoveReason.DependencyChanged: protobufEventMessage.@event.removeReason = 0; break; case ItemRemoveReason.Expired: protobufEventMessage.@event.removeReason = 1; break; case ItemRemoveReason.Removed: protobufEventMessage.@event.removeReason = 2; break; default: protobufEventMessage.@event.removeReason = 3; break; } } } } else // General Events { if (cachingEventMessage.EventID.EventType == Persistence.EventType.ITEM_ADDED_EVENT) { protobufEventMessage.@event.item = EventHelper.ConvertToEventItem(cachingEventMessage.Item, nCache.ItemAddedFilter); protobufEventMessage.eventType = Common.Protobuf.EventMessage.EventType.ITEM_ADDED_EVENT; } else if (cachingEventMessage.EventID.EventType == Persistence.EventType.ITEM_UPDATED_EVENT) { protobufEventMessage.@event.item = EventHelper.ConvertToEventItem(cachingEventMessage.Item, nCache.ItemUpdatedFilter); protobufEventMessage.@event.oldItem = EventHelper.ConvertToEventItem(cachingEventMessage.OldItem, nCache.ItemUpdatedFilter); protobufEventMessage.eventType = Common.Protobuf.EventMessage.EventType.ITEM_UPDATED_EVENT; } else if (cachingEventMessage.EventID.EventType == Persistence.EventType.ITEM_REMOVED_EVENT) { protobufEventMessage.@event.item = EventHelper.ConvertToEventItem(cachingEventMessage.Item, nCache.ItemRemovedFilter); protobufEventMessage.eventType = Common.Protobuf.EventMessage.EventType.ITEM_REMOVED_EVENT; switch (cachingEventMessage.RemoveReason) { case ItemRemoveReason.DependencyChanged: protobufEventMessage.@event.removeReason = 0; break; case ItemRemoveReason.Expired: protobufEventMessage.@event.removeReason = 1; break; case ItemRemoveReason.Removed: protobufEventMessage.@event.removeReason = 2; break; default: protobufEventMessage.@event.removeReason = 3; break; } } } protobufEventMessage.@event.operationCounter = cachingEventMessage.EventID.OperationCounter; protobufEventMessage.flagMap = cachingEventMessage.FlagMap.Data; return protobufEventMessage; } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.Spatial { using System; using System.Collections.Generic; using System.Diagnostics; using System.Spatial; using System.Xml; /// <summary> /// Gml Writer /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gml", Justification = "Gml is the common name for this format")] internal sealed class GmlWriter : DrawBoth { /// <summary> /// The underlying writer /// </summary> private XmlWriter writer; /// <summary> /// Stack of spatial types currently been built /// </summary> private Stack<SpatialType> parentStack; /// <summary> /// If an SRID has been written already. /// </summary> private bool coordinateSystemWritten; /// <summary> /// The Coordinate System to write /// </summary> private CoordinateSystem currentCoordinateSystem; /// <summary> /// Figure has been written to the current spatial type /// </summary> private bool figureWritten; /// <summary> /// Whether there are shapes written in the current container /// </summary> private bool shouldWriteContainerWrapper; /// <summary> /// Constructor /// </summary> /// <param name="writer">The Xml Writer to output to</param> public GmlWriter(XmlWriter writer) { this.writer = writer; this.OnReset(); } /// <summary> /// Begin drawing a spatial object /// </summary> /// <param name="type">The spatial type of the object</param> /// <returns>The type to be passed down the pipeline</returns> protected override SpatialType OnBeginGeography(SpatialType type) { this.BeginGeo(type); return type; } /// <summary> /// Draw a point in the specified coordinate /// </summary> /// <param name="position">Next position</param> /// <returns>The position to be passed down the pipeline</returns> protected override GeographyPosition OnLineTo(GeographyPosition position) { this.WritePoint(position.Latitude, position.Longitude, position.Z, position.M); return position; } /// <summary> /// Ends the current spatial object /// </summary> protected override void OnEndGeography() { this.EndGeo(); } /// <summary> /// Begin drawing a spatial object /// </summary> /// <param name="type">The spatial type of the object</param> /// <returns>The type to be passed down the pipeline</returns> protected override SpatialType OnBeginGeometry(SpatialType type) { this.BeginGeo(type); return type; } /// <summary> /// Draw a point in the specified coordinate /// </summary> /// <param name="position">Next position</param> /// <returns>The position to be passed down the pipeline</returns> protected override GeometryPosition OnLineTo(GeometryPosition position) { this.WritePoint(position.X, position.Y, position.Z, position.M); return position; } /// <summary> /// Ends the current spatial object /// </summary> protected override void OnEndGeometry() { this.EndGeo(); } /// <summary> /// Set the coordinate system /// </summary> /// <param name="coordinateSystem">The CoordinateSystem</param> /// <returns>The coordinateSystem to be passed down the pipeline</returns> protected override CoordinateSystem OnSetCoordinateSystem(CoordinateSystem coordinateSystem) { this.currentCoordinateSystem = coordinateSystem; return coordinateSystem; } /// <summary> /// Begin drawing a figure /// </summary> /// <param name="position">Next position</param> /// <returns>The position to be passed down the pipeline</returns> protected override GeographyPosition OnBeginFigure(GeographyPosition position) { this.BeginFigure(position.Latitude, position.Longitude, position.Z, position.M); return position; } /// <summary> /// Begin drawing a figure /// </summary> /// <param name="position">Next position</param> /// <returns>The position to be passed down the pipeline</returns> protected override GeometryPosition OnBeginFigure(GeometryPosition position) { BeginFigure(position.X, position.Y, position.Z, position.M); return position; } /// <summary> /// Ends the current figure /// </summary> protected override void OnEndFigure() { if (this.parentStack.Peek() == SpatialType.Polygon) { this.writer.WriteEndElement(); this.writer.WriteEndElement(); } } /// <summary> /// Setup the pipeline for reuse /// </summary> protected override void OnReset() { this.parentStack = new Stack<SpatialType>(); this.coordinateSystemWritten = false; this.currentCoordinateSystem = null; this.figureWritten = false; this.shouldWriteContainerWrapper = false; } /// <summary> /// Begin a figure /// </summary> /// <param name="x">The first coordinate</param> /// <param name="y">The second coordinate</param> /// <param name="z">The optional third coordinate</param> /// <param name="m">The optional fourth coordinate</param> private void BeginFigure(double x, double y, double? z, double? m) { if (this.parentStack.Peek() == SpatialType.Polygon) { // first figure is exterior, all subsequent figures are interior this.WriteStartElement(this.figureWritten ? GmlConstants.InteriorRing : GmlConstants.ExteriorRing); this.WriteStartElement(GmlConstants.LinearRing); } this.figureWritten = true; this.WritePoint(x, y, z, m); } /// <summary> /// Begin drawing a spatial object /// </summary> /// <param name="type">The spatial type of the object</param> private void BeginGeo(SpatialType type) { if (this.shouldWriteContainerWrapper) { Debug.Assert(this.parentStack.Count > 0, "should be inside a container"); // when the first shape in the collection is beginning, write the container's wrapper switch (this.parentStack.Peek()) { case SpatialType.MultiPoint: this.WriteStartElement(GmlConstants.PointMembers); break; case SpatialType.MultiLineString: this.WriteStartElement(GmlConstants.LineStringMembers); break; case SpatialType.MultiPolygon: this.WriteStartElement(GmlConstants.PolygonMembers); break; case SpatialType.Collection: this.WriteStartElement(GmlConstants.CollectionMembers); break; default: Debug.Assert(false, "unknown container type, incorrect flag status"); break; } this.shouldWriteContainerWrapper = false; } this.figureWritten = false; this.parentStack.Push(type); switch (type) { case SpatialType.Point: this.WriteStartElement(GmlConstants.Point); break; case SpatialType.LineString: this.WriteStartElement(GmlConstants.LineString); break; case SpatialType.Polygon: this.WriteStartElement(GmlConstants.Polygon); break; case SpatialType.MultiPoint: this.shouldWriteContainerWrapper = true; this.WriteStartElement(GmlConstants.MultiPoint); break; case SpatialType.MultiLineString: this.shouldWriteContainerWrapper = true; this.WriteStartElement(GmlConstants.MultiLineString); break; case SpatialType.MultiPolygon: this.shouldWriteContainerWrapper = true; this.WriteStartElement(GmlConstants.MultiPolygon); break; case SpatialType.Collection: this.shouldWriteContainerWrapper = true; this.WriteStartElement(GmlConstants.Collection); break; case SpatialType.FullGlobe: this.writer.WriteStartElement(GmlConstants.FullGlobe, GmlConstants.FullGlobeNamespace); break; default: throw new NotSupportedException("Unknown type " + type); } this.WriteCoordinateSystem(); } /// <summary> /// Write the element with namespaces /// </summary> /// <param name="elementName">The element name</param> private void WriteStartElement(string elementName) { this.writer.WriteStartElement(GmlConstants.GmlPrefix, elementName, GmlConstants.GmlNamespace); } /// <summary> /// Write coordinate system /// </summary> private void WriteCoordinateSystem() { Debug.Assert(this.writer.WriteState == WriteState.Element, "Writer at element start"); if (!coordinateSystemWritten && this.currentCoordinateSystem != null) { this.coordinateSystemWritten = true; var crsValue = GmlConstants.SrsPrefix + this.currentCoordinateSystem.Id; this.writer.WriteAttributeString(GmlConstants.GmlPrefix, GmlConstants.SrsName, GmlConstants.GmlNamespace, crsValue); } } /// <summary> /// Write a Point /// </summary> /// <param name="x">The first coordinate</param> /// <param name="y">The second coordinate</param> /// <param name="z">The optional third coordinate</param> /// <param name="m">The optional fourth coordinate</param> private void WritePoint(double x, double y, double? z, double? m) { this.WriteStartElement(GmlConstants.Position); this.writer.WriteValue(x); this.writer.WriteValue(" "); this.writer.WriteValue(y); if (z.HasValue) { this.writer.WriteValue(" "); this.writer.WriteValue(z.Value); if (m.HasValue) { this.writer.WriteValue(" "); this.writer.WriteValue(m.Value); } } else { if (m.HasValue) { this.writer.WriteValue(" "); this.writer.WriteValue(double.NaN); this.writer.WriteValue(" "); this.writer.WriteValue(m.Value); } } this.writer.WriteEndElement(); } /// <summary> /// End Geography/Geometry /// </summary> private void EndGeo() { SpatialType type = this.parentStack.Pop(); switch (type) { case SpatialType.MultiPoint: case SpatialType.MultiLineString: case SpatialType.MultiPolygon: case SpatialType.Collection: if (!this.shouldWriteContainerWrapper) { // container wrapper has been written, end it this.writer.WriteEndElement(); } this.writer.WriteEndElement(); // On EndGeo we should turn off wrapper, nested empty collection types relies on this call. this.shouldWriteContainerWrapper = false; break; case SpatialType.Point: if (!figureWritten) { // empty point needs an empty pos this.WriteStartElement(GmlConstants.Position); this.writer.WriteEndElement(); } this.writer.WriteEndElement(); break; case SpatialType.LineString: if (!figureWritten) { // empty linestring needs an empty posList this.WriteStartElement(GmlConstants.PositionList); this.writer.WriteEndElement(); } this.writer.WriteEndElement(); break; case SpatialType.Polygon: case SpatialType.FullGlobe: this.writer.WriteEndElement(); break; default: Debug.Assert(false, "Unknown type in stack, mismatch switch between BeginGeo() and EndGeo()?"); break; } } } }
using System; using System.Diagnostics; using System.Text; using Address = System.UInt64; #pragma warning disable 1591 // disable warnings on XML comments not being present // This code was automatically generated by the TraceParserGen tool, which converts // an ETW event manifest into strongly typed C# classes. namespace Microsoft.Diagnostics.Tracing.Parsers { using Microsoft.Diagnostics.Tracing.Parsers.ETWClrProfiler; [System.CodeDom.Compiler.GeneratedCode("traceparsergen", "2.0")] public sealed class ETWClrProfilerTraceEventParser : TraceEventParser { public static string ProviderName = "ETWClrProfiler"; public static Guid ProviderGuid = new Guid(unchecked((int)0x6652970f), unchecked((short)0x1756), unchecked((short)0x5d8d), 0x08, 0x05, 0xe9, 0xaa, 0xd1, 0x52, 0xaa, 0x84); public enum Keywords : long { GC = 0x1, GCHeap = 0x2, GCAlloc = 0x4, GCAllocSampled = 0x8, Call = 0x10, CallSampled = 0x20, DisableInlining = 0x40, Detach = 0x800000000000, }; public ETWClrProfilerTraceEventParser(TraceEventSource source) : base(source) { } public event Action<CallEnterArgs> CallEnter { add { source.RegisterEventTemplate(CallEnterTemplate(value)); } remove { source.UnregisterEventTemplate(value, 29, ProviderGuid); } } public event Action<EmptyTraceData> CaptureStateStart { add { source.RegisterEventTemplate(CaptureStateStartTemplate(value)); } remove { source.UnregisterEventTemplate(value, 24, ProviderGuid); } } public event Action<EmptyTraceData> CaptureStateStop { add { source.RegisterEventTemplate(CaptureStateStopTemplate(value)); } remove { source.UnregisterEventTemplate(value, 25, ProviderGuid); } } public event Action<ClassIDDefintionArgs> ClassIDDefintion { add { source.RegisterEventTemplate(ClassIDDefintionTemplate(value)); } remove { source.UnregisterEventTemplate(value, 1, ProviderGuid); } } public event Action<FinalizeableObjectQueuedArgs> FinalizeableObjectQueued { add { source.RegisterEventTemplate(FinalizeableObjectQueuedTemplate(value)); } remove { source.UnregisterEventTemplate(value, 11, ProviderGuid); } } public event Action<GCStartArgs> GCStart { add { source.RegisterEventTemplate(GCStartTemplate(value)); } remove { source.UnregisterEventTemplate(value, 20, ProviderGuid); } } public event Action<GCStopArgs> GCStop { add { source.RegisterEventTemplate(GCStopTemplate(value)); } remove { source.UnregisterEventTemplate(value, 21, ProviderGuid); } } public event Action<HandleCreatedArgs> HandleCreated { add { source.RegisterEventTemplate(HandleCreatedTemplate(value)); } remove { source.UnregisterEventTemplate(value, 12, ProviderGuid); } } public event Action<HandleDestroyedArgs> HandleDestroyed { add { source.RegisterEventTemplate(HandleDestroyedTemplate(value)); } remove { source.UnregisterEventTemplate(value, 13, ProviderGuid); } } public event Action<ModuleIDDefintionArgs> ModuleIDDefintion { add { source.RegisterEventTemplate(ModuleIDDefintionTemplate(value)); } remove { source.UnregisterEventTemplate(value, 2, ProviderGuid); } } public event Action<ObjectAllocatedArgs> ObjectAllocated { add { source.RegisterEventTemplate(ObjectAllocatedTemplate(value)); } remove { source.UnregisterEventTemplate(value, 10, ProviderGuid); } } public event Action<ObjectReferencesArgs> ObjectReferences { add { source.RegisterEventTemplate(ObjectReferencesTemplate(value)); } remove { source.UnregisterEventTemplate(value, 16, ProviderGuid); } } public event Action<ObjectsMovedArgs> ObjectsMoved { add { source.RegisterEventTemplate(ObjectsMovedTemplate(value)); } remove { source.UnregisterEventTemplate(value, 22, ProviderGuid); } } public event Action<ObjectsSurvivedArgs> ObjectsSurvived { add { source.RegisterEventTemplate(ObjectsSurvivedTemplate(value)); } remove { source.UnregisterEventTemplate(value, 23, ProviderGuid); } } public event Action<ProfilerErrorArgs> ProfilerError { add { source.RegisterEventTemplate(ProfilerErrorTemplate(value)); } remove { source.UnregisterEventTemplate(value, 26, ProviderGuid); } } public event Action<EmptyTraceData> ProfilerShutdown { add { source.RegisterEventTemplate(ProfilerShutdownTemplate(value)); } remove { source.UnregisterEventTemplate(value, 27, ProviderGuid); } } public event Action<RootReferencesArgs> RootReferences { add { source.RegisterEventTemplate(RootReferencesTemplate(value)); } remove { source.UnregisterEventTemplate(value, 15, ProviderGuid); } } public event Action<SamplingRateChangeArgs> SamplingRateChange { add { source.RegisterEventTemplate(SamplingRateChangeTemplate(value)); } remove { source.UnregisterEventTemplate(value, 28, ProviderGuid); } } public event Action<SendManifestArgs> SendManifest { add { source.RegisterEventTemplate(SendManifestTemplate(value)); } remove { source.UnregisterEventTemplate(value, 65534, ProviderGuid); } } #region private protected override string GetProviderName() { return ProviderName; } static private CallEnterArgs CallEnterTemplate(Action<CallEnterArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new CallEnterArgs(action, 29, 29, "CallEnter", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private EmptyTraceData CaptureStateStartTemplate(Action<EmptyTraceData> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new EmptyTraceData(action, 24, 24, "CaptureState", Guid.Empty, 1, "Start", ProviderGuid, ProviderName); } static private EmptyTraceData CaptureStateStopTemplate(Action<EmptyTraceData> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new EmptyTraceData(action, 25, 24, "CaptureState", Guid.Empty, 2, "Stop", ProviderGuid, ProviderName); } static private ClassIDDefintionArgs ClassIDDefintionTemplate(Action<ClassIDDefintionArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new ClassIDDefintionArgs(action, 1, 10, "ClassIDDefintion", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private FinalizeableObjectQueuedArgs FinalizeableObjectQueuedTemplate(Action<FinalizeableObjectQueuedArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new FinalizeableObjectQueuedArgs(action, 11, 13, "FinalizeableObjectQueued", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private GCStartArgs GCStartTemplate(Action<GCStartArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new GCStartArgs(action, 20, 1, "GC", Guid.Empty, 1, "Start", ProviderGuid, ProviderName); } static private GCStopArgs GCStopTemplate(Action<GCStopArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new GCStopArgs(action, 21, 1, "GC", Guid.Empty, 2, "Stop", ProviderGuid, ProviderName); } static private HandleCreatedArgs HandleCreatedTemplate(Action<HandleCreatedArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new HandleCreatedArgs(action, 12, 14, "HandleCreated", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private HandleDestroyedArgs HandleDestroyedTemplate(Action<HandleDestroyedArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new HandleDestroyedArgs(action, 13, 15, "HandleDestroyed", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private ModuleIDDefintionArgs ModuleIDDefintionTemplate(Action<ModuleIDDefintionArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new ModuleIDDefintionArgs(action, 2, 11, "ModuleIDDefintion", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private ObjectAllocatedArgs ObjectAllocatedTemplate(Action<ObjectAllocatedArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new ObjectAllocatedArgs(action, 10, 12, "ObjectAllocated", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private ObjectReferencesArgs ObjectReferencesTemplate(Action<ObjectReferencesArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new ObjectReferencesArgs(action, 16, 23, "ObjectReferences", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private ObjectsMovedArgs ObjectsMovedTemplate(Action<ObjectsMovedArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new ObjectsMovedArgs(action, 22, 20, "ObjectsMoved", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private ObjectsSurvivedArgs ObjectsSurvivedTemplate(Action<ObjectsSurvivedArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new ObjectsSurvivedArgs(action, 23, 21, "ObjectsSurvived", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private ProfilerErrorArgs ProfilerErrorTemplate(Action<ProfilerErrorArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new ProfilerErrorArgs(action, 26, 26, "ProfilerError", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private EmptyTraceData ProfilerShutdownTemplate(Action<EmptyTraceData> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new EmptyTraceData(action, 27, 27, "ProfilerShutdown", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private RootReferencesArgs RootReferencesTemplate(Action<RootReferencesArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new RootReferencesArgs(action, 15, 22, "RootReferences", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private SamplingRateChangeArgs SamplingRateChangeTemplate(Action<SamplingRateChangeArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new SamplingRateChangeArgs(action, 28, 28, "SamplingRateChange", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private SendManifestArgs SendManifestTemplate(Action<SendManifestArgs> action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new SendManifestArgs(action, 65534, 65534, "SendManifest", Guid.Empty, 0, "", ProviderGuid, ProviderName); } static private volatile TraceEvent[] s_templates; protected override void EnumerateTemplates(Func<string, string, EventFilterResponse> eventsToObserve, Action<TraceEvent> callback) { if (s_templates == null) { var templates = new TraceEvent[19]; templates[0] = ClassIDDefintionTemplate(null); templates[1] = ModuleIDDefintionTemplate(null); templates[2] = ObjectAllocatedTemplate(null); templates[3] = FinalizeableObjectQueuedTemplate(null); templates[4] = HandleCreatedTemplate(null); templates[5] = HandleDestroyedTemplate(null); templates[6] = RootReferencesTemplate(null); templates[7] = ObjectReferencesTemplate(null); templates[8] = GCStartTemplate(null); templates[9] = GCStopTemplate(null); templates[10] = ObjectsMovedTemplate(null); templates[11] = ObjectsSurvivedTemplate(null); templates[12] = CaptureStateStartTemplate(null); templates[13] = CaptureStateStopTemplate(null); templates[14] = ProfilerErrorTemplate(null); templates[15] = ProfilerShutdownTemplate(null); templates[16] = SamplingRateChangeTemplate(null); templates[17] = CallEnterTemplate(null); templates[18] = SendManifestTemplate(null); s_templates = templates; } foreach (var template in s_templates) if (eventsToObserve == null || eventsToObserve(template.ProviderName, template.EventName) == EventFilterResponse.AcceptEvent) callback(template); } #endregion } } namespace Microsoft.Diagnostics.Tracing.Parsers.ETWClrProfiler { public sealed class CallEnterArgs : TraceEvent { public Address FunctionID { get { return (Address)GetInt64At(0); } } public int SamplingRate { get { if (EventDataLength >= 12) { return GetInt32At(8); } return 1; } } #region Private internal CallEnterArgs(Action<CallEnterArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 8)); Debug.Assert(!(Version > 0 && EventDataLength < 8)); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<CallEnterArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "FunctionID", FunctionID); XmlAttrib(sb, "SamplingRate", SamplingRate); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "FunctionID", "SamplingRate" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return FunctionID; case 1: return SamplingRate; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<CallEnterArgs> m_target; #endregion } public sealed class ClassIDDefintionArgs : TraceEvent { public Address ClassID { get { return (Address)GetInt64At(0); } } public int Token { get { return GetInt32At(8); } } public ClassDefinitionFlags Flags { get { return (ClassDefinitionFlags)GetInt32At(12); } } public Address ModuleID { get { return (Address)GetInt64At(16); } } public string Name { get { return GetUnicodeStringAt(24); } } #region Private internal ClassIDDefintionArgs(Action<ClassIDDefintionArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != SkipUnicodeString(24))); Debug.Assert(!(Version > 0 && EventDataLength < SkipUnicodeString(24))); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<ClassIDDefintionArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "ClassID", ClassID); XmlAttrib(sb, "Token", Token); XmlAttrib(sb, "Flags", Flags); XmlAttrib(sb, "ModuleID", ModuleID); XmlAttrib(sb, "Name", Name); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "ClassID", "Token", "Flags", "ModuleID", "Name" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return ClassID; case 1: return Token; case 2: return Flags; case 3: return ModuleID; case 4: return Name; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<ClassIDDefintionArgs> m_target; #endregion } public sealed class FinalizeableObjectQueuedArgs : TraceEvent { public long ObjectID { get { return GetInt64At(0); } } public long ClassID { get { return GetInt64At(8); } } #region Private internal FinalizeableObjectQueuedArgs(Action<FinalizeableObjectQueuedArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 16)); Debug.Assert(!(Version > 0 && EventDataLength < 16)); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<FinalizeableObjectQueuedArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "ObjectID", ObjectID); XmlAttrib(sb, "ClassID", ClassID); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "ObjectID", "ClassID" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return ObjectID; case 1: return ClassID; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<FinalizeableObjectQueuedArgs> m_target; #endregion } public sealed class GCStartArgs : TraceEvent { public int GCID { get { return GetInt32At(0); } } public int Generation { get { return GetInt32At(4); } } public bool Induced { get { return GetInt32At(8) != 0; } } #region Private internal GCStartArgs(Action<GCStartArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 12)); Debug.Assert(!(Version > 0 && EventDataLength < 12)); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<GCStartArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "GCID", GCID); XmlAttrib(sb, "Generation", Generation); XmlAttrib(sb, "Induced", Induced); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "GCID", "Generation", "Induced" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return GCID; case 1: return Generation; case 2: return Induced; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<GCStartArgs> m_target; #endregion } public sealed class GCStopArgs : TraceEvent { public int GCID { get { return GetInt32At(0); } } #region Private internal GCStopArgs(Action<GCStopArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 4)); Debug.Assert(!(Version > 0 && EventDataLength < 4)); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<GCStopArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "GCID", GCID); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "GCID" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return GCID; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<GCStopArgs> m_target; #endregion } public sealed class HandleCreatedArgs : TraceEvent { public long HandleID { get { return GetInt64At(0); } } public long InitialObjectID { get { return GetInt64At(8); } } #region Private internal HandleCreatedArgs(Action<HandleCreatedArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 16)); Debug.Assert(!(Version > 0 && EventDataLength < 16)); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<HandleCreatedArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "HandleID", HandleID); XmlAttrib(sb, "InitialObjectID", InitialObjectID); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "HandleID", "InitialObjectID" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return HandleID; case 1: return InitialObjectID; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<HandleCreatedArgs> m_target; #endregion } public sealed class HandleDestroyedArgs : TraceEvent { public long HandleID { get { return GetInt64At(0); } } #region Private internal HandleDestroyedArgs(Action<HandleDestroyedArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 8)); Debug.Assert(!(Version > 0 && EventDataLength < 8)); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<HandleDestroyedArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "HandleID", HandleID); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "HandleID" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return HandleID; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<HandleDestroyedArgs> m_target; #endregion } public sealed class ModuleIDDefintionArgs : TraceEvent { public Address ModuleID { get { return (Address)GetInt64At(0); } } public Address AssemblyID { get { return (Address)GetInt64At(8); } } public string Path { get { return GetUnicodeStringAt(16); } } #region Private internal ModuleIDDefintionArgs(Action<ModuleIDDefintionArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != SkipUnicodeString(16))); Debug.Assert(!(Version > 0 && EventDataLength < SkipUnicodeString(16))); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<ModuleIDDefintionArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "ModuleID", ModuleID); XmlAttrib(sb, "AssemblyID", AssemblyID); XmlAttrib(sb, "Path", Path); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "ModuleID", "AssemblyID", "Path" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return ModuleID; case 1: return AssemblyID; case 2: return Path; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<ModuleIDDefintionArgs> m_target; #endregion } public sealed class ObjectAllocatedArgs : TraceEvent { public Address ObjectID { get { return (Address)GetInt64At(0); } } public Address ClassID { get { return (Address)GetInt64At(8); } } public long Size { get { return GetInt64At(16); } } public long RepresentativeSize { get { return GetInt64At(24); } } #region Private internal ObjectAllocatedArgs(Action<ObjectAllocatedArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 32)); Debug.Assert(!(Version > 0 && EventDataLength < 32)); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<ObjectAllocatedArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "ObjectID", ObjectID); XmlAttrib(sb, "ClassID", ClassID); XmlAttrib(sb, "Size", Size); XmlAttrib(sb, "RepresentativeSize", RepresentativeSize); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "ObjectID", "ClassID", "Size", "RepresentativeSize" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return ObjectID; case 1: return ClassID; case 2: return Size; case 3: return RepresentativeSize; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<ObjectAllocatedArgs> m_target; #endregion } public sealed class ObjectReferencesArgs : TraceEvent { public long ObjectID { get { return GetInt64At(0); } } public long ClassID { get { return GetInt64At(8); } } public long Size { get { return GetInt64At(16); } } public int ObjectRefCount { get { return GetInt32At(24); } } public Address ObjectRefs(int arrayIndex) { return GetAddressAt(28 + (arrayIndex * PointerSize)); } #region Private internal ObjectReferencesArgs(Action<ObjectReferencesArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != HostOffset(0 + (ObjectRefCount * 4) + 28, 1))); Debug.Assert(!(Version > 0 && EventDataLength < HostOffset(0 + (ObjectRefCount * 4) + 28, 1))); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<ObjectReferencesArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "ObjectID", ObjectID); XmlAttrib(sb, "ClassID", ClassID); XmlAttrib(sb, "Size", Size); XmlAttrib(sb, "ObjectRefCount", ObjectRefCount); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "ObjectID", "ClassID", "Size", "ObjectRefCount", "ObjectRefs" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return ObjectID; case 1: return ClassID; case 2: return Size; case 3: return ObjectRefCount; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<ObjectReferencesArgs> m_target; #endregion } public sealed class ObjectsMovedArgs : TraceEvent { public int Count { get { return GetInt32At(0); } } public Address RangeBases(int arrayIndex) { return GetAddressAt(4 + (PointerSize * arrayIndex)); } public Address TargetBases(int arrayIndex) { return GetAddressAt(4 + (PointerSize * Count) + (PointerSize * arrayIndex)); } public int Lengths(int arrayIndex) { return GetInt32At(4 + 2 * (PointerSize * Count) + (4 * arrayIndex)); } #region Private internal ObjectsMovedArgs(Action<ObjectsMovedArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 4 + 2 * (PointerSize * Count) + (4 * Count))); Debug.Assert(!(Version > 0 && EventDataLength < 4 + 2 * (PointerSize * Count) + (4 * Count))); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<ObjectsMovedArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "Count", Count); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "Count", "RangeBases", "TargetBases", "Lengths" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return Count; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<ObjectsMovedArgs> m_target; #endregion } public sealed class ObjectsSurvivedArgs : TraceEvent { public int Count { get { return GetInt32At(0); } } public Address RangeBases(int arrayIndex) { // The ranges are a block of pointer sized elements. that is after the 4 byte length field return GetAddressAt(4 + (PointerSize * arrayIndex)); } public int Lengths(int arrayIndex) { // The lengths are a blob of 32 bit integers that are after the RangeBases return GetInt32At(4 + (PointerSize * Count) + (4 * arrayIndex)); } #region Private internal ObjectsSurvivedArgs(Action<ObjectsSurvivedArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 4 + (PointerSize * Count) + (4 * Count))); Debug.Assert(!(Version > 0 && EventDataLength < 4 + (PointerSize * Count) + (4 * Count))); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<ObjectsSurvivedArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "Count", Count); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "Count", "RangeBases", "Lengths" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return Count; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<ObjectsSurvivedArgs> m_target; #endregion } public sealed class ProfilerErrorArgs : TraceEvent { public long ErrorCode { get { return GetInt64At(0); } } public string Message { get { return GetUnicodeStringAt(8); } } #region Private internal ProfilerErrorArgs(Action<ProfilerErrorArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != SkipUnicodeString(8))); Debug.Assert(!(Version > 0 && EventDataLength < SkipUnicodeString(8))); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<ProfilerErrorArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "ErrorCode", ErrorCode); XmlAttrib(sb, "Message", Message); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "ErrorCode", "Message" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return ErrorCode; case 1: return Message; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<ProfilerErrorArgs> m_target; #endregion } public sealed class RootReferencesArgs : TraceEvent { public int Count { get { return GetInt32At(0); } } public Address ObjectIDs(int arrayIndex) { return GetAddressAt(4 + (PointerSize * arrayIndex)); } public GCRootKind GCRootKinds(int arrayIndex) { int ret = GetInt32At(4 + PointerSize * Count + (4 * arrayIndex)); Debug.Assert((ret & 0xFFFFFF00) == 0); // assert is is less than 256, we only use 4 bits so far. return (GCRootKind)ret; } public GCRootFlags GCRootFlags(int arrayIndex) { int ret = GetInt32At(4 + PointerSize * Count + 4 * Count + 4 * arrayIndex); Debug.Assert((ret & 0xFFFFFFF0) == 0); // assert is is less than 16, we only use 4 values so far. return (GCRootFlags)ret; } public Address RootIDs(int arrayIndex) { return GetAddressAt(4 + PointerSize * Count + (2 * 4 * Count) + PointerSize * arrayIndex); } #region Private internal RootReferencesArgs(Action<RootReferencesArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != 4 + (2 * PointerSize * Count) + (2 * 4 * Count))); Debug.Assert(!(Version > 0 && EventDataLength < 4 + (2 * PointerSize * Count) + (2 * 4 * Count))); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<RootReferencesArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "Count", Count); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "Count", "ObjectIDs", "GCRootKinds", "GCRootFlags", "RootIDs" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return Count; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<RootReferencesArgs> m_target; #endregion } public sealed class SamplingRateChangeArgs : TraceEvent { public long ClassID { get { return GetInt64At(0); } } public string ClassName { get { return GetUnicodeStringAt(8); } } public int MSecDelta { get { return GetInt32At(SkipUnicodeString(8)); } } public int MinAllocPerMSec { get { return GetInt32At(SkipUnicodeString(8) + 4); } } public float NewAllocPerMSec { get { return GetSingleAt(SkipUnicodeString(8) + 8); } } public float AllocPerMSec { get { return GetSingleAt(SkipUnicodeString(8) + 12); } } public int SampleRate { get { return GetInt32At(SkipUnicodeString(8) + 16); } } #region Private internal SamplingRateChangeArgs(Action<SamplingRateChangeArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != SkipUnicodeString(8) + 20)); Debug.Assert(!(Version > 0 && EventDataLength < SkipUnicodeString(8) + 20)); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<SamplingRateChangeArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "ClassID", ClassID); XmlAttrib(sb, "ClassName", ClassName); XmlAttrib(sb, "MSecDelta", MSecDelta); XmlAttrib(sb, "MinAllocPerMSec", MinAllocPerMSec); XmlAttrib(sb, "NewAllocPerMSec", NewAllocPerMSec); XmlAttrib(sb, "AllocPerMSec", AllocPerMSec); XmlAttrib(sb, "SampleRate", SampleRate); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "ClassID", "ClassName", "MSecDelta", "MinAllocPerMSec", "NewAllocPerMSec", "AllocPerMSec", "SampleRate" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return ClassID; case 1: return ClassName; case 2: return MSecDelta; case 3: return MinAllocPerMSec; case 4: return NewAllocPerMSec; case 5: return AllocPerMSec; case 6: return SampleRate; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<SamplingRateChangeArgs> m_target; #endregion } public sealed class SendManifestArgs : TraceEvent { public int Format { get { return GetByteAt(0); } } public int MajorVersion { get { return GetByteAt(1); } } public int MinorVersion { get { return GetByteAt(2); } } public int Magic { get { return GetByteAt(3); } } public int TotalChunks { get { return GetInt16At(4); } } public int ChunkNumger { get { return GetInt16At(6); } } public string Data { get { return GetUTF8StringAt(8); } } #region Private internal SendManifestArgs(Action<SendManifestArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != SkipUTF8String(8))); Debug.Assert(!(Version > 0 && EventDataLength < SkipUTF8String(8))); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<SendManifestArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "Format", Format); XmlAttrib(sb, "MajorVersion", MajorVersion); XmlAttrib(sb, "MinorVersion", MinorVersion); XmlAttrib(sb, "Magic", Magic); XmlAttrib(sb, "TotalChunks", TotalChunks); XmlAttrib(sb, "ChunkNumger", ChunkNumger); XmlAttrib(sb, "Data", Data); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "Format", "MajorVersion", "MinorVersion", "Magic", "TotalChunks", "ChunkNumger", "Data" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return Format; case 1: return MajorVersion; case 2: return MinorVersion; case 3: return Magic; case 4: return TotalChunks; case 5: return ChunkNumger; case 6: return Data; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<SendManifestArgs> m_target; #endregion } [Flags] public enum ClassDefinitionFlags { ValueType = 0x1, Public = 0x2, Finalizable = 0x4, } [Flags] public enum GCRootFlags { Pinning = 0x1, WeakRef = 0x2, Interior = 0x4, RefCounted = 0x8, } public enum GCRootKind { Stack = 0x0, Finalizer = 0x1, Handle = 0x2, Other = 0x3, } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Web; using Aurora.DataManager; using Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework.Capabilities; using Aurora.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; namespace OpenSim.Services.CapsService { public class DisplayNamesCAPS : ICapsServiceConnector { private List<string> bannedNames = new List<string>(); private IEventQueueService m_eventQueue; private IProfileConnector m_profileConnector; private IRegionClientCapsService m_service; private IUserAccountService m_userService; #region Stream Handler #region Delegates public delegate byte[] StreamHandlerCallback( string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse); #endregion public class StreamHandler : BaseStreamHandler { private readonly StreamHandlerCallback m_callback; public StreamHandler(string httpMethod, string path, StreamHandlerCallback callback) : base(httpMethod, path) { m_callback = callback; } public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return m_callback(path, request, httpRequest, httpResponse); } } #endregion #region ICapsServiceConnector Members public void RegisterCaps(IRegionClientCapsService service) { IConfig displayNamesConfig = service.ClientCaps.Registry.RequestModuleInterface<ISimulationBase>().ConfigSource.Configs[ "DisplayNamesModule"]; if (displayNamesConfig != null) { if (!displayNamesConfig.GetBoolean("Enabled", true)) return; string bannedNamesString = displayNamesConfig.GetString("BannedUserNames", ""); if (bannedNamesString != "") bannedNames = new List<string>(bannedNamesString.Split(',')); } m_service = service; m_profileConnector = DataManager.RequestPlugin<IProfileConnector>(); m_eventQueue = service.Registry.RequestModuleInterface<IEventQueueService>(); m_userService = service.Registry.RequestModuleInterface<IUserAccountService>(); string post = CapsUtil.CreateCAPS("SetDisplayName", ""); service.AddCAPS("SetDisplayName", post); service.AddStreamHandler("SetDisplayName", new RestHTTPHandler("POST", post, ProcessSetDisplayName)); post = CapsUtil.CreateCAPS("GetDisplayNames", ""); service.AddCAPS("GetDisplayNames", post); service.AddStreamHandler("GetDisplayNames", new StreamHandler("GET", post, ProcessGetDisplayName)); } public void EnteringRegion() { } public void DeregisterCaps() { m_service.RemoveStreamHandler("SetDisplayName", "POST"); m_service.RemoveStreamHandler("GetDisplayNames", "GET"); } #endregion #region Caps Messages /// <summary> /// Set the display name for the given user /// </summary> /// <param name = "mDhttpMethod"></param> /// <param name = "agentID"></param> /// <returns></returns> private Hashtable ProcessSetDisplayName(Hashtable mDhttpMethod) { try { OSDMap rm = (OSDMap) OSDParser.DeserializeLLSDXml((string) mDhttpMethod["requestbody"]); OSDArray display_name = (OSDArray) rm["display_name"]; string oldDisplayName = display_name[0].AsString(); string newDisplayName = display_name[1].AsString(); UserAccount account = m_userService.GetUserAccount(UUID.Zero, m_service.AgentID); //Check to see if their name contains a banned character #if (!ISWIN) foreach (string bannedUserName in bannedNames) { string BannedUserName = bannedUserName.Replace(" ", ""); if (newDisplayName.ToLower().Contains(BannedUserName.ToLower())) { //Revert the name to the original and send them a warning newDisplayName = account.Name; //m_avatar.ControllingClient.SendAlertMessage ("You cannot update your display name to the name chosen, your name has been reverted. This request has been logged."); break; //No more checking } } #else if (bannedNames.Select(bannedUserName => bannedUserName.Replace(" ", "")).Any(BannedUserName => newDisplayName.ToLower().Contains(BannedUserName.ToLower()))) { newDisplayName = account.Name; } #endif IUserProfileInfo info = m_profileConnector.GetUserProfile(m_service.AgentID); if (info == null) { //m_avatar.ControllingClient.SendAlertMessage ("You cannot update your display name currently as your profile cannot be found."); } else { //Set the name info.DisplayName = newDisplayName; m_profileConnector.UpdateUserProfile(info); //One for us DisplayNameUpdate(newDisplayName, oldDisplayName, account, m_service.AgentID); #if (!ISWIN) foreach (IRegionClientCapsService avatar in m_service.RegionCaps.GetClients()) { if (avatar.AgentID != m_service.AgentID) { //Update all others DisplayNameUpdate(newDisplayName, oldDisplayName, account, avatar.AgentID); } } #else foreach (IRegionClientCapsService avatar in m_service.RegionCaps.GetClients().Where(avatar => avatar.AgentID != m_service.AgentID)) { //Update all others DisplayNameUpdate(newDisplayName, oldDisplayName, account, avatar.AgentID); } #endif //The reply SetDisplayNameReply(newDisplayName, oldDisplayName, account); } } catch { } //Send back data Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 200; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = ""; return responsedata; } /// <summary> /// Get the user's display name, currently not used? /// </summary> /// <param name = "mDhttpMethod"></param> /// <param name = "agentID"></param> /// <returns></returns> private byte[] ProcessGetDisplayName(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { //I've never seen this come in, so for now... do nothing NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); string[] ids = query.GetValues("ids"); string username = query.GetOne("username"); OSDMap map = new OSDMap(); OSDArray agents = new OSDArray(); OSDArray bad_ids = new OSDArray(); OSDArray bad_usernames = new OSDArray(); if (ids != null) { foreach (string id in ids) { UserAccount account = m_userService.GetUserAccount(UUID.Zero, UUID.Parse(id)); if (account != null) { IUserProfileInfo info = DataManager.RequestPlugin<IProfileConnector>().GetUserProfile(account.PrincipalID); if (info != null) PackUserInfo(info, account, ref agents); else PackUserInfo(info, account, ref agents); //else //Technically is right, but needs to be packed no matter what for OS based grids // bad_ids.Add (id); } } } else if (username != null) { UserAccount account = m_userService.GetUserAccount(UUID.Zero, username.Replace('.', ' ')); if (account != null) { IUserProfileInfo info = DataManager.RequestPlugin<IProfileConnector>().GetUserProfile(account.PrincipalID); if (info != null) PackUserInfo(info, account, ref agents); else bad_usernames.Add(username); } } map["agents"] = agents; map["bad_ids"] = bad_ids; map["bad_usernames"] = bad_usernames; byte[] m = OSDParser.SerializeLLSDXmlBytes(map); httpResponse.Body.Write(m, 0, m.Length); httpResponse.StatusCode = (int) HttpStatusCode.OK; httpResponse.Send(); return null; } private void PackUserInfo(IUserProfileInfo info, UserAccount account, ref OSDArray agents) { OSDMap agentMap = new OSDMap(); agentMap["username"] = account.Name; agentMap["display_name"] = (info == null || info.DisplayName == "") ? account.Name : info.DisplayName; agentMap["display_name_next_update"] = OSD.FromDate( DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime()); agentMap["legacy_first_name"] = account.FirstName; agentMap["legacy_last_name"] = account.LastName; agentMap["id"] = account.PrincipalID; agentMap["is_display_name_default"] = isDefaultDisplayName(account.FirstName, account.LastName, account.Name, info == null ? account.Name : info.DisplayName); agents.Add(agentMap); } #region Event Queue /// <summary> /// Send the user a display name update /// </summary> /// <param name = "newDisplayName"></param> /// <param name = "oldDisplayName"></param> /// <param name = "InfoFromAv"></param> /// <param name = "ToAgentID"></param> public void DisplayNameUpdate(string newDisplayName, string oldDisplayName, UserAccount InfoFromAv, UUID ToAgentID) { if (m_eventQueue != null) { //If the DisplayName is blank, the client refuses to do anything, so we send the name by default if (newDisplayName == "") newDisplayName = InfoFromAv.Name; bool isDefaultName = isDefaultDisplayName(InfoFromAv.FirstName, InfoFromAv.LastName, InfoFromAv.Name, newDisplayName); OSD item = DisplayNameUpdate(newDisplayName, oldDisplayName, InfoFromAv.PrincipalID, isDefaultName, InfoFromAv.FirstName, InfoFromAv.LastName, InfoFromAv.FirstName + "." + InfoFromAv.LastName); m_eventQueue.Enqueue(item, ToAgentID, m_service.RegionHandle); } } private bool isDefaultDisplayName(string first, string last, string name, string displayName) { if (displayName == name) return true; else if (displayName == first + "." + last) return true; return false; } /// <summary> /// Reply to the set display name reply /// </summary> /// <param name = "newDisplayName"></param> /// <param name = "oldDisplayName"></param> /// <param name = "m_avatar"></param> public void SetDisplayNameReply(string newDisplayName, string oldDisplayName, UserAccount m_avatar) { if (m_eventQueue != null) { bool isDefaultName = isDefaultDisplayName(m_avatar.FirstName, m_avatar.LastName, m_avatar.Name, newDisplayName); OSD item = DisplayNameReply(newDisplayName, oldDisplayName, m_avatar.PrincipalID, isDefaultName, m_avatar.FirstName, m_avatar.LastName, m_avatar.FirstName + "." + m_avatar.LastName); m_eventQueue.Enqueue(item, m_avatar.PrincipalID, m_service.RegionHandle); } } /// <summary> /// Tell the user about an update /// </summary> /// <param name = "newDisplayName"></param> /// <param name = "oldDisplayName"></param> /// <param name = "ID"></param> /// <param name = "isDefault"></param> /// <param name = "First"></param> /// <param name = "Last"></param> /// <param name = "Account"></param> /// <returns></returns> public OSD DisplayNameUpdate(string newDisplayName, string oldDisplayName, UUID ID, bool isDefault, string First, string Last, string Account) { OSDMap nameReply = new OSDMap {{"message", OSD.FromString("DisplayNameUpdate")}}; OSDMap body = new OSDMap(); OSDMap agentData = new OSDMap { {"display_name", OSD.FromString(newDisplayName)}, { "display_name_next_update", OSD.FromDate( DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime()) }, {"id", OSD.FromUUID(ID)}, {"is_display_name_default", OSD.FromBoolean(isDefault)}, {"legacy_first_name", OSD.FromString(First)}, {"legacy_last_name", OSD.FromString(Last)}, {"username", OSD.FromString(Account)} }; body.Add("agent", agentData); body.Add("agent_id", OSD.FromUUID(ID)); body.Add("old_display_name", OSD.FromString(oldDisplayName)); nameReply.Add("body", body); return nameReply; } /// <summary> /// Send back a user's display name /// </summary> /// <param name = "newDisplayName"></param> /// <param name = "oldDisplayName"></param> /// <param name = "ID"></param> /// <param name = "isDefault"></param> /// <param name = "First"></param> /// <param name = "Last"></param> /// <param name = "Account"></param> /// <returns></returns> public OSD DisplayNameReply(string newDisplayName, string oldDisplayName, UUID ID, bool isDefault, string First, string Last, string Account) { OSDMap nameReply = new OSDMap(); OSDMap body = new OSDMap(); OSDMap content = new OSDMap(); OSDMap agentData = new OSDMap(); content.Add("display_name", OSD.FromString(newDisplayName)); content.Add("display_name_next_update", OSD.FromDate( DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime())); content.Add("id", OSD.FromUUID(ID)); content.Add("is_display_name_default", OSD.FromBoolean(isDefault)); content.Add("legacy_first_name", OSD.FromString(First)); content.Add("legacy_last_name", OSD.FromString(Last)); content.Add("username", OSD.FromString(Account)); body.Add("content", content); body.Add("agent", agentData); body.Add("reason", OSD.FromString("OK")); body.Add("status", OSD.FromInteger(200)); nameReply.Add("body", body); nameReply.Add("message", OSD.FromString("SetDisplayNameReply")); return nameReply; } #endregion #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding; public class ProceduralWorld : MonoBehaviour { public Transform target; public ProceduralPrefab[] prefabs; /** How far away to generate tiles */ public int range = 1; /** World size of tiles */ public float tileSize = 100; public int subTiles = 20; /** Enable static batching on generated tiles. * Will improve overall FPS, but might cause FPS on * some frames when static batching is done */ public bool staticBatching = false; Queue<IEnumerator> tileGenerationQueue = new Queue<IEnumerator>(); [System.Serializable] public class ProceduralPrefab { /** Prefab to use */ public GameObject prefab; /** Number of objects per square world unit */ public float density = 0; /** Multiply by [perlin noise]. * Value from 0 to 1 indicating weight. */ public float perlin = 0; /** Perlin will be raised to this power. * A higher value gives more distinct edges */ public float perlinPower = 1; /** Some offset to avoid identical density maps */ public Vector2 perlinOffset = Vector2.zero; /** Perlin noise scale. * A higher value spreads out the maximums and minimums of the density. */ public float perlinScale = 1; /** Multiply by [random]. * Value from 0 to 1 indicating weight. */ public float random = 1; /** If checked, a single object will be created in the center of each tile */ public bool singleFixed = false; } /** All tiles */ Dictionary<Int2, ProceduralTile> tiles = new Dictionary<Int2, ProceduralTile>(); // Use this for initialization void Start () { // Calculate the closest tiles // and then recalculate the graph Update (); AstarPath.active.Scan (); StartCoroutine (GenerateTiles ()); } // Update is called once per frame void Update () { // Calculate the tile the target is standing on Int2 p = new Int2 ( Mathf.RoundToInt ((target.position.x - tileSize*0.5f) / tileSize), Mathf.RoundToInt ((target.position.z - tileSize*0.5f) / tileSize) ); // Clamp range range = range < 1 ? 1 : range; // Remove tiles which are out of range bool changed = true; while ( changed ) { changed = false; foreach (KeyValuePair<Int2,ProceduralTile> pair in tiles ) { if ( Mathf.Abs (pair.Key.x-p.x) > range || Mathf.Abs (pair.Key.y-p.y) > range ) { pair.Value.Destroy (); tiles.Remove ( pair.Key ); changed = true; break; } } } // Add tiles which have come in range // and start calculating them for ( int x = p.x-range; x <= p.x+range; x++ ) { for ( int z = p.y-range; z <= p.y+range; z++ ) { if ( !tiles.ContainsKey ( new Int2(x,z) ) ) { ProceduralTile tile = new ProceduralTile ( this, x, z ); var generator = tile.Generate (); // Tick it one step forward generator.MoveNext (); // Calculate the rest later tileGenerationQueue.Enqueue (generator); tiles.Add ( new Int2(x,z), tile ); } } } // The ones directly adjacent to the current one // should always be completely calculated // make sure they are for ( int x = p.x-1; x <= p.x+1; x++ ) { for ( int z = p.y-1; z <= p.y+1; z++ ) { tiles[new Int2(x,z)].ForceFinish(); } } } IEnumerator GenerateTiles () { while (true) { if (tileGenerationQueue.Count > 0) { var generator = tileGenerationQueue.Dequeue (); yield return StartCoroutine (generator); } yield return null; } } class ProceduralTile { int x, z; System.Random rnd; bool staticBatching; ProceduralWorld world; public bool destroyed { get; private set; } public ProceduralTile ( ProceduralWorld world, int x, int z) { this.x = x; this.z = z; this.world = world; rnd = new System.Random ( (x * 10007) ^ (z*36007)); } Transform root; IEnumerator ie; public IEnumerator Generate () { ie = InternalGenerate (); GameObject rt = new GameObject ("Tile " + x + " " + z ); root = rt.transform; while ( ie != null && root != null && ie.MoveNext ()) yield return ie.Current; ie = null; } public void ForceFinish () { while ( ie != null && root != null && ie.MoveNext ()) {} ie = null; } Vector3 RandomInside () { Vector3 v = new Vector3(); v.x = (x + (float)rnd.NextDouble())*world.tileSize; v.z = (z + (float)rnd.NextDouble())*world.tileSize; return v; } Vector3 RandomInside ( float px, float pz) { Vector3 v = new Vector3(); v.x = (px + (float)rnd.NextDouble()/world.subTiles)*world.tileSize; v.z = (pz + (float)rnd.NextDouble()/world.subTiles)*world.tileSize; return v; } Quaternion RandomYRot () { return Quaternion.Euler ( 360*(float)rnd.NextDouble(),0, 360*(float)rnd.NextDouble()); } IEnumerator InternalGenerate () { Debug.Log ( "Generating tile " + x + ", " + z ); int counter = 0; float[,] ditherMap = new float[world.subTiles+2,world.subTiles+2]; //List<GameObject> objs = new List<GameObject>(); for ( int i=0;i<world.prefabs.Length;i++ ) { ProceduralPrefab pref = world.prefabs[i]; if ( pref.singleFixed ) { Vector3 p = new Vector3 ( (x+0.5f) * world.tileSize, 0, (z+0.5f) * world.tileSize ); GameObject ob = GameObject.Instantiate ( pref.prefab, p, Quaternion.identity ) as GameObject; ob.transform.parent = root; } else { float subSize = world.tileSize/world.subTiles; for ( int sx=0; sx < world.subTiles; sx++ ) { for ( int sz=0; sz < world.subTiles; sz++ ) { ditherMap[sx+1,sz+1] = 0; } } for ( int sx=0; sx < world.subTiles; sx++ ) { for ( int sz=0; sz < world.subTiles; sz++ ) { float px = x + sx/(float)world.subTiles;//sx / world.tileSize; float pz = z + sz/(float)world.subTiles;//sz / world.tileSize; float perl = Mathf.Pow (Mathf.PerlinNoise ( (px + pref.perlinOffset.x)*pref.perlinScale, (pz + pref.perlinOffset.y)*pref.perlinScale ), pref.perlinPower ); float density = pref.density * Mathf.Lerp ( 1, perl, pref.perlin) * Mathf.Lerp ( 1, (float)rnd.NextDouble (), pref.random ); float fcount = subSize*subSize*density + ditherMap[sx+1,sz+1]; int count = Mathf.RoundToInt(fcount); // Apply dithering // See http://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering ditherMap[sx+1+1,sz+1+0] += (7f/16f) * (fcount - count); ditherMap[sx+1-1,sz+1+1] += (3f/16f) * (fcount - count); ditherMap[sx+1+0,sz+1+1] += (5f/16f) * (fcount - count); ditherMap[sx+1+1,sz+1+1] += (1f/16f) * (fcount - count); // Create a number of objects for ( int j=0;j<count;j++) { // Find a random position inside the current sub-tile Vector3 p = RandomInside (px, pz); GameObject ob = GameObject.Instantiate ( pref.prefab, p, RandomYRot () ) as GameObject; ob.transform.parent = root; //ob.SetActive ( false ); //objs.Add ( ob ); counter++; if ( counter % 2 == 0 ) yield return null; } } } } } ditherMap = null; yield return null; yield return null; //Batch everything for improved performance if (Application.HasProLicense () && world.staticBatching) { StaticBatchingUtility.Combine (root.gameObject); } } public void Destroy () { if (root != null) { Debug.Log ("Destroying tile " + x + ", " + z); GameObject.Destroy (root.gameObject); root = null; } // Make sure the tile generator coroutine is destroyed ie = null; } } }
using System; using System.Linq; using System.Text; using SFML.Graphics; namespace NetGore.Graphics { /// <summary> /// Interface for an object that can batch the drawing of multiple 2D sprites and text. /// Classes that implement this interface are NOT guarenteed to be thread-safe! If you wish to use /// threaded rendering, you must use a separate <see cref="ISpriteBatch"/> for each thread or manually /// add thread safety. /// </summary> public interface ISpriteBatch : IDisposable { /// <summary> /// Gets or sets the <see cref="BlendMode"/> currently being used. /// </summary> BlendMode BlendMode { get; set; } /// <summary> /// Gets a value that indicates whether the object is disposed. /// </summary> bool IsDisposed { get; } /// <summary> /// Gets if this <see cref="ISpriteBatch"/> is currently inbetween calls to Begin() and End(). /// </summary> bool IsStarted { get; } /// <summary> /// Gets or sets the name of this sprite batch. /// </summary> string Name { set; get; } /// <summary> /// Gets or sets the <see cref="RenderTarget"/> that this <see cref="SpriteBatch"/> is drawing to. /// </summary> RenderTarget RenderTarget { get; set; } /// <summary> /// Gets or sets an object that uniquely identifies this sprite batch. /// </summary> object Tag { set; get; } /// <summary> /// Prepares the graphics device for drawing sprites with specified blending, sorting, and render state options, /// and a global transform matrix. /// </summary> /// <param name="blendMode">Blending options to use when rendering.</param> /// <param name="position">The top-left corner of the view area.</param> /// <param name="size">The size of the view area.</param> /// <param name="rotation">The amount to rotation the view in degrees.</param> void Begin(BlendMode blendMode, Vector2 position, Vector2 size, float rotation); /// <summary> /// Prepares the graphics device for drawing sprites with specified blending, sorting, and render state options, /// and a global transform matrix. /// </summary> /// <param name="blendMode">Blending options to use when rendering.</param> /// <param name="camera">The <see cref="ICamera2D"/> that describes the view of the world.</param> void Begin(BlendMode blendMode, ICamera2D camera); /// <summary> /// Prepares the graphics device for drawing sprites with specified blending, sorting, and render state options, /// and a global transform matrix. /// </summary> /// <param name="blendMode">Blending options to use when rendering.</param> void Begin(BlendMode blendMode); /// <summary> /// Prepares the graphics device for drawing sprites with specified blending, sorting, and render state options, /// and a global transform matrix. /// </summary> void Begin(); /// <summary> /// Draws a raw <see cref="SFML.Graphics.Sprite"/>. Recommended to avoid using when possible, but when needed, /// can provide a slight performance boost when drawing a large number of sprites with identical state. /// </summary> /// <param name="sprite">The <see cref="SFML.Graphics.Sprite"/> to draw.</param> /// <param name="shader">The <see cref="Shader"/> to use while drawing.</param> void Draw(SFML.Graphics.Sprite sprite, Shader shader = null); /// <summary> /// Adds a sprite to the batch of sprites to be rendered, specifying the texture, destination, and source rectangles, /// color tint, rotation, origin, effects, and sort depth. /// </summary> /// <param name="texture">The sprite texture.</param> /// <param name="destinationRectangle">A rectangle specifying, in screen coordinates, where the sprite will be drawn. /// If this rectangle is not the same size as sourceRectangle, the sprite is scaled to fit.</param> /// <param name="sourceRectangle">A rectangle specifying, in texels, which section of the rectangle to draw. /// Use null to draw the entire texture.</param> /// <param name="color">The color channel modulation to use. Use <see cref="Color.White"/> for full color with /// no tinting.</param> /// <param name="rotation">The angle, in radians, to rotate the sprite around the origin.</param> /// <param name="origin">The origin of the sprite. Specify (0,0) for the upper-left corner.</param> /// <param name="effects">Rotations to apply prior to rendering.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void Draw(Texture texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects = SpriteEffects.None, Shader shader = null); /// <summary> /// Draws a raw <see cref="Drawable"/> object. /// </summary> /// <param name="drawable">The object to draw.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void Draw(Drawable drawable, Shader shader = null); /// <summary> /// Adds a sprite to the batch of sprites to be rendered, specifying the texture, destination, and source rectangles, /// color tint, rotation, origin, effects, and sort depth. /// </summary> /// <param name="texture">The sprite texture.</param> /// <param name="destinationRectangle">A rectangle specifying, in screen coordinates, where the sprite will be drawn. /// If this rectangle is not the same size as sourceRectangle, the sprite is scaled to fit.</param> /// <param name="sourceRectangle">A rectangle specifying, in texels, which section of the rectangle to draw. /// Use null to draw the entire texture.</param> /// <param name="color">The color channel modulation to use. Use <see cref="Color.White"/> for full color with /// no tinting.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void Draw(Texture texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color, Shader shader = null); /// <summary> /// Adds a sprite to the batch of sprites to be rendered, specifying the texture, destination, and source rectangles, /// color tint, rotation, origin, effects, and sort depth. /// </summary> /// <param name="texture">The sprite texture.</param> /// <param name="destinationRectangle">A rectangle specifying, in screen coordinates, where the sprite will be drawn. /// If this rectangle is not the same size as sourceRectangle, the sprite is scaled to fit.</param> /// <param name="color">The color channel modulation to use. Use <see cref="Color.White"/> for full color with /// no tinting.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void Draw(Texture texture, Rectangle destinationRectangle, Color color, Shader shader = null); /// <summary> /// Adds a sprite to the batch of sprites to be rendered, specifying the texture, destination, and source rectangles, /// color tint, rotation, origin, effects, and sort depth. /// </summary> /// <param name="texture">The sprite texture.</param> /// <param name="position">The location, in screen coordinates, where the sprite will be drawn.</param> /// <param name="sourceRectangle">A rectangle specifying, in texels, which section of the rectangle to draw. /// Use null to draw the entire texture.</param> /// <param name="color">The color channel modulation to use. Use <see cref="Color.White"/> for full color with /// no tinting.</param> /// <param name="rotation">The angle, in radians, to rotate the sprite around the origin.</param> /// <param name="origin">The origin of the sprite. Specify (0,0) for the upper-left corner.</param> /// <param name="scale">Vector containing separate scalar multiples for the x- and y-axes of the sprite.</param> /// <param name="effects">Rotations to apply prior to rendering.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void Draw(Texture texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects = SpriteEffects.None, Shader shader = null); /// <summary> /// Adds a sprite to the batch of sprites to be rendered, specifying the texture, destination, and source rectangles, /// color tint, rotation, origin, effects, and sort depth. /// </summary> /// <param name="texture">The sprite texture.</param> /// <param name="position">The location, in screen coordinates, where the sprite will be drawn.</param> /// <param name="sourceRectangle">A rectangle specifying, in texels, which section of the rectangle to draw. /// Use null to draw the entire texture.</param> /// <param name="color">The color channel modulation to use. Use <see cref="Color.White"/> for full color with /// no tinting.</param> /// <param name="rotation">The angle, in radians, to rotate the sprite around the origin.</param> /// <param name="origin">The origin of the sprite. Specify (0,0) for the upper-left corner.</param> /// <param name="scale">Uniform multiple by which to scale the sprite width and height.</param> /// <param name="effects">Rotations to apply prior to rendering.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void Draw(Texture texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects = SpriteEffects.None, Shader shader = null); /// <summary> /// Adds a sprite to the batch of sprites to be rendered, specifying the texture, destination, and source rectangles, /// color tint, rotation, origin, effects, and sort depth. /// </summary> /// <param name="texture">The sprite texture.</param> /// <param name="position">The location, in screen coordinates, where the sprite will be drawn.</param> /// <param name="sourceRectangle">A rectangle specifying, in texels, which section of the rectangle to draw. /// Use null to draw the entire texture.</param> /// <param name="color">The color channel modulation to use. Use <see cref="Color.White"/> for full color with /// no tinting.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void Draw(Texture texture, Vector2 position, Rectangle? sourceRectangle, Color color, Shader shader = null); /// <summary> /// Adds a sprite to the batch of sprites to be rendered, specifying the texture, destination, and source rectangles, /// color tint, rotation, origin, effects, and sort depth. /// </summary> /// <param name="texture">The sprite texture.</param> /// <param name="position">The location, in screen coordinates, where the sprite will be drawn.</param> /// <param name="color">The color channel modulation to use. Use <see cref="Color.White"/> for full color with /// no tinting.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void Draw(Texture texture, Vector2 position, Color color, Shader shader = null); /// <summary> /// Adds a mutable sprite string to the batch of sprites to be rendered, specifying the font, output text, /// screen position, color tint, rotation, origin, scale, effects, and depth. /// </summary> /// <param name="font">The <see cref="Font"/> to use to draw.</param> /// <param name="text">The mutable (read/write) string to draw.</param> /// <param name="position">The location, in screen coordinates, where the text will be drawn.</param> /// <param name="color">The desired color of the text.</param> /// <param name="rotation">The angle, in radians, to rotate the text around the origin.</param> /// <param name="origin">The origin of the string. Specify (0,0) for the upper-left corner.</param> /// <param name="scale">Vector containing separate scalar multiples for the x- and y-axes of the sprite.</param> /// <param name="style">How to style the drawn string.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void DrawString(Font font, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, Text.Styles style = Text.Styles.Regular, Shader shader = null); /// <summary> /// Adds a mutable sprite string to the batch of sprites to be rendered, specifying the font, output text, /// screen position, color tint, rotation, origin, scale, effects, and depth. /// </summary> /// <param name="font">The <see cref="Font"/> to use to draw.</param> /// <param name="text">The string to draw.</param> /// <param name="position">The location, in screen coordinates, where the text will be drawn.</param> /// <param name="color">The desired color of the text.</param> /// <param name="rotation">The angle, in radians, to rotate the text around the origin.</param> /// <param name="origin">The origin of the string. Specify (0,0) for the upper-left corner.</param> /// <param name="scale">Vector containing separate scalar multiples for the x- and y-axes of the sprite.</param> /// <param name="style">How to style the drawn string.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void DrawString(Font font, string text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, Text.Styles style = Text.Styles.Regular, Shader shader = null); /// <summary> /// Adds a mutable sprite string to the batch of sprites to be rendered, specifying the font, output text, /// screen position, color tint, rotation, origin, scale, effects, and depth. /// </summary> /// <param name="font">The <see cref="Font"/> to use to draw.</param> /// <param name="text">The mutable (read/write) string to draw.</param> /// <param name="position">The location, in screen coordinates, where the text will be drawn.</param> /// <param name="color">The desired color of the text.</param> /// <param name="rotation">The angle, in radians, to rotate the text around the origin.</param> /// <param name="origin">The origin of the string. Specify (0,0) for the upper-left corner.</param> /// <param name="scale">Vector containing separate scalar multiples for the x- and y-axes of the sprite.</param> /// <param name="style">How to style the drawn string.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void DrawString(Font font, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, float scale = 1.0f, Text.Styles style = Text.Styles.Regular, Shader shader = null); /// <summary> /// Adds a mutable sprite string to the batch of sprites to be rendered, specifying the font, output text, /// screen position, color tint, rotation, origin, scale, effects, and depth. /// </summary> /// <param name="font">The <see cref="Font"/> to use to draw.</param> /// <param name="text">The string to draw.</param> /// <param name="position">The location, in screen coordinates, where the text will be drawn.</param> /// <param name="color">The desired color of the text.</param> /// <param name="rotation">The angle, in radians, to rotate the text around the origin.</param> /// <param name="origin">The origin of the string. Specify (0,0) for the upper-left corner.</param> /// <param name="scale">Vector containing separate scalar multiples for the x- and y-axes of the sprite.</param> /// <param name="style">How to style the drawn string.</param> /// <param name="shader">The shader to use on the text being drawn.</param> void DrawString(Font font, string text, Vector2 position, Color color, float rotation, Vector2 origin, float scale, Text.Styles style = Text.Styles.Regular, Shader shader = null); /// <summary> /// Adds a mutable sprite string to the batch of sprites to be rendered, specifying the font, output text, /// screen position, color tint, rotation, origin, scale, effects, and depth. /// </summary> /// <param name="font">The <see cref="Font"/> to use to draw.</param> /// <param name="text">The mutable (read/write) string to draw.</param> /// <param name="position">The location, in screen coordinates, where the text will be drawn.</param> /// <param name="color">The desired color of the text.</param> void DrawString(Font font, StringBuilder text, Vector2 position, Color color); /// <summary> /// Adds a mutable sprite string to the batch of sprites to be rendered, specifying the font, output text, /// screen position, color tint, rotation, origin, scale, effects, and depth. /// </summary> /// <param name="font">The <see cref="Font"/> to use to draw.</param> /// <param name="text">The string to draw.</param> /// <param name="position">The location, in screen coordinates, where the text will be drawn.</param> /// <param name="color">The desired color of the text.</param> void DrawString(Font font, string text, Vector2 position, Color color); /// <summary> /// Flushes the sprite batch and restores the device state to how it was before Begin was called. /// </summary> void End(); } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface IEmployeePayHistoryOriginalData : ISchemaBaseOriginalData { System.DateTime RateChangeDate { get; } string Rate { get; } string PayFrequency { get; } } public partial class EmployeePayHistory : OGM<EmployeePayHistory, EmployeePayHistory.EmployeePayHistoryData, System.String>, ISchemaBase, INeo4jBase, IEmployeePayHistoryOriginalData { #region Initialize static EmployeePayHistory() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion AdditionalGeneratedStoredQueries(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, EmployeePayHistory> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.EmployeePayHistoryAlias, IWhereQuery> query) { q.EmployeePayHistoryAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.EmployeePayHistory.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"EmployeePayHistory => RateChangeDate : {this.RateChangeDate}, Rate : {this.Rate}, PayFrequency : {this.PayFrequency}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new EmployeePayHistoryData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 if (InnerData.RateChangeDate == null) throw new PersistenceException(string.Format("Cannot save EmployeePayHistory with key '{0}' because the RateChangeDate cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.Rate == null) throw new PersistenceException(string.Format("Cannot save EmployeePayHistory with key '{0}' because the Rate cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.PayFrequency == null) throw new PersistenceException(string.Format("Cannot save EmployeePayHistory with key '{0}' because the PayFrequency cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.ModifiedDate == null) throw new PersistenceException(string.Format("Cannot save EmployeePayHistory with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>")); #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class EmployeePayHistoryData : Data<System.String> { public EmployeePayHistoryData() { } public EmployeePayHistoryData(EmployeePayHistoryData data) { RateChangeDate = data.RateChangeDate; Rate = data.Rate; PayFrequency = data.PayFrequency; ModifiedDate = data.ModifiedDate; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "EmployeePayHistory"; } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("RateChangeDate", Conversion<System.DateTime, long>.Convert(RateChangeDate)); dictionary.Add("Rate", Rate); dictionary.Add("PayFrequency", PayFrequency); dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate)); dictionary.Add("Uid", Uid); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("RateChangeDate", out value)) RateChangeDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("Rate", out value)) Rate = (string)value; if (properties.TryGetValue("PayFrequency", out value)) PayFrequency = (string)value; if (properties.TryGetValue("ModifiedDate", out value)) ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("Uid", out value)) Uid = (string)value; } #endregion #region Members for interface IEmployeePayHistory public System.DateTime RateChangeDate { get; set; } public string Rate { get; set; } public string PayFrequency { get; set; } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get; set; } #endregion #region Members for interface INeo4jBase public string Uid { get; set; } #endregion } #endregion #region Outer Data #region Members for interface IEmployeePayHistory public System.DateTime RateChangeDate { get { LazyGet(); return InnerData.RateChangeDate; } set { if (LazySet(Members.RateChangeDate, InnerData.RateChangeDate, value)) InnerData.RateChangeDate = value; } } public string Rate { get { LazyGet(); return InnerData.Rate; } set { if (LazySet(Members.Rate, InnerData.Rate, value)) InnerData.Rate = value; } } public string PayFrequency { get { LazyGet(); return InnerData.PayFrequency; } set { if (LazySet(Members.PayFrequency, InnerData.PayFrequency, value)) InnerData.PayFrequency = value; } } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } } #endregion #region Members for interface INeo4jBase public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static EmployeePayHistoryMembers members = null; public static EmployeePayHistoryMembers Members { get { if (members == null) { lock (typeof(EmployeePayHistory)) { if (members == null) members = new EmployeePayHistoryMembers(); } } return members; } } public class EmployeePayHistoryMembers { internal EmployeePayHistoryMembers() { } #region Members for interface IEmployeePayHistory public Property RateChangeDate { get; } = Datastore.AdventureWorks.Model.Entities["EmployeePayHistory"].Properties["RateChangeDate"]; public Property Rate { get; } = Datastore.AdventureWorks.Model.Entities["EmployeePayHistory"].Properties["Rate"]; public Property PayFrequency { get; } = Datastore.AdventureWorks.Model.Entities["EmployeePayHistory"].Properties["PayFrequency"]; #endregion #region Members for interface ISchemaBase public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]; #endregion #region Members for interface INeo4jBase public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]; #endregion } private static EmployeePayHistoryFullTextMembers fullTextMembers = null; public static EmployeePayHistoryFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(EmployeePayHistory)) { if (fullTextMembers == null) fullTextMembers = new EmployeePayHistoryFullTextMembers(); } } return fullTextMembers; } } public class EmployeePayHistoryFullTextMembers { internal EmployeePayHistoryFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(EmployeePayHistory)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["EmployeePayHistory"]; } } return entity; } private static EmployeePayHistoryEvents events = null; public static EmployeePayHistoryEvents Events { get { if (events == null) { lock (typeof(EmployeePayHistory)) { if (events == null) events = new EmployeePayHistoryEvents(); } } return events; } } public class EmployeePayHistoryEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<EmployeePayHistory, EntityEventArgs> onNew; public event EventHandler<EmployeePayHistory, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<EmployeePayHistory, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((EmployeePayHistory)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<EmployeePayHistory, EntityEventArgs> onDelete; public event EventHandler<EmployeePayHistory, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<EmployeePayHistory, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((EmployeePayHistory)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<EmployeePayHistory, EntityEventArgs> onSave; public event EventHandler<EmployeePayHistory, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<EmployeePayHistory, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((EmployeePayHistory)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnRateChangeDate private static bool onRateChangeDateIsRegistered = false; private static EventHandler<EmployeePayHistory, PropertyEventArgs> onRateChangeDate; public static event EventHandler<EmployeePayHistory, PropertyEventArgs> OnRateChangeDate { add { lock (typeof(OnPropertyChange)) { if (!onRateChangeDateIsRegistered) { Members.RateChangeDate.Events.OnChange -= onRateChangeDateProxy; Members.RateChangeDate.Events.OnChange += onRateChangeDateProxy; onRateChangeDateIsRegistered = true; } onRateChangeDate += value; } } remove { lock (typeof(OnPropertyChange)) { onRateChangeDate -= value; if (onRateChangeDate == null && onRateChangeDateIsRegistered) { Members.RateChangeDate.Events.OnChange -= onRateChangeDateProxy; onRateChangeDateIsRegistered = false; } } } } private static void onRateChangeDateProxy(object sender, PropertyEventArgs args) { EventHandler<EmployeePayHistory, PropertyEventArgs> handler = onRateChangeDate; if ((object)handler != null) handler.Invoke((EmployeePayHistory)sender, args); } #endregion #region OnRate private static bool onRateIsRegistered = false; private static EventHandler<EmployeePayHistory, PropertyEventArgs> onRate; public static event EventHandler<EmployeePayHistory, PropertyEventArgs> OnRate { add { lock (typeof(OnPropertyChange)) { if (!onRateIsRegistered) { Members.Rate.Events.OnChange -= onRateProxy; Members.Rate.Events.OnChange += onRateProxy; onRateIsRegistered = true; } onRate += value; } } remove { lock (typeof(OnPropertyChange)) { onRate -= value; if (onRate == null && onRateIsRegistered) { Members.Rate.Events.OnChange -= onRateProxy; onRateIsRegistered = false; } } } } private static void onRateProxy(object sender, PropertyEventArgs args) { EventHandler<EmployeePayHistory, PropertyEventArgs> handler = onRate; if ((object)handler != null) handler.Invoke((EmployeePayHistory)sender, args); } #endregion #region OnPayFrequency private static bool onPayFrequencyIsRegistered = false; private static EventHandler<EmployeePayHistory, PropertyEventArgs> onPayFrequency; public static event EventHandler<EmployeePayHistory, PropertyEventArgs> OnPayFrequency { add { lock (typeof(OnPropertyChange)) { if (!onPayFrequencyIsRegistered) { Members.PayFrequency.Events.OnChange -= onPayFrequencyProxy; Members.PayFrequency.Events.OnChange += onPayFrequencyProxy; onPayFrequencyIsRegistered = true; } onPayFrequency += value; } } remove { lock (typeof(OnPropertyChange)) { onPayFrequency -= value; if (onPayFrequency == null && onPayFrequencyIsRegistered) { Members.PayFrequency.Events.OnChange -= onPayFrequencyProxy; onPayFrequencyIsRegistered = false; } } } } private static void onPayFrequencyProxy(object sender, PropertyEventArgs args) { EventHandler<EmployeePayHistory, PropertyEventArgs> handler = onPayFrequency; if ((object)handler != null) handler.Invoke((EmployeePayHistory)sender, args); } #endregion #region OnModifiedDate private static bool onModifiedDateIsRegistered = false; private static EventHandler<EmployeePayHistory, PropertyEventArgs> onModifiedDate; public static event EventHandler<EmployeePayHistory, PropertyEventArgs> OnModifiedDate { add { lock (typeof(OnPropertyChange)) { if (!onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; Members.ModifiedDate.Events.OnChange += onModifiedDateProxy; onModifiedDateIsRegistered = true; } onModifiedDate += value; } } remove { lock (typeof(OnPropertyChange)) { onModifiedDate -= value; if (onModifiedDate == null && onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; onModifiedDateIsRegistered = false; } } } } private static void onModifiedDateProxy(object sender, PropertyEventArgs args) { EventHandler<EmployeePayHistory, PropertyEventArgs> handler = onModifiedDate; if ((object)handler != null) handler.Invoke((EmployeePayHistory)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<EmployeePayHistory, PropertyEventArgs> onUid; public static event EventHandler<EmployeePayHistory, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<EmployeePayHistory, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((EmployeePayHistory)sender, args); } #endregion } #endregion } #endregion #region IEmployeePayHistoryOriginalData public IEmployeePayHistoryOriginalData OriginalVersion { get { return this; } } #region Members for interface IEmployeePayHistory System.DateTime IEmployeePayHistoryOriginalData.RateChangeDate { get { return OriginalData.RateChangeDate; } } string IEmployeePayHistoryOriginalData.Rate { get { return OriginalData.Rate; } } string IEmployeePayHistoryOriginalData.PayFrequency { get { return OriginalData.PayFrequency; } } #endregion #region Members for interface ISchemaBase ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } } System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } } #endregion #region Members for interface INeo4jBase INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } } string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } } #endregion #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Xunit; namespace System.Numerics.Matrices.Tests { /// <summary> /// Tests for the Matrix4x1 structure. /// </summary> public class Test4x1 { const int Epsilon = 10; [Fact] public void ConstructorValuesAreAccessibleByIndexer() { Matrix4x1 matrix4x1; matrix4x1 = new Matrix4x1(); for (int x = 0; x < matrix4x1.Columns; x++) { for (int y = 0; y < matrix4x1.Rows; y++) { Assert.Equal(0, matrix4x1[x, y], Epsilon); } } double value = 33.33; matrix4x1 = new Matrix4x1(value); for (int x = 0; x < matrix4x1.Columns; x++) { for (int y = 0; y < matrix4x1.Rows; y++) { Assert.Equal(value, matrix4x1[x, y], Epsilon); } } GenerateFilledMatrixWithValues(out matrix4x1); for (int y = 0; y < matrix4x1.Rows; y++) { for (int x = 0; x < matrix4x1.Columns; x++) { Assert.Equal(y * matrix4x1.Columns + x, matrix4x1[x, y], Epsilon); } } } [Fact] public void IndexerGetAndSetValuesCorrectly() { Matrix4x1 matrix4x1 = new Matrix4x1(); for (int x = 0; x < matrix4x1.Columns; x++) { for (int y = 0; y < matrix4x1.Rows; y++) { matrix4x1[x, y] = y * matrix4x1.Columns + x; } } for (int y = 0; y < matrix4x1.Rows; y++) { for (int x = 0; x < matrix4x1.Columns; x++) { Assert.Equal(y * matrix4x1.Columns + x, matrix4x1[x, y], Epsilon); } } } [Fact] public void ConstantValuesAreCorrect() { Matrix4x1 matrix4x1 = new Matrix4x1(); Assert.Equal(4, matrix4x1.Columns); Assert.Equal(1, matrix4x1.Rows); Assert.Equal(Matrix4x1.ColumnCount, matrix4x1.Columns); Assert.Equal(Matrix4x1.RowCount, matrix4x1.Rows); } [Fact] public void ScalarMultiplicationIsCorrect() { Matrix4x1 matrix4x1; GenerateFilledMatrixWithValues(out matrix4x1); for (double c = -10; c <= 10; c += 0.5) { Matrix4x1 result = matrix4x1 * c; for (int y = 0; y < matrix4x1.Rows; y++) { for (int x = 0; x < matrix4x1.Columns; x++) { Assert.Equal(matrix4x1[x, y] * c, result[x, y], Epsilon); } } } } [Fact] public void MemberGetAndSetValuesCorrectly() { Matrix4x1 matrix4x1 = new Matrix4x1(); matrix4x1.M11 = 0; matrix4x1.M21 = 1; matrix4x1.M31 = 2; matrix4x1.M41 = 3; Assert.Equal(0, matrix4x1.M11, Epsilon); Assert.Equal(1, matrix4x1.M21, Epsilon); Assert.Equal(2, matrix4x1.M31, Epsilon); Assert.Equal(3, matrix4x1.M41, Epsilon); Assert.Equal(matrix4x1[0, 0], matrix4x1.M11, Epsilon); Assert.Equal(matrix4x1[1, 0], matrix4x1.M21, Epsilon); Assert.Equal(matrix4x1[2, 0], matrix4x1.M31, Epsilon); Assert.Equal(matrix4x1[3, 0], matrix4x1.M41, Epsilon); } [Fact] public void HashCodeGenerationWorksCorrectly() { HashSet<int> hashCodes = new HashSet<int>(); Matrix4x1 value = new Matrix4x1(1); for (int i = 2; i <= 100; i++) { Assert.True(hashCodes.Add(value.GetHashCode()), "Unique hash code generation failure."); value *= i; } } [Fact] public void SimpleAdditionGeneratesCorrectValues() { Matrix4x1 value1 = new Matrix4x1(1); Matrix4x1 value2 = new Matrix4x1(99); Matrix4x1 result = value1 + value2; for (int y = 0; y < Matrix4x1.RowCount; y++) { for (int x = 0; x < Matrix4x1.ColumnCount; x++) { Assert.Equal(1 + 99, result[x, y], Epsilon); } } } [Fact] public void SimpleSubtractionGeneratesCorrectValues() { Matrix4x1 value1 = new Matrix4x1(100); Matrix4x1 value2 = new Matrix4x1(1); Matrix4x1 result = value1 - value2; for (int y = 0; y < Matrix4x1.RowCount; y++) { for (int x = 0; x < Matrix4x1.ColumnCount; x++) { Assert.Equal(100 - 1, result[x, y], Epsilon); } } } [Fact] public void EqualityOperatorWorksCorrectly() { Matrix4x1 value1 = new Matrix4x1(100); Matrix4x1 value2 = new Matrix4x1(50) * 2; Assert.Equal(value1, value2); Assert.True(value1 == value2, "Equality operator failed."); } [Fact] public void AccessorThrowsWhenOutOfBounds() { Matrix4x1 matrix4x1 = new Matrix4x1(); Assert.Throws<ArgumentOutOfRangeException>(() => { matrix4x1[-1, 0] = 0; }); Assert.Throws<ArgumentOutOfRangeException>(() => { matrix4x1[0, -1] = 0; }); Assert.Throws<ArgumentOutOfRangeException>(() => { matrix4x1[4, 0] = 0; }); Assert.Throws<ArgumentOutOfRangeException>(() => { matrix4x1[0, 1] = 0; }); } [Fact] public void MuliplyByMatrix2x4ProducesMatrix2x1() { Matrix4x1 matrix1 = new Matrix4x1(3); Matrix2x4 matrix2 = new Matrix2x4(2); Matrix2x1 result = matrix1 * matrix2; Matrix2x1 expected = new Matrix2x1(24, 24); Assert.Equal(expected, result); } [Fact] public void MuliplyByMatrix3x4ProducesMatrix3x1() { Matrix4x1 matrix1 = new Matrix4x1(3); Matrix3x4 matrix2 = new Matrix3x4(2); Matrix3x1 result = matrix1 * matrix2; Matrix3x1 expected = new Matrix3x1(24, 24, 24); Assert.Equal(expected, result); } [Fact] public void MuliplyByMatrix4x4ProducesMatrix4x1() { Matrix4x1 matrix1 = new Matrix4x1(3); Matrix4x4 matrix2 = new Matrix4x4(2); Matrix4x1 result = matrix1 * matrix2; Matrix4x1 expected = new Matrix4x1(24, 24, 24, 24); Assert.Equal(expected, result); } private void GenerateFilledMatrixWithValues(out Matrix4x1 matrix) { matrix = new Matrix4x1(0, 1, 2, 3); } } }
using OpenSim.Framework; using OpenSim.Region.CoreModules.Scripting; /* * 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 copyrightD * 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 OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { public class BSPrimLinkable : BSPrimDisplaced { // The purpose of this subclass is to add linkset functionality to the prim. This overrides // operations necessary for keeping the linkset created and, additionally, this // calls the linkset implementation for its creation and management. #pragma warning disable 414 // A linkset reports any collision on any part of the linkset. public long SomeCollisionSimulationStep = 0; private static readonly string LogHeader = "[BULLETS PRIMLINKABLE]"; #pragma warning restore 414 // This adds the overrides for link() and delink() so the prim is linkable. public BSPrimLinkable(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) : base(localID, primName, parent_scene, pos, size, rotation, pbs, pisPhysical) { // Default linkset implementation for this prim LinksetType = (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation; Linkset = BSLinkset.Factory(PhysScene, this); Linkset.Refresh(this); } public override OMV.Vector3 CenterOfMass { get { return Linkset.CenterOfMass; } } public override OMV.Vector3 GeometricCenter { get { return Linkset.GeometricCenter; } } public override bool HasSomeCollision { get { return (SomeCollisionSimulationStep == PhysScene.SimulationStep) || base.IsColliding; } set { if (value) SomeCollisionSimulationStep = PhysScene.SimulationStep; else SomeCollisionSimulationStep = 0; base.HasSomeCollision = value; } } public BSLinkset Linkset { get; set; } // The index of this child prim. public int LinksetChildIndex { get; set; } public BSLinkset.LinksetImplementation LinksetType { get; set; } // When simulator changes orientation, this might be moving a child of the linkset. public override OMV.Quaternion Orientation { get { return base.Orientation; } set { base.Orientation = value; PhysScene.TaintedObject(LocalID, "BSPrimLinkable.setOrientation", delegate() { Linkset.UpdateProperties(UpdatedProperties.Orientation, this); }); } } // When simulator changes position, this might be moving a child of the linkset. public override OMV.Vector3 Position { get { return base.Position; } set { base.Position = value; PhysScene.TaintedObject(LocalID, "BSPrimLinkable.setPosition", delegate() { Linkset.UpdateProperties(UpdatedProperties.Position, this); }); } } public override float TotalMass { get { return Linkset.LinksetMass; } } // Called after a simulation step to post a collision with this object. // This returns 'true' if the collision has been queued and the SendCollisions call must // be made at the end of the simulation step. public override bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { bool ret = false; // Ask the linkset if it wants to handle the collision if (!Linkset.HandleCollide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth)) { // The linkset didn't handle it so pass the collision through normal processing ret = base.Collide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth); } return ret; } // Convert the existing linkset of this prim into a new type. public bool ConvertLinkset(BSLinkset.LinksetImplementation newType) { bool ret = false; if (LinksetType != newType) { DetailLog("{0},BSPrimLinkable.ConvertLinkset,oldT={1},newT={2}", LocalID, LinksetType, newType); // Set the implementation type first so the call to BSLinkset.Factory gets the new type. this.LinksetType = newType; BSLinkset oldLinkset = this.Linkset; BSLinkset newLinkset = BSLinkset.Factory(PhysScene, this); this.Linkset = newLinkset; // Pick up any physical dependencies this linkset might have in the physics engine. oldLinkset.RemoveDependencies(this); // Create a list of the children (mainly because can't interate through a list that's changing) List<BSPrimLinkable> children = new List<BSPrimLinkable>(); oldLinkset.ForEachMember((child) => { if (!oldLinkset.IsRoot(child)) children.Add(child); return false; // 'false' says to continue to next member }); // Remove the children from the old linkset and add to the new (will be a new instance from the factory) foreach (BSPrimLinkable child in children) { oldLinkset.RemoveMeFromLinkset(child, true /*inTaintTime*/); } foreach (BSPrimLinkable child in children) { newLinkset.AddMeToLinkset(child); child.Linkset = newLinkset; } // Force the shape and linkset to get reconstructed newLinkset.Refresh(this); this.ForceBodyShapeRebuild(true /* inTaintTime */); } return ret; } public override void delink() { // TODO: decide if this parent checking needs to happen at taint time // Race condition here: if link() and delink() in same simulation tick, the delink will not happen BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG int childrenBefore = Linkset.NumberOfChildren; // DEBUG Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime*/); DetailLog("{0},BSPrimLinkable.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); return; } public override void Destroy() { Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime */); base.Destroy(); } public override void link(Manager.PhysicsActor obj) { BSPrimLinkable parent = obj as BSPrimLinkable; if (parent != null) { BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG int childrenBefore = Linkset.NumberOfChildren; // DEBUG Linkset = parent.Linkset.AddMeToLinkset(this); DetailLog("{0},BSPrimLinkable.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); } return; } // Refresh the linkset structure and parameters when the prim's physical parameters are changed. public override void UpdatePhysicalParameters() { base.UpdatePhysicalParameters(); // Recompute any linkset parameters. // When going from non-physical to physical, this re-enables the constraints that // had been automatically disabled when the mass was set to zero. // For compound based linksets, this enables and disables interactions of the children. if (Linkset != null) // null can happen during initialization Linkset.Refresh(this); } // Called after a simulation step for the changes in physical object properties. // Do any filtering/modification needed for linksets. public override void UpdateProperties(EntityProperties entprop) { if (Linkset.IsRoot(this) || Linkset.ShouldReportPropertyUpdates(this)) { // Properties are only updated for the roots of a linkset. // TODO: this will have to change when linksets are articulated. base.UpdateProperties(entprop); } /* else { // For debugging, report the movement of children DetailLog("{0},BSPrim.UpdateProperties,child,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, entprop.Position, entprop.Rotation, entprop.Velocity, entprop.Acceleration, entprop.RotationalVelocity); } */ // The linkset might like to know about changing locations Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this); } // When the prim is made dynamic or static, the linkset needs to change. protected override void MakeDynamic(bool makeStatic) { base.MakeDynamic(makeStatic); if (Linkset != null) // null can happen during initialization { if (makeStatic) Linkset.MakeStatic(this); else Linkset.MakeDynamic(this); } } // Body is being taken apart. Remove physical dependencies and schedule a rebuild. protected override void RemoveDependencies() { Linkset.RemoveDependencies(this); base.RemoveDependencies(); } #region Extension public override object Extension(string pFunct, params object[] pParams) { DetailLog("{0} BSPrimLinkable.Extension,op={1},nParam={2}", LocalID, pFunct, pParams.Length); object ret = null; switch (pFunct) { // physGetLinksetType(); // pParams = [ BSPhysObject root, null ] case ExtendedPhysics.PhysFunctGetLinksetType: { ret = (object)LinksetType; DetailLog("{0},BSPrimLinkable.Extension.physGetLinksetType,type={1}", LocalID, ret); break; } // physSetLinksetType(type); // pParams = [ BSPhysObject root, null, integer type ] case ExtendedPhysics.PhysFunctSetLinksetType: { if (pParams.Length > 2) { BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[2]; if (Linkset.IsRoot(this)) { PhysScene.TaintedObject(LocalID, "BSPrim.PhysFunctSetLinksetType", delegate() { // Cause the linkset type to change DetailLog("{0},BSPrimLinkable.Extension.physSetLinksetType, oldType={1},newType={2}", LocalID, Linkset.LinksetImpl, linksetType); ConvertLinkset(linksetType); }); } ret = (object)(int)linksetType; } break; } // physChangeLinkType(linknum, typeCode); // pParams = [ BSPhysObject root, BSPhysObject child, integer linkType ] case ExtendedPhysics.PhysFunctChangeLinkType: { ret = Linkset.Extension(pFunct, pParams); break; } // physGetLinkType(linknum); // pParams = [ BSPhysObject root, BSPhysObject child ] case ExtendedPhysics.PhysFunctGetLinkType: { ret = Linkset.Extension(pFunct, pParams); break; } // physChangeLinkParams(linknum, [code, value, code, value, ...]); // pParams = [ BSPhysObject root, BSPhysObject child, object[] [ string op, object opParam, string op, object opParam, ... ] ] case ExtendedPhysics.PhysFunctChangeLinkParams: { ret = Linkset.Extension(pFunct, pParams); break; } default: ret = base.Extension(pFunct, pParams); break; } return ret; } #endregion Extension } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using System; using System.Linq; namespace Google.Cloud.Spanner.Admin.Instance.V1 { /// <summary> /// Resource name for the 'project' resource. /// </summary> public sealed partial class ProjectName : IResourceName, IEquatable<ProjectName> { private static readonly PathTemplate s_template = new PathTemplate("projects/{project}"); /// <summary> /// Parses the given project resource name in string form into a new /// <see cref="ProjectName"/> instance. /// </summary> /// <param name="projectName">The project resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ProjectName"/> if successful.</returns> public static ProjectName Parse(string projectName) { GaxPreconditions.CheckNotNull(projectName, nameof(projectName)); TemplatedResourceName resourceName = s_template.ParseName(projectName); return new ProjectName(resourceName[0]); } /// <summary> /// Tries to parse the given project resource name in string form into a new /// <see cref="ProjectName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="ArgumentNullException"/> if <paramref name="projectName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="projectName">The project resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="ProjectName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns> public static bool TryParse(string projectName, out ProjectName result) { GaxPreconditions.CheckNotNull(projectName, nameof(projectName)); TemplatedResourceName resourceName; if (s_template.TryParseName(projectName, out resourceName)) { result = new ProjectName(resourceName[0]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="ProjectName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> public ProjectName(string projectId) { ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <inheritdoc /> public ResourceNameKind Kind => ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as ProjectName); /// <inheritdoc /> public bool Equals(ProjectName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(ProjectName a, ProjectName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(ProjectName a, ProjectName b) => !(a == b); } /// <summary> /// Resource name for the 'instance_config' resource. /// </summary> public sealed partial class InstanceConfigName : IResourceName, IEquatable<InstanceConfigName> { private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/instanceConfigs/{instance_config}"); /// <summary> /// Parses the given instance_config resource name in string form into a new /// <see cref="InstanceConfigName"/> instance. /// </summary> /// <param name="instanceConfigName">The instance_config resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="InstanceConfigName"/> if successful.</returns> public static InstanceConfigName Parse(string instanceConfigName) { GaxPreconditions.CheckNotNull(instanceConfigName, nameof(instanceConfigName)); TemplatedResourceName resourceName = s_template.ParseName(instanceConfigName); return new InstanceConfigName(resourceName[0], resourceName[1]); } /// <summary> /// Tries to parse the given instance_config resource name in string form into a new /// <see cref="InstanceConfigName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="ArgumentNullException"/> if <paramref name="instanceConfigName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="instanceConfigName">The instance_config resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="InstanceConfigName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceConfigName, out InstanceConfigName result) { GaxPreconditions.CheckNotNull(instanceConfigName, nameof(instanceConfigName)); TemplatedResourceName resourceName; if (s_template.TryParseName(instanceConfigName, out resourceName)) { result = new InstanceConfigName(resourceName[0], resourceName[1]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="InstanceConfigName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="instanceConfigId">The instanceConfig ID. Must not be <c>null</c>.</param> public InstanceConfigName(string projectId, string instanceConfigId) { ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); InstanceConfigId = GaxPreconditions.CheckNotNull(instanceConfigId, nameof(instanceConfigId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The instanceConfig ID. Never <c>null</c>. /// </summary> public string InstanceConfigId { get; } /// <inheritdoc /> public ResourceNameKind Kind => ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, InstanceConfigId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as InstanceConfigName); /// <inheritdoc /> public bool Equals(InstanceConfigName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(InstanceConfigName a, InstanceConfigName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(InstanceConfigName a, InstanceConfigName b) => !(a == b); } /// <summary> /// Resource name for the 'instance' resource. /// </summary> public sealed partial class InstanceName : IResourceName, IEquatable<InstanceName> { private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/instances/{instance}"); /// <summary> /// Parses the given instance resource name in string form into a new /// <see cref="InstanceName"/> instance. /// </summary> /// <param name="instanceName">The instance resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName) { GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName)); TemplatedResourceName resourceName = s_template.ParseName(instanceName); return new InstanceName(resourceName[0], resourceName[1]); } /// <summary> /// Tries to parse the given instance resource name in string form into a new /// <see cref="InstanceName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="ArgumentNullException"/> if <paramref name="instanceName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="instanceName">The instance resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="InstanceName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceName, out InstanceName result) { GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName)); TemplatedResourceName resourceName; if (s_template.TryParseName(instanceName, out resourceName)) { result = new InstanceName(resourceName[0], resourceName[1]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="InstanceName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="instanceId">The instance ID. Must not be <c>null</c>.</param> public InstanceName(string projectId, string instanceId) { ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); InstanceId = GaxPreconditions.CheckNotNull(instanceId, nameof(instanceId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The instance ID. Never <c>null</c>. /// </summary> public string InstanceId { get; } /// <inheritdoc /> public ResourceNameKind Kind => ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, InstanceId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as InstanceName); /// <inheritdoc /> public bool Equals(InstanceName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(InstanceName a, InstanceName b) => !(a == b); } public partial class CreateInstanceRequest { /// <summary> /// <see cref="ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ProjectName ParentAsProjectName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Spanner.Admin.Instance.V1.ProjectName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="InstanceId"/> resource name property. /// </summary> public InstanceName InstanceIdAsInstanceName { get { return string.IsNullOrEmpty(InstanceId) ? null : Google.Cloud.Spanner.Admin.Instance.V1.InstanceName.Parse(InstanceId); } set { InstanceId = value != null ? value.ToString() : ""; } } } public partial class DeleteInstanceRequest { /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public InstanceName InstanceName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.Admin.Instance.V1.InstanceName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class GetInstanceConfigRequest { /// <summary> /// <see cref="InstanceConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public InstanceConfigName InstanceConfigName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class GetInstanceRequest { /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public InstanceName InstanceName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.Admin.Instance.V1.InstanceName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class Instance { /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public InstanceName InstanceName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.Admin.Instance.V1.InstanceName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } /// <summary> /// <see cref="InstanceConfigName"/>-typed view over the <see cref="Config"/> resource name property. /// </summary> public InstanceConfigName ConfigAsInstanceConfigName { get { return string.IsNullOrEmpty(Config) ? null : Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName.Parse(Config); } set { Config = value != null ? value.ToString() : ""; } } } public partial class InstanceConfig { /// <summary> /// <see cref="InstanceConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public InstanceConfigName InstanceConfigName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.Admin.Instance.V1.InstanceConfigName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class ListInstanceConfigsRequest { /// <summary> /// <see cref="ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ProjectName ParentAsProjectName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Spanner.Admin.Instance.V1.ProjectName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class ListInstancesRequest { /// <summary> /// <see cref="ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ProjectName ParentAsProjectName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Spanner.Admin.Instance.V1.ProjectName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } }
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Messaging; using System.Runtime; using System.Security; using System.Security.Permissions; using System.ServiceModel; using System.Threading; class MsmqBindingMonitor { static readonly TimeSpan DefaultUpdateInterval = TimeSpan.FromMinutes(10); CommunicationState currentState = CommunicationState.Created; List<MsmqBindingFilter> filters = new List<MsmqBindingFilter>(); string host; int iteration; Dictionary<string, MatchState> knownPublicQueues = new Dictionary<string, MatchState>(); Dictionary<string, MatchState> knownPrivateQueues = new Dictionary<string, MatchState>(); object thisLock = new object(); IOThreadTimer timer; TimeSpan updateInterval; ManualResetEvent firstRoundComplete; bool retryMatchedFilters; public MsmqBindingMonitor(string host) : this(host, DefaultUpdateInterval, false) { } public MsmqBindingMonitor(string host, TimeSpan updateInterval, bool retryMatchedFilters) { if (string.Compare(host, "localhost", StringComparison.OrdinalIgnoreCase) == 0) { this.host = "."; } else { this.host = host; } this.firstRoundComplete = new ManualResetEvent(false); this.updateInterval = updateInterval; this.retryMatchedFilters = retryMatchedFilters; this.iteration = 1; } public void AddFilter(MsmqBindingFilter filter) { lock (this.thisLock) { this.filters.Add(filter); // Now - see if we match any known queues MatchFilter(filter, knownPublicQueues.Values); MatchFilter(filter, knownPrivateQueues.Values); } } public bool ContainsFilter(MsmqBindingFilter filter) { lock (this.thisLock) { return this.filters.Contains(filter); } } public void Open() { lock (this.thisLock) { if (this.currentState != CommunicationState.Created) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CommunicationObjectCannotBeModified, this.GetType().ToString()))); } this.currentState = CommunicationState.Opened; this.ScheduleRetryTimerIfNotSet(); } } public void Close() { lock (this.thisLock) { if (this.currentState != CommunicationState.Opened) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CommunicationObjectCannotBeModified, this.GetType().ToString()))); } this.currentState = CommunicationState.Closed; this.CancelRetryTimer(); } } public void RemoveFilter(MsmqBindingFilter filter) { lock (this.thisLock) { this.filters.Remove(filter); RematchQueues(filter, knownPublicQueues.Values); RematchQueues(filter, knownPrivateQueues.Values); } } public void WaitForFirstRoundComplete() { this.firstRoundComplete.WaitOne(); } void ScheduleRetryTimerIfNotSet() { if (this.timer == null) { this.timer = new IOThreadTimer(new Action<object>(OnTimer), null, false); // Schedule one enumeration to run immediately... this.timer.Set(0); } } void CancelRetryTimer() { if (this.timer != null) { this.timer.Cancel(); this.timer = null; } } void MatchFilter(MsmqBindingFilter filter, IEnumerable<MatchState> queues) { // Run through all the queues - see if we are better than any existing matches... foreach (MatchState state in queues) { int matchLength = filter.Match(state.QueueName); if (matchLength > state.LastMatchLength) { if (state.LastMatch != null) { state.LastMatch.MatchLost(this.host, state.QueueName, state.IsPrivate, state.CallbackState); } state.LastMatchLength = matchLength; state.LastMatch = filter; state.CallbackState = filter.MatchFound(this.host, state.QueueName, state.IsPrivate); } } } void RetryMatchFilters(IEnumerable<MatchState> queues) { // Run through all the queues and call match found on them foreach (MatchState state in queues) { if (state.LastMatch != null) { state.CallbackState = state.LastMatch.MatchFound(this.host, state.QueueName, state.IsPrivate); } } } void MatchQueue(MatchState state) { MsmqBindingFilter bestMatch = state.LastMatch; int bestMatchLength = state.LastMatchLength; // look through all the filters for the largest match: foreach (MsmqBindingFilter filter in this.filters) { int matchLength = filter.Match(state.QueueName); if (matchLength > bestMatchLength) { bestMatchLength = matchLength; bestMatch = filter; } } if (bestMatch != state.LastMatch) { if (state.LastMatch != null) { state.LastMatch.MatchLost(this.host, state.QueueName, state.IsPrivate, state.CallbackState); } state.LastMatchLength = bestMatchLength; state.LastMatch = bestMatch; state.CallbackState = bestMatch.MatchFound(this.host, state.QueueName, state.IsPrivate); } } // The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version. /* // We demand full trust because this method calls into MessageQueue, which is defined in a non-APTCA assembly. // MSMQ is not enabled in partial trust, so this demand should not break customers. [PermissionSet(SecurityAction.Demand, Unrestricted = true)] */ void OnTimer(object state) { try { if (this.currentState != CommunicationState.Opened) return; lock (this.thisLock) { if (this.retryMatchedFilters) { RetryMatchFilters(knownPublicQueues.Values); RetryMatchFilters(knownPrivateQueues.Values); } bool scanNeeded = ((this.retryMatchedFilters == false) || (this.retryMatchedFilters && (this.iteration % 2) != 0)); if (scanNeeded) { MsmqDiagnostics.ScanStarted(); // enumerate the public queues first try { MessageQueue[] queues = MessageQueue.GetPublicQueuesByMachine(this.host); ProcessFoundQueues(queues, knownPublicQueues, false); } catch (MessageQueueException ex) { MsmqDiagnostics.CannotReadQueues(this.host, true, ex); } // enumerate the private queues next try { MessageQueue[] queues = MessageQueue.GetPrivateQueuesByMachine(this.host); ProcessFoundQueues(queues, knownPrivateQueues, true); } catch (MessageQueueException ex) { MsmqDiagnostics.CannotReadQueues(this.host, false, ex); } // Figure out if we lost any queues: ProcessLostQueues(knownPublicQueues); ProcessLostQueues(knownPrivateQueues); } this.iteration++; this.timer.Set(this.updateInterval); } } finally { this.firstRoundComplete.Set(); } } // The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version. /* // We demand full trust because this method calls into MessageQueue, which is defined in a non-APTCA assembly. // MSMQ is not enabled in partial trust, so this demand should not break customers. [PermissionSet(SecurityAction.Demand, Unrestricted = true)] */ void ProcessFoundQueues(MessageQueue[] queues, Dictionary<string, MatchState> knownQueues, bool isPrivate) { foreach (MessageQueue queue in queues) { MatchState state; string name = ExtractQueueName(queue.QueueName, isPrivate); if (!knownQueues.TryGetValue(name, out state)) { state = new MatchState(name, this.iteration, isPrivate); knownQueues.Add(name, state); MatchQueue(state); } else { state.DiscoveryIteration = this.iteration; } } } string ExtractQueueName(string name, bool isPrivate) { // private queues start with "private$\\" if (isPrivate) { return name.Substring("private$\\".Length); } else { return name; } } void ProcessLostQueues(Dictionary<string, MatchState> knownQueues) { List<MatchState> lostQueues = new List<MatchState>(); foreach (MatchState state in knownQueues.Values) { if (state.DiscoveryIteration != this.iteration) { // we lost this queue! lostQueues.Add(state); } } foreach (MatchState state in lostQueues) { knownQueues.Remove(state.QueueName); if (state.LastMatch != null) { state.LastMatch.MatchLost(this.host, state.QueueName, state.IsPrivate, state.CallbackState); } } } void RematchQueues(MsmqBindingFilter filter, IEnumerable<MatchState> queues) { // if any queue currently matches "filter", re-match it against the other filters: foreach (MatchState state in queues) { if (state.LastMatch == filter) { state.LastMatch.MatchLost(this.host, state.QueueName, state.IsPrivate, state.CallbackState); state.LastMatch = null; state.LastMatchLength = -1; MatchQueue(state); } } } class MatchState { string name; int iteration; MsmqBindingFilter lastMatch; int lastMatchLength; object callbackState; bool isPrivate; public MatchState(string name, int iteration, bool isPrivate) { this.name = name; this.iteration = iteration; this.isPrivate = isPrivate; this.lastMatchLength = -1; } public object CallbackState { get { return this.callbackState; } set { this.callbackState = value; } } public int DiscoveryIteration { get { return this.iteration; } set { this.iteration = value; } } public bool IsPrivate { get { return this.isPrivate; } } public MsmqBindingFilter LastMatch { get { return this.lastMatch; } set { this.lastMatch = value; } } public int LastMatchLength { get { return this.lastMatchLength; } set { this.lastMatchLength = value; } } public string QueueName { get { return this.name; } } } } }
//----------------------------------------------------------------------------- // Torque3D - postFXManager.gui.settings.cs - Contains the code for the // application of settings to the controls, and vice versa. // // // Copyright (C) Luma Arcade 2010 // Written By Sven Bergstrom | Luma Arcade //----------------------------------------------------------------------------- $PostFXManager::defaultPreset = "core/scripts/client/postFx/default.postfxpreset.cs"; function PostFXManager::settingsSetEnabled(%this, %bEnablePostFX) { $PostFXManager::PostFX::Enabled = %bEnablePostFX; //if to enable the postFX, apply the ones that are enabled if ( %bEnablePostFX ) { //SSAO, HDR, LightRays, DOF, Sharpness, NV if ( $PostFXManager::PostFX::EnableSSAO ) SSAOPostFx.enable(); else SSAOPostFx.disable(); if ( $PostFXManager::PostFX::EnableHDR ) HDRPostFX.enable(); else HDRPostFX.disable(); if ( $PostFXManager::PostFX::EnableLightRays ) LightRayPostFX.enable(); else LightRayPostFX.disable(); if ( $PostFXManager::PostFX::EnableDOF ) DOFPostEffect.enable(); else DOFPostEffect.disable(); //if ( $PostFXManager::PostFX::EnableSharpness ) //SharpnessPostFX.enable(); //else //SharpnessPostFX.disable(); //if ( $PostFXManager::PostFX::EnableNightVision ) //NightVisionPostFX.enable(); //else //NightVisionPostFX.disable(); postVerbose("% - PostFX Manager - PostFX enabled"); } else { //Disable all postFX SSAOPostFx.disable(); HDRPostFX.disable(); LightRayPostFX.disable(); DOFPostEffect.disable(); //SharpnessPostFX.disable(); //NightVisionPostFX.disable(); postVerbose("% - PostFX Manager - PostFX disabled"); } } function PostFXManager::settingsEffectSetEnabled(%this, %sName, %bEnable) { %postEffect = 0; //Determine the postFX to enable, and apply the boolean if(%sName $= "SSAO") { %postEffect = SSAOPostFx; $PostFXManager::PostFX::EnableSSAO = %bEnable; //$pref::PostFX::SSAO::Enabled = %bEnable; } else if(%sName $= "HDR") { %postEffect = HDRPostFX; $PostFXManager::PostFX::EnableHDR = %bEnable; //$pref::PostFX::HDR::Enabled = %bEnable; } else if(%sName $= "LightRays") { %postEffect = LightRayPostFX; $PostFXManager::PostFX::EnableLightRays = %bEnable; //$pref::PostFX::LightRays::Enabled = %bEnable; } else if(%sName $= "DOF") { %postEffect = DOFPostEffect; $PostFXManager::PostFX::EnableDOF = %bEnable; //$pref::PostFX::DOF::Enabled = %bEnable; } else if(%sName $= "Sharp") { %postEffect = SharpnessPostFX; $PostFXManager::PostFX::EnableSharpness = %bEnable; //$pref::PostFX::Sharpness::Enabled = %bEnable; } else if(%sName $= "NV") { %postEffect = NightVisionPostFX; //$PostFXManager::NightVision::EnableNightVision = %bEnable; } // Apply the change if ( %bEnable == true ) { %postEffect.enable(); postVerbose("% - PostFX Manager - " @ %sName @ " enabled"); } else { %postEffect.disable(); postVerbose("% - PostFX Manager - " @ %sName @ " disabled"); } } function PostFXManager::settingsRefreshSSAO(%this) { //Apply the enabled flag ppOptionsEnableSSAO.setValue($PostFXManager::PostFX::EnableSSAO); //Add the items we need to display ppOptionsSSAOQuality.clear(); ppOptionsSSAOQuality.add("Low", 0); ppOptionsSSAOQuality.add("Medium", 1); ppOptionsSSAOQuality.add("High", 2); //Set the selected, after adding the items! ppOptionsSSAOQuality.setSelected($SSAOPostFx::quality); //SSAO - Set the values of the sliders, General Tab ppOptionsSSAOOverallStrength.setValue($SSAOPostFx::overallStrength); ppOptionsSSAOBlurDepth.setValue($SSAOPostFx::blurDepthTol); ppOptionsSSAOBlurNormal.setValue($SSAOPostFx::blurNormalTol); //SSAO - Set the values for the near tab ppOptionsSSAONearDepthMax.setValue($SSAOPostFx::sDepthMax); ppOptionsSSAONearDepthMin.setValue($SSAOPostFx::sDepthMin); ppOptionsSSAONearRadius.setValue($SSAOPostFx::sRadius); ppOptionsSSAONearStrength.setValue($SSAOPostFx::sStrength); ppOptionsSSAONearToleranceNormal.setValue($SSAOPostFx::sNormalTol); ppOptionsSSAONearTolerancePower.setValue($SSAOPostFx::sNormalPow); //SSAO - Set the values for the far tab ppOptionsSSAOFarDepthMax.setValue($SSAOPostFx::lDepthMax); ppOptionsSSAOFarDepthMin.setValue($SSAOPostFx::lDepthMin); ppOptionsSSAOFarRadius.setValue($SSAOPostFx::lRadius); ppOptionsSSAOFarStrength.setValue($SSAOPostFx::lStrength); ppOptionsSSAOFarToleranceNormal.setValue($SSAOPostFx::lNormalTol); ppOptionsSSAOFarTolerancePower.setValue($SSAOPostFx::lNormalPow); } function PostFXManager::settingsRefreshHDR(%this) { //Apply the enabled flag ppOptionsEnableHDR.setValue($PostFXManager::PostFX::EnableHDR); ppOptionsHDRBloom.setValue($HDRPostFX::enableBloom); ppOptionsHDRBloomBlurBrightPassThreshold.setValue($HDRPostFX::brightPassThreshold); ppOptionsHDRBloomBlurMean.setValue($HDRPostFX::gaussMean); ppOptionsHDRBloomBlurMultiplier.setValue($HDRPostFX::gaussMultiplier); ppOptionsHDRBloomBlurStdDev.setValue($HDRPostFX::gaussStdDev); ppOptionsHDRBrightnessAdaptRate.setValue($HDRPostFX::adaptRate); ppOptionsHDREffectsBlueShift.setValue($HDRPostFX::enableBlueShift); ppOptionsHDREffectsBlueShiftColor.BaseColor = $HDRPostFX::blueShiftColor; ppOptionsHDREffectsBlueShiftColor.PickColor = $HDRPostFX::blueShiftColor; ppOptionsHDRKeyValue.setValue($HDRPostFX::keyValue); ppOptionsHDRMinLuminance.setValue($HDRPostFX::minLuminace); ppOptionsHDRToneMapping.setValue($HDRPostFX::enableToneMapping); ppOptionsHDRToneMappingAmount.setValue($HDRPostFX::enableToneMapping); ppOptionsHDRWhiteCutoff.setValue($HDRPostFX::whiteCutoff); } function PostFXManager::settingsRefreshLightrays(%this) { //Apply the enabled flag ppOptionsEnableLightRays.setValue($PostFXManager::PostFX::EnableLightRays); ppOptionsLightRaysBrightScalar.setValue($LightRayPostFX::brightScalar); } function PostFXManager::settingsRefreshDOF(%this) { //Apply the enabled flag //ppOptionsEnableDOF.setValue($PostFXManager::PostFX::EnableDOF); ppOptionsDOFEnableDOF.setValue($PostFXManager::PostFX::EnableDOF); ppOptionsDOFEnableAutoFocus.setValue($DOFPostFx::EnableAutoFocus); ppOptionsDOFFarBlurMinSlider.setValue($DOFPostFx::BlurMin); ppOptionsDOFFarBlurMaxSlider.setValue($DOFPostFx::BlurMax); ppOptionsDOFFocusRangeMinSlider.setValue($DOFPostFx::FocusRangeMin); ppOptionsDOFFocusRangeMaxSlider.setValue($DOFPostFx::FocusRangeMax); ppOptionsDOFBlurCurveNearSlider.setValue($DOFPostFx::BlurCurveNear); ppOptionsDOFBlurCurveFarSlider.setValue($DOFPostFx::BlurCurveFar); } function PostFXManager::settingsRefreshSharpness(%this) { //Apply the enabled flag ppOptionsEnableSharpness.setValue($PostFXManager::PostFX::EnableSharpness); ppOptionsSharpenRange.setValue($SharpPostFx::sharpRange); ppOptionsSharpenStrength.setValue($SharpPostFx::sharpPower); ppOptionsSharpenWidth.setValue($SharpPostFx::sharpWidth); } function PostFXManager::settingsRefreshNightVision(%this) { //Apply the enabled flag ppOptionsEnableNV.setValue($PostFXManager::PostFX::EnableNightVision); ppOptionsNVDistFreq.setValue($NVPostFx::DistFreq); ppOptionsNVDistMul.setValue($NVPostFx::DistMul); ppOptionsNVDistRoll.setValue($NVPostFx::DistRoll); ppOptionsNVBright.setValue($NVPostFx::brightThreshold); ppOptionsNVHighMul.setValue($NVPostFx::highMultiplier); ppOptionsNVLowMul.setValue($NVPostFx::lowMultiplier); } function PostFXManager::settingsRefreshAll(%this) { $PostFXManager::PostFX::Enabled = $pref::enablePostEffects; $PostFXManager::PostFX::EnableSSAO = SSAOPostFx.isEnabled(); $PostFXManager::PostFX::EnableHDR = HDRPostFX.isEnabled(); $PostFXManager::PostFX::EnableLightRays = LightRayPostFX.isEnabled(); $PostFXManager::PostFX::EnableDOF = DOFPostEffect.isEnabled(); $PostFXManager::PostFX::EnableSharpness = ""; $PostFXManager::PostFX::EnableNightVision = ""; //For all the postFX here, apply the active settings in the system //to the gui controls. %this.settingsRefreshSSAO(); %this.settingsRefreshHDR(); %this.settingsRefreshLightrays(); %this.settingsRefreshDOF(); %this.settingsRefreshSharpness(); %this.settingsRefreshNightVision(); postVerbose("% - PostFX Manager - GUI values updated."); } function PostFXManager::settingsApplyFromPreset(%this) { postVerbose("% - PostFX Manager - Applying from preset"); //SSAO Settings $SSAOPostFx::blurDepthTol = $PostFXManager::Settings::SSAO::blurDepthTol; $SSAOPostFx::blurNormalTol = $PostFXManager::Settings::SSAO::blurNormalTol; $SSAOPostFx::lDepthMax = $PostFXManager::Settings::SSAO::lDepthMax; $SSAOPostFx::lDepthMin = $PostFXManager::Settings::SSAO::lDepthMin; $SSAOPostFx::lDepthPow = $PostFXManager::Settings::SSAO::lDepthPow; $SSAOPostFx::lNormalPow = $PostFXManager::Settings::SSAO::lNormalPow; $SSAOPostFx::lNormalTol = $PostFXManager::Settings::SSAO::lNormalTol; $SSAOPostFx::lRadius = $PostFXManager::Settings::SSAO::lRadius; $SSAOPostFx::lStrength = $PostFXManager::Settings::SSAO::lStrength; $SSAOPostFx::overallStrength = $PostFXManager::Settings::SSAO::overallStrength; $SSAOPostFx::quality = $PostFXManager::Settings::SSAO::quality; $SSAOPostFx::sDepthMax = $PostFXManager::Settings::SSAO::sDepthMax; $SSAOPostFx::sDepthMin = $PostFXManager::Settings::SSAO::sDepthMin; $SSAOPostFx::sDepthPow = $PostFXManager::Settings::SSAO::sDepthPow; $SSAOPostFx::sNormalPow = $PostFXManager::Settings::SSAO::sNormalPow; $SSAOPostFx::sNormalTol = $PostFXManager::Settings::SSAO::sNormalTol; $SSAOPostFx::sRadius = $PostFXManager::Settings::SSAO::sRadius; $SSAOPostFx::sStrength = $PostFXManager::Settings::SSAO::sStrength; //HDR settings $HDRPostFX::adaptRate = $PostFXManager::Settings::HDR::adaptRate; $HDRPostFX::blueShiftColor = $PostFXManager::Settings::HDR::blueShiftColor; $HDRPostFX::brightPassThreshold = $PostFXManager::Settings::HDR::brightPassThreshold; $HDRPostFX::enableBloom = $PostFXManager::Settings::HDR::enableBloom; $HDRPostFX::enableBlueShift = $PostFXManager::Settings::HDR::enableBlueShift; $HDRPostFX::enableToneMapping = $PostFXManager::Settings::HDR::enableToneMapping; $HDRPostFX::gaussMean = $PostFXManager::Settings::HDR::gaussMean; $HDRPostFX::gaussMultiplier = $PostFXManager::Settings::HDR::gaussMultiplier; $HDRPostFX::gaussStdDev = $PostFXManager::Settings::HDR::gaussStdDev; $HDRPostFX::keyValue = $PostFXManager::Settings::HDR::keyValue; $HDRPostFX::minLuminace = $PostFXManager::Settings::HDR::minLuminace; $HDRPostFX::whiteCutoff = $PostFXManager::Settings::HDR::whiteCutoff; //Light rays settings $LightRayPostFX::brightScalar = $PostFXManager::Settings::LightRays::brightScalar; //DOF settings $DOFPostFx::EnableAutoFocus = $PostFXManager::Settings::DOF::EnableAutoFocus; $DOFPostFx::BlurMin = $PostFXManager::Settings::DOF::BlurMin; $DOFPostFx::BlurMax = $PostFXManager::Settings::DOF::BlurMax; $DOFPostFx::FocusRangeMin = $PostFXManager::Settings::DOF::FocusRangeMin; $DOFPostFx::FocusRangeMax = $PostFXManager::Settings::DOF::FocusRangeMax; $DOFPostFx::BlurCurveNear = $PostFXManager::Settings::DOF::BlurCurveNear; $DOFPostFx::BlurCurveFar = $PostFXManager::Settings::DOF::BlurCurveFar; //Sharpen effect settings $SharpPostFx::sharpRange = $PostFXManager::Settings::Sharpen::sharpRange; $SharpPostFx::sharpWidth = $PostFXManager::Settings::Sharpen::sharpWidth; $SharpPostFx::sharpPower = $PostFXManager::Settings::Sharpen::sharpPower; //Night vision $NVPostFx::brightThreshold = $PostFXManager::Settings::NightVision::brightThreshold; $NVPostFx::DistFreq = $PostFXManager::Settings::NightVision::DistFreq; $NVPostFx::DistMul = $PostFXManager::Settings::NightVision::DistMul; $NVPostFx::DistRoll = $PostFXManager::Settings::NightVision::DistRoll; $NVPostFx::lowMultiplier = $PostFXManager::Settings::NightVision::lowMultiplier; $NVPostFx::highMultiplier = $PostFXManager::Settings::NightVision::highMultiplier; if ( $PostFXManager::forceEnableFromPresets ) { $PostFXManager::PostFX::Enabled = $PostFXManager::Settings::EnablePostFX; $PostFXManager::PostFX::EnableNightVision = $PostFXManager::Settings::EnableNightVision; $PostFXManager::PostFX::EnableSharpen = $PostFXManager::Settings::EnableSharpen; $PostFXManager::PostFX::EnableDOF = $PostFXManager::Settings::EnableDOF; $PostFXManager::PostFX::EnableLightRays = $PostFXManager::Settings::EnableLightRays; $PostFXManager::PostFX::EnableHDR = $PostFXManager::Settings::EnableHDR; $PostFXManager::PostFX::EnableSSAO = $PostFXManager::Settings::EnabledSSAO; %this.settingsSetEnabled( true ); } //make sure we apply the correct settings to the DOF ppOptionsUpdateDOFSettings(); // Update the actual GUI controls if its awake ( otherwise it will when opened ). if ( PostFXManager.isAwake() ) %this.settingsRefreshAll(); } function PostFXManager::settingsApplySSAO(%this) { $PostFXManager::Settings::SSAO::blurDepthTol = $SSAOPostFx::blurDepthTol; $PostFXManager::Settings::SSAO::blurNormalTol = $SSAOPostFx::blurNormalTol; $PostFXManager::Settings::SSAO::lDepthMax = $SSAOPostFx::lDepthMax; $PostFXManager::Settings::SSAO::lDepthMin = $SSAOPostFx::lDepthMin; $PostFXManager::Settings::SSAO::lDepthPow = $SSAOPostFx::lDepthPow; $PostFXManager::Settings::SSAO::lNormalPow = $SSAOPostFx::lNormalPow; $PostFXManager::Settings::SSAO::lNormalTol = $SSAOPostFx::lNormalTol; $PostFXManager::Settings::SSAO::lRadius = $SSAOPostFx::lRadius; $PostFXManager::Settings::SSAO::lStrength = $SSAOPostFx::lStrength; $PostFXManager::Settings::SSAO::overallStrength = $SSAOPostFx::overallStrength; $PostFXManager::Settings::SSAO::quality = $SSAOPostFx::quality; $PostFXManager::Settings::SSAO::sDepthMax = $SSAOPostFx::sDepthMax; $PostFXManager::Settings::SSAO::sDepthMin = $SSAOPostFx::sDepthMin; $PostFXManager::Settings::SSAO::sDepthPow = $SSAOPostFx::sDepthPow; $PostFXManager::Settings::SSAO::sNormalPow = $SSAOPostFx::sNormalPow; $PostFXManager::Settings::SSAO::sNormalTol = $SSAOPostFx::sNormalTol; $PostFXManager::Settings::SSAO::sRadius = $SSAOPostFx::sRadius; $PostFXManager::Settings::SSAO::sStrength = $SSAOPostFx::sStrength; postVerbose("% - PostFX Manager - Settings Saved - SSAO"); } function PostFXManager::settingsApplyHDR(%this) { $PostFXManager::Settings::HDR::adaptRate = $HDRPostFX::adaptRate; $PostFXManager::Settings::HDR::blueShiftColor = $HDRPostFX::blueShiftColor; $PostFXManager::Settings::HDR::brightPassThreshold = $HDRPostFX::brightPassThreshold; $PostFXManager::Settings::HDR::enableBloom = $HDRPostFX::enableBloom; $PostFXManager::Settings::HDR::enableBlueShift = $HDRPostFX::enableBlueShift; $PostFXManager::Settings::HDR::enableToneMapping = $HDRPostFX::enableToneMapping; $PostFXManager::Settings::HDR::gaussMean = $HDRPostFX::gaussMean; $PostFXManager::Settings::HDR::gaussMultiplier = $HDRPostFX::gaussMultiplier; $PostFXManager::Settings::HDR::gaussStdDev = $HDRPostFX::gaussStdDev; $PostFXManager::Settings::HDR::keyValue = $HDRPostFX::keyValue; $PostFXManager::Settings::HDR::minLuminace = $HDRPostFX::minLuminace; $PostFXManager::Settings::HDR::whiteCutoff = $HDRPostFX::whiteCutoff; postVerbose("% - PostFX Manager - Settings Saved - HDR"); } function PostFXManager::settingsApplyLightRays(%this) { $PostFXManager::Settings::LightRays::brightScalar = $LightRayPostFX::brightScalar; postVerbose("% - PostFX Manager - Settings Saved - Light Rays"); } function PostFXManager::settingsApplyDOF(%this) { $PostFXManager::Settings::DOF::EnableAutoFocus = $DOFPostFx::EnableAutoFocus; $PostFXManager::Settings::DOF::BlurMin = $DOFPostFx::BlurMin; $PostFXManager::Settings::DOF::BlurMax = $DOFPostFx::BlurMax; $PostFXManager::Settings::DOF::FocusRangeMin = $DOFPostFx::FocusRangeMin; $PostFXManager::Settings::DOF::FocusRangeMax = $DOFPostFx::FocusRangeMax; $PostFXManager::Settings::DOF::BlurCurveNear = $DOFPostFx::BlurCurveNear; $PostFXManager::Settings::DOF::BlurCurveFar = $DOFPostFx::BlurCurveFar; postVerbose("% - PostFX Manager - Settings Saved - DOF"); } function PostFXManager::settingsApplySharpen(%this) { $PostFXManager::Settings::Sharpen::sharpRange = $SharpPostFx::sharpRange; $PostFXManager::Settings::Sharpen::sharpWidth = $SharpPostFx::sharpWidth; $PostFXManager::Settings::Sharpen::sharpPower = $SharpPostFx::sharpPower; postVerbose("% - PostFX Manager - Settings Saved - Sharpen"); } function PostFXManager::settingsApplyNightVision(%this) { $PostFXManager::Settings::NightVision::brightThreshold = $NVPostFx::brightThreshold; $PostFXManager::Settings::NightVision::DistFreq = $NVPostFx::DistFreq; $PostFXManager::Settings::NightVision::DistMul = $NVPostFx::DistMul; $PostFXManager::Settings::NightVision::DistRoll = $NVPostFx::DistRoll; $PostFXManager::Settings::NightVision::highMultiplier = $NVPostFx::highMultiplier; $PostFXManager::Settings::NightVision::lowMultiplier = $NVPostFx::lowMultiplier; postVerbose("% - PostFX Manager - Settings Saved - Night Vision"); } function PostFXManager::settingsApplyAll(%this, %sFrom) { // Apply settings which control if effects are on/off altogether. $PostFXManager::Settings::EnablePostFX = $PostFXManager::PostFX::Enabled; $PostFXManager::Settings::EnableNightVision = $PostFXManager::PostFX::EnableNightVision; $PostFXManager::Settings::EnableSharpen = $PostFXManager::PostFX::EnableSharpen; $PostFXManager::Settings::EnableDOF = $PostFXManager::PostFX::EnableDOF; $PostFXManager::Settings::EnableLightRays = $PostFXManager::PostFX::EnableLightRays; $PostFXManager::Settings::EnableHDR = $PostFXManager::PostFX::EnableHDR; $PostFXManager::Settings::EnabledSSAO = $PostFXManager::PostFX::EnableSSAO; // Apply settings should save the values in the system to the // the preset structure ($PostFXManager::Settings::*) // SSAO Settings %this.settingsApplySSAO(); // HDR settings %this.settingsApplyHDR(); // Light rays settings %this.settingsApplyLightRays(); // DOF %this.settingsApplyDOF(); // Sharpness %this.settingsApplySharpen(); // NV %this.settingsApplyNightVision(); postVerbose("% - PostFX Manager - All Settings applied to $PostFXManager::Settings"); } function PostFXManager::settingsApplyDefaultPreset(%this) { PostFXManager::loadPresetHandler($PostFXManager::defaultPreset); }
namespace AxiomCoders.PdfTemplateEditor.Forms { partial class OptionsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tabControl = new System.Windows.Forms.TabControl(); this.tabPage_General = new System.Windows.Forms.TabPage(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.showBalloonBordersCheckBox = new System.Windows.Forms.CheckBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.autoSaveEnableCheckBox = new System.Windows.Forms.CheckBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.tabPage_Rulers = new System.Windows.Forms.TabPage(); this.unitComboBox = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.tabPage_Grid = new System.Windows.Forms.TabPage(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label8 = new System.Windows.Forms.Label(); this.gridUnitComboBox = new System.Windows.Forms.ComboBox(); this.snapToGridCheckBox = new System.Windows.Forms.CheckBox(); this.showMinorLinesCheckBox = new System.Windows.Forms.CheckBox(); this.label7 = new System.Windows.Forms.Label(); this.showGridCheckBox = new System.Windows.Forms.CheckBox(); this.label6 = new System.Windows.Forms.Label(); this.styleComboBox = new System.Windows.Forms.ComboBox(); this.gridColorPicker = new System.Windows.Forms.Button(); this.OkApplyButton = new System.Windows.Forms.Button(); this.applyButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.btnHelp = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.txtNumOffPreviewItems = new AxiomCoders.PdfTemplateEditor.Controls.NumericTextBox(); this.autoSaveIntervalTextBox = new AxiomCoders.PdfTemplateEditor.Controls.NumericTextBox(); this.subsValueTextBox = new AxiomCoders.PdfTemplateEditor.Controls.NumericTextBox(); this.gridValueTextBox = new AxiomCoders.PdfTemplateEditor.Controls.NumericTextBox(); this.tabControl.SuspendLayout(); this.tabPage_General.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox2.SuspendLayout(); this.tabPage_Rulers.SuspendLayout(); this.tabPage_Grid.SuspendLayout(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // tabControl // this.tabControl.Controls.Add(this.tabPage_General); this.tabControl.Controls.Add(this.tabPage_Rulers); this.tabControl.Controls.Add(this.tabPage_Grid); this.tabControl.Location = new System.Drawing.Point(12, 12); this.tabControl.Name = "tabControl"; this.tabControl.SelectedIndex = 0; this.tabControl.Size = new System.Drawing.Size(335, 199); this.tabControl.TabIndex = 0; // // tabPage_General // this.tabPage_General.Controls.Add(this.groupBox3); this.tabPage_General.Controls.Add(this.groupBox2); this.tabPage_General.Location = new System.Drawing.Point(4, 22); this.tabPage_General.Name = "tabPage_General"; this.tabPage_General.Padding = new System.Windows.Forms.Padding(3); this.tabPage_General.Size = new System.Drawing.Size(327, 173); this.tabPage_General.TabIndex = 2; this.tabPage_General.Text = "General"; this.tabPage_General.UseVisualStyleBackColor = true; // // groupBox3 // this.groupBox3.Controls.Add(this.txtNumOffPreviewItems); this.groupBox3.Controls.Add(this.label4); this.groupBox3.Controls.Add(this.showBalloonBordersCheckBox); this.groupBox3.Location = new System.Drawing.Point(8, 98); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(308, 69); this.groupBox3.TabIndex = 1; this.groupBox3.TabStop = false; this.groupBox3.Text = "Common"; // // showBalloonBordersCheckBox // this.showBalloonBordersCheckBox.AutoSize = true; this.showBalloonBordersCheckBox.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.showBalloonBordersCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.showBalloonBordersCheckBox.Location = new System.Drawing.Point(7, 19); this.showBalloonBordersCheckBox.Name = "showBalloonBordersCheckBox"; this.showBalloonBordersCheckBox.Size = new System.Drawing.Size(137, 18); this.showBalloonBordersCheckBox.TabIndex = 0; this.showBalloonBordersCheckBox.Text = "Show balloon borders:"; this.showBalloonBordersCheckBox.UseVisualStyleBackColor = true; this.showBalloonBordersCheckBox.CheckedChanged += new System.EventHandler(this.showBalloonBordersCheckBox_CheckedChanged); // // groupBox2 // this.groupBox2.Controls.Add(this.autoSaveEnableCheckBox); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.autoSaveIntervalTextBox); this.groupBox2.Location = new System.Drawing.Point(8, 11); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(308, 80); this.groupBox2.TabIndex = 0; this.groupBox2.TabStop = false; this.groupBox2.Text = "Auto save"; // // autoSaveEnableCheckBox // this.autoSaveEnableCheckBox.AutoSize = true; this.autoSaveEnableCheckBox.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.autoSaveEnableCheckBox.Checked = true; this.autoSaveEnableCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.autoSaveEnableCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.autoSaveEnableCheckBox.Location = new System.Drawing.Point(8, 49); this.autoSaveEnableCheckBox.Name = "autoSaveEnableCheckBox"; this.autoSaveEnableCheckBox.Size = new System.Drawing.Size(118, 18); this.autoSaveEnableCheckBox.TabIndex = 1; this.autoSaveEnableCheckBox.Text = "Enable auto save:"; this.autoSaveEnableCheckBox.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.autoSaveEnableCheckBox.UseVisualStyleBackColor = true; this.autoSaveEnableCheckBox.CheckedChanged += new System.EventHandler(this.autoSaveEnableCheckBox_CheckedChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 26); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(95, 13); this.label2.TabIndex = 0; this.label2.Text = "Auto save interval:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(159, 26); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(24, 13); this.label3.TabIndex = 2; this.label3.Text = "sec"; // // tabPage_Rulers // this.tabPage_Rulers.Controls.Add(this.unitComboBox); this.tabPage_Rulers.Controls.Add(this.label1); this.tabPage_Rulers.Location = new System.Drawing.Point(4, 22); this.tabPage_Rulers.Name = "tabPage_Rulers"; this.tabPage_Rulers.Padding = new System.Windows.Forms.Padding(3); this.tabPage_Rulers.Size = new System.Drawing.Size(327, 173); this.tabPage_Rulers.TabIndex = 0; this.tabPage_Rulers.Text = "Rulers & Units"; this.tabPage_Rulers.UseVisualStyleBackColor = true; // // unitComboBox // this.unitComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.unitComboBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.unitComboBox.FormattingEnabled = true; this.unitComboBox.Items.AddRange(new object[] { "inch", "mm", "cm", "pixel"}); this.unitComboBox.Location = new System.Drawing.Point(38, 18); this.unitComboBox.Name = "unitComboBox"; this.unitComboBox.Size = new System.Drawing.Size(103, 21); this.unitComboBox.TabIndex = 0; this.unitComboBox.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 21); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(26, 13); this.label1.TabIndex = 0; this.label1.Text = "Unit"; // // tabPage_Grid // this.tabPage_Grid.Controls.Add(this.groupBox1); this.tabPage_Grid.Location = new System.Drawing.Point(4, 22); this.tabPage_Grid.Name = "tabPage_Grid"; this.tabPage_Grid.Padding = new System.Windows.Forms.Padding(3); this.tabPage_Grid.Size = new System.Drawing.Size(327, 173); this.tabPage_Grid.TabIndex = 1; this.tabPage_Grid.Text = "Guides, Grid"; this.tabPage_Grid.UseVisualStyleBackColor = true; // // groupBox1 // this.groupBox1.Controls.Add(this.subsValueTextBox); this.groupBox1.Controls.Add(this.label8); this.groupBox1.Controls.Add(this.gridUnitComboBox); this.groupBox1.Controls.Add(this.snapToGridCheckBox); this.groupBox1.Controls.Add(this.gridValueTextBox); this.groupBox1.Controls.Add(this.showMinorLinesCheckBox); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.showGridCheckBox); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.styleComboBox); this.groupBox1.Controls.Add(this.gridColorPicker); this.groupBox1.Location = new System.Drawing.Point(6, 10); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(311, 154); this.groupBox1.TabIndex = 13; this.groupBox1.TabStop = false; this.groupBox1.Text = "Grid"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(11, 80); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(69, 13); this.label8.TabIndex = 7; this.label8.Text = "Subdivisions:"; // // gridUnitComboBox // this.gridUnitComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.gridUnitComboBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.gridUnitComboBox.FormattingEnabled = true; this.gridUnitComboBox.Items.AddRange(new object[] { "inch", "cm", "mm", "pixels"}); this.gridUnitComboBox.Location = new System.Drawing.Point(130, 50); this.gridUnitComboBox.Name = "gridUnitComboBox"; this.gridUnitComboBox.Size = new System.Drawing.Size(73, 21); this.gridUnitComboBox.TabIndex = 2; this.gridUnitComboBox.SelectedIndexChanged += new System.EventHandler(this.gridUnitComboBox_SelectedIndexChanged); // // snapToGridCheckBox // this.snapToGridCheckBox.AutoSize = true; this.snapToGridCheckBox.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.snapToGridCheckBox.Location = new System.Drawing.Point(210, 108); this.snapToGridCheckBox.Name = "snapToGridCheckBox"; this.snapToGridCheckBox.Size = new System.Drawing.Size(83, 17); this.snapToGridCheckBox.TabIndex = 7; this.snapToGridCheckBox.Text = "Snap to grid"; this.snapToGridCheckBox.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.snapToGridCheckBox.UseVisualStyleBackColor = true; this.snapToGridCheckBox.Visible = false; this.snapToGridCheckBox.CheckedChanged += new System.EventHandler(this.snapToGridCheckBox_CheckedChanged); // // showMinorLinesCheckBox // this.showMinorLinesCheckBox.AutoSize = true; this.showMinorLinesCheckBox.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.showMinorLinesCheckBox.Checked = true; this.showMinorLinesCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.showMinorLinesCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.showMinorLinesCheckBox.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.showMinorLinesCheckBox.Location = new System.Drawing.Point(92, 107); this.showMinorLinesCheckBox.Name = "showMinorLinesCheckBox"; this.showMinorLinesCheckBox.Size = new System.Drawing.Size(111, 18); this.showMinorLinesCheckBox.TabIndex = 6; this.showMinorLinesCheckBox.Text = "Show minor lines"; this.showMinorLinesCheckBox.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.showMinorLinesCheckBox.UseVisualStyleBackColor = true; this.showMinorLinesCheckBox.CheckedChanged += new System.EventHandler(this.ShowMiLines_CheckedChanged); // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(6, 53); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(74, 13); this.label7.TabIndex = 4; this.label7.Text = "Gridline every:"; // // showGridCheckBox // this.showGridCheckBox.AutoSize = true; this.showGridCheckBox.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.showGridCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.showGridCheckBox.Location = new System.Drawing.Point(7, 107); this.showGridCheckBox.Name = "showGridCheckBox"; this.showGridCheckBox.Size = new System.Drawing.Size(79, 18); this.showGridCheckBox.TabIndex = 5; this.showGridCheckBox.Text = "Show grid"; this.showGridCheckBox.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.showGridCheckBox.UseVisualStyleBackColor = true; this.showGridCheckBox.CheckedChanged += new System.EventHandler(this.ShowGr_CheckedChanged); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(47, 26); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(33, 13); this.label6.TabIndex = 3; this.label6.Text = "Style:"; // // styleComboBox // this.styleComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.styleComboBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.styleComboBox.FormattingEnabled = true; this.styleComboBox.Items.AddRange(new object[] { "Lines", "Dashed Lines", "Dots"}); this.styleComboBox.Location = new System.Drawing.Point(86, 23); this.styleComboBox.Name = "styleComboBox"; this.styleComboBox.Size = new System.Drawing.Size(97, 21); this.styleComboBox.TabIndex = 0; this.styleComboBox.SelectedIndexChanged += new System.EventHandler(this.styleComboBox_SelectedIndexChanged); // // gridColorPicker // this.gridColorPicker.BackColor = System.Drawing.Color.DarkGray; this.gridColorPicker.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.gridColorPicker.Location = new System.Drawing.Point(246, 24); this.gridColorPicker.Name = "gridColorPicker"; this.gridColorPicker.Size = new System.Drawing.Size(47, 47); this.gridColorPicker.TabIndex = 3; this.gridColorPicker.UseVisualStyleBackColor = false; this.gridColorPicker.Click += new System.EventHandler(this.MjColor_Click); // // OkApplyButton // this.OkApplyButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.OkApplyButton.Location = new System.Drawing.Point(353, 32); this.OkApplyButton.Name = "OkApplyButton"; this.OkApplyButton.Size = new System.Drawing.Size(75, 23); this.OkApplyButton.TabIndex = 1; this.OkApplyButton.Text = "&Ok"; this.OkApplyButton.UseVisualStyleBackColor = true; this.OkApplyButton.Click += new System.EventHandler(this.OkApplyButton_Click); // // applyButton // this.applyButton.Enabled = false; this.applyButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.applyButton.Location = new System.Drawing.Point(353, 102); this.applyButton.Name = "applyButton"; this.applyButton.Size = new System.Drawing.Size(75, 23); this.applyButton.TabIndex = 3; this.applyButton.Text = "&Apply"; this.applyButton.UseVisualStyleBackColor = true; this.applyButton.Click += new System.EventHandler(this.applyButton_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.cancelButton.Location = new System.Drawing.Point(353, 61); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 2; this.cancelButton.Text = "&Cancel"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // btnHelp // this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnHelp.Location = new System.Drawing.Point(353, 188); this.btnHelp.Name = "btnHelp"; this.btnHelp.Size = new System.Drawing.Size(75, 23); this.btnHelp.TabIndex = 4; this.btnHelp.Text = "&Help"; this.btnHelp.UseVisualStyleBackColor = true; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(0, 0); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(100, 20); this.textBox1.TabIndex = 0; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(4, 46); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(111, 13); this.label4.TabIndex = 2; this.label4.Text = "Num of preview items:"; // // txtNumOffPreviewItems // this.txtNumOffPreviewItems.AllowSpace = false; this.txtNumOffPreviewItems.Location = new System.Drawing.Point(132, 43); this.txtNumOffPreviewItems.Name = "txtNumOffPreviewItems"; this.txtNumOffPreviewItems.Size = new System.Drawing.Size(60, 20); this.txtNumOffPreviewItems.TabIndex = 3; this.txtNumOffPreviewItems.Text = "10"; this.txtNumOffPreviewItems.TextChanged += new System.EventHandler(this.txtNumOffPreviewItems_TextChanged); // // autoSaveIntervalTextBox // this.autoSaveIntervalTextBox.AllowSpace = false; this.autoSaveIntervalTextBox.Location = new System.Drawing.Point(107, 23); this.autoSaveIntervalTextBox.Name = "autoSaveIntervalTextBox"; this.autoSaveIntervalTextBox.Size = new System.Drawing.Size(46, 20); this.autoSaveIntervalTextBox.TabIndex = 0; this.autoSaveIntervalTextBox.TextChanged += new System.EventHandler(this.autoSaveIntervalTextBox_TextChanged); // // subsValueTextBox // this.subsValueTextBox.AllowSpace = false; this.subsValueTextBox.Location = new System.Drawing.Point(86, 77); this.subsValueTextBox.Name = "subsValueTextBox"; this.subsValueTextBox.Size = new System.Drawing.Size(38, 20); this.subsValueTextBox.TabIndex = 4; this.subsValueTextBox.TextChanged += new System.EventHandler(this.subsValueTextBox_TextChanged); // // gridValueTextBox // this.gridValueTextBox.AllowSpace = false; this.gridValueTextBox.Location = new System.Drawing.Point(86, 50); this.gridValueTextBox.Name = "gridValueTextBox"; this.gridValueTextBox.Size = new System.Drawing.Size(38, 20); this.gridValueTextBox.TabIndex = 1; this.gridValueTextBox.TextChanged += new System.EventHandler(this.gridValueTextBox_TextChanged); // // OptionsForm // this.AcceptButton = this.OkApplyButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(440, 225); this.Controls.Add(this.btnHelp); this.Controls.Add(this.cancelButton); this.Controls.Add(this.applyButton); this.Controls.Add(this.OkApplyButton); this.Controls.Add(this.tabControl); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "OptionsForm"; this.Text = "Preferences"; this.TopMost = true; this.tabControl.ResumeLayout(false); this.tabPage_General.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.tabPage_Rulers.ResumeLayout(false); this.tabPage_Rulers.PerformLayout(); this.tabPage_Grid.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl tabControl; private System.Windows.Forms.TabPage tabPage_Rulers; private System.Windows.Forms.ComboBox unitComboBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.TabPage tabPage_Grid; private System.Windows.Forms.Button OkApplyButton; private System.Windows.Forms.Button gridColorPicker; private System.Windows.Forms.CheckBox showGridCheckBox; private System.Windows.Forms.CheckBox showMinorLinesCheckBox; private System.Windows.Forms.CheckBox snapToGridCheckBox; private System.Windows.Forms.TabPage tabPage_General; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.ComboBox gridUnitComboBox; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox styleComboBox; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.CheckBox autoSaveEnableCheckBox; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.CheckBox showBalloonBordersCheckBox; private System.Windows.Forms.Button applyButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.TextBox textBox1; private AxiomCoders.PdfTemplateEditor.Controls.NumericTextBox gridValueTextBox; private AxiomCoders.PdfTemplateEditor.Controls.NumericTextBox subsValueTextBox; private AxiomCoders.PdfTemplateEditor.Controls.NumericTextBox autoSaveIntervalTextBox; private AxiomCoders.PdfTemplateEditor.Controls.NumericTextBox txtNumOffPreviewItems; private System.Windows.Forms.Label label4; } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="CustomerAssetServiceClient"/> instances.</summary> public sealed partial class CustomerAssetServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CustomerAssetServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CustomerAssetServiceSettings"/>.</returns> public static CustomerAssetServiceSettings GetDefault() => new CustomerAssetServiceSettings(); /// <summary>Constructs a new <see cref="CustomerAssetServiceSettings"/> object with default settings.</summary> public CustomerAssetServiceSettings() { } private CustomerAssetServiceSettings(CustomerAssetServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateCustomerAssetsSettings = existing.MutateCustomerAssetsSettings; OnCopy(existing); } partial void OnCopy(CustomerAssetServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerAssetServiceClient.MutateCustomerAssets</c> and /// <c>CustomerAssetServiceClient.MutateCustomerAssetsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateCustomerAssetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="CustomerAssetServiceSettings"/> object.</returns> public CustomerAssetServiceSettings Clone() => new CustomerAssetServiceSettings(this); } /// <summary> /// Builder class for <see cref="CustomerAssetServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class CustomerAssetServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerAssetServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CustomerAssetServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CustomerAssetServiceClientBuilder() { UseJwtAccessWithScopes = CustomerAssetServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CustomerAssetServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerAssetServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CustomerAssetServiceClient Build() { CustomerAssetServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CustomerAssetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CustomerAssetServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CustomerAssetServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CustomerAssetServiceClient.Create(callInvoker, Settings); } private async stt::Task<CustomerAssetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CustomerAssetServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CustomerAssetServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerAssetServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerAssetServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>CustomerAssetService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage customer assets. /// </remarks> public abstract partial class CustomerAssetServiceClient { /// <summary> /// The default endpoint for the CustomerAssetService service, which is a host of "googleads.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default CustomerAssetService scopes.</summary> /// <remarks> /// The default CustomerAssetService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="CustomerAssetServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="CustomerAssetServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CustomerAssetServiceClient"/>.</returns> public static stt::Task<CustomerAssetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CustomerAssetServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CustomerAssetServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="CustomerAssetServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CustomerAssetServiceClient"/>.</returns> public static CustomerAssetServiceClient Create() => new CustomerAssetServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CustomerAssetServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="CustomerAssetServiceSettings"/>.</param> /// <returns>The created <see cref="CustomerAssetServiceClient"/>.</returns> internal static CustomerAssetServiceClient Create(grpccore::CallInvoker callInvoker, CustomerAssetServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CustomerAssetService.CustomerAssetServiceClient grpcClient = new CustomerAssetService.CustomerAssetServiceClient(callInvoker); return new CustomerAssetServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC CustomerAssetService client</summary> public virtual CustomerAssetService.CustomerAssetServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomerAssetsResponse MutateCustomerAssets(MutateCustomerAssetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerAssetsResponse> MutateCustomerAssetsAsync(MutateCustomerAssetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerAssetsResponse> MutateCustomerAssetsAsync(MutateCustomerAssetsRequest request, st::CancellationToken cancellationToken) => MutateCustomerAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose customer assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual customer assets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomerAssetsResponse MutateCustomerAssets(string customerId, scg::IEnumerable<CustomerAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCustomerAssets(new MutateCustomerAssetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose customer assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual customer assets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerAssetsResponse> MutateCustomerAssetsAsync(string customerId, scg::IEnumerable<CustomerAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCustomerAssetsAsync(new MutateCustomerAssetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose customer assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual customer assets. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerAssetsResponse> MutateCustomerAssetsAsync(string customerId, scg::IEnumerable<CustomerAssetOperation> operations, st::CancellationToken cancellationToken) => MutateCustomerAssetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CustomerAssetService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage customer assets. /// </remarks> public sealed partial class CustomerAssetServiceClientImpl : CustomerAssetServiceClient { private readonly gaxgrpc::ApiCall<MutateCustomerAssetsRequest, MutateCustomerAssetsResponse> _callMutateCustomerAssets; /// <summary> /// Constructs a client wrapper for the CustomerAssetService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="CustomerAssetServiceSettings"/> used within this client.</param> public CustomerAssetServiceClientImpl(CustomerAssetService.CustomerAssetServiceClient grpcClient, CustomerAssetServiceSettings settings) { GrpcClient = grpcClient; CustomerAssetServiceSettings effectiveSettings = settings ?? CustomerAssetServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateCustomerAssets = clientHelper.BuildApiCall<MutateCustomerAssetsRequest, MutateCustomerAssetsResponse>(grpcClient.MutateCustomerAssetsAsync, grpcClient.MutateCustomerAssets, effectiveSettings.MutateCustomerAssetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateCustomerAssets); Modify_MutateCustomerAssetsApiCall(ref _callMutateCustomerAssets); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateCustomerAssetsApiCall(ref gaxgrpc::ApiCall<MutateCustomerAssetsRequest, MutateCustomerAssetsResponse> call); partial void OnConstruction(CustomerAssetService.CustomerAssetServiceClient grpcClient, CustomerAssetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CustomerAssetService client</summary> public override CustomerAssetService.CustomerAssetServiceClient GrpcClient { get; } partial void Modify_MutateCustomerAssetsRequest(ref MutateCustomerAssetsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateCustomerAssetsResponse MutateCustomerAssets(MutateCustomerAssetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomerAssetsRequest(ref request, ref callSettings); return _callMutateCustomerAssets.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes customer assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateCustomerAssetsResponse> MutateCustomerAssetsAsync(MutateCustomerAssetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomerAssetsRequest(ref request, ref callSettings); return _callMutateCustomerAssets.Async(request, callSettings); } } }
// ========================================================== // Updated to use UGUI, March 2015 // Dennis Trevillyan - WatreGames // using UnityEngine; using UnityEngine.UI; using System.Collections; using UMA; namespace UMA.Examples { public class UMACustomization : MonoBehaviour { public UMAData umaData; public UMADynamicAvatar umaDynamicAvatar; public CameraTrack cameraTrack; public UMAMouseOrbitImproved orbitor; private UMADnaHumanoid umaDna; private UMADnaTutorial umaTutorialDna; private GameObject DnaPanel; // This is the parent panel private GameObject DnaScrollPanel; // This is the scrollable panel that holds the sliders // Slider objects private Slider HeightSlider; private Slider UpperMuscleSlider; private Slider UpperWeightSlider; private Slider LowerMuscleSlider; private Slider LowerWeightSlider; private Slider ArmLengthSlider; private Slider ForearmLengthSlider; private Slider LegSeparationSlider; private Slider HandSizeSlider; private Slider FeetSizeSlider; private Slider LegSizeSlider; private Slider ArmWidthSlider; private Slider ForearmWidthSlider; private Slider BreastSlider; private Slider BellySlider; private Slider WaistSizeSlider; private Slider GlueteusSizeSlider; private Slider HeadSizeSlider; private Slider NeckThickSlider; private Slider EarSizeSlider; private Slider EarPositionSlider; private Slider EarRotationSlider; private Slider NoseSizeSlider; private Slider NoseCurveSlider; private Slider NoseWidthSlider; private Slider NoseInclinationSlider; private Slider NosePositionSlider; private Slider NosePronuncedSlider; private Slider NoseFlattenSlider; private Slider ChinSizeSlider; private Slider ChinPronouncedSlider; private Slider ChinPositionSlider; private Slider MandibleSizeSlider; private Slider JawSizeSlider; private Slider JawPositionSlider; private Slider CheekSizeSlider; private Slider CheekPositionSlider; private Slider lowCheekPronSlider; private Slider ForeHeadSizeSlider; private Slider ForeHeadPositionSlider; private Slider LipSizeSlider; private Slider MouthSlider; private Slider EyeSizeSlider; private Slider EyeRotationSlider; private Slider EyeSpacingSlider; private Slider LowCheekPosSlider; private Slider HeadWidthSlider; private Slider[] sliders; private Rect ViewPortReduced; private Transform baseTarget; private Button DnaHide; // get the sliders and store for later use void Awake() { // Find the panels and hide for now DnaPanel = GameObject.Find("DnaEditorPanel"); if (DnaPanel == null || DnaPanel.activeSelf == false) return; HeightSlider = GameObject.Find("HeightSlider").GetComponent<Slider>(); UpperMuscleSlider = GameObject.Find("UpperMuscleSlider").GetComponent<Slider>(); UpperWeightSlider = GameObject.Find("UpperWeightSlider").GetComponent<Slider>(); LowerMuscleSlider = GameObject.Find("LowerMuscleSlider").GetComponent<Slider>(); LowerWeightSlider = GameObject.Find("LowerWeightSlider").GetComponent<Slider>(); ArmLengthSlider = GameObject.Find("ArmLengthSlider").GetComponent<Slider>(); ForearmLengthSlider = GameObject.Find("ForearmLengthSlider").GetComponent<Slider>(); LegSeparationSlider = GameObject.Find("LegSepSlider").GetComponent<Slider>(); HandSizeSlider = GameObject.Find("HandSizeSlider").GetComponent<Slider>(); FeetSizeSlider = GameObject.Find("FeetSizeSlider").GetComponent<Slider>(); LegSizeSlider = GameObject.Find("LegSizeSlider").GetComponent<Slider>(); ArmWidthSlider = GameObject.Find("ArmWidthSlider").GetComponent<Slider>(); ForearmWidthSlider = GameObject.Find("ForearmWidthSlider").GetComponent<Slider>(); BreastSlider = GameObject.Find("BreastSizeSlider").GetComponent<Slider>(); BellySlider = GameObject.Find("BellySlider").GetComponent<Slider>(); WaistSizeSlider = GameObject.Find("WaistSizeSlider").GetComponent<Slider>(); GlueteusSizeSlider = GameObject.Find("GluteusSlider").GetComponent<Slider>(); HeadSizeSlider = GameObject.Find("HeadSizeSlider").GetComponent<Slider>(); HeadWidthSlider = GameObject.Find("HeadWidthSlider").GetComponent<Slider>(); NeckThickSlider = GameObject.Find("NeckSlider").GetComponent<Slider>(); EarSizeSlider = GameObject.Find("EarSizeSlider").GetComponent<Slider>(); EarPositionSlider = GameObject.Find("EarPosSlider").GetComponent<Slider>(); EarRotationSlider = GameObject.Find("EarRotSlider").GetComponent<Slider>(); NoseSizeSlider = GameObject.Find("NoseSizeSlider").GetComponent<Slider>(); NoseCurveSlider = GameObject.Find("NoseCurveSlider").GetComponent<Slider>(); NoseWidthSlider = GameObject.Find("NoseWidthSlider").GetComponent<Slider>(); NoseInclinationSlider = GameObject.Find("NoseInclineSlider").GetComponent<Slider>(); NosePositionSlider = GameObject.Find("NosePosSlider").GetComponent<Slider>(); NosePronuncedSlider = GameObject.Find("NosePronSlider").GetComponent<Slider>(); NoseFlattenSlider = GameObject.Find("NoseFlatSlider").GetComponent<Slider>(); ChinSizeSlider = GameObject.Find("ChinSizeSlider").GetComponent<Slider>(); ChinPronouncedSlider = GameObject.Find("ChinPronSlider").GetComponent<Slider>(); ChinPositionSlider = GameObject.Find("ChinPosSlider").GetComponent<Slider>(); MandibleSizeSlider = GameObject.Find("MandibleSizeSlider").GetComponent<Slider>(); JawSizeSlider = GameObject.Find("JawSizeSlider").GetComponent<Slider>(); JawPositionSlider = GameObject.Find("JawPosSlider").GetComponent<Slider>(); CheekSizeSlider = GameObject.Find("CheekSizeSlider").GetComponent<Slider>(); CheekPositionSlider = GameObject.Find("CheekPosSlider").GetComponent<Slider>(); lowCheekPronSlider = GameObject.Find("LowCheekPronSlider").GetComponent<Slider>(); ForeHeadSizeSlider = GameObject.Find("ForeheadSizeSlider").GetComponent<Slider>(); ForeHeadPositionSlider = GameObject.Find("ForeheadPosSlider").GetComponent<Slider>(); LipSizeSlider = GameObject.Find("LipSizeSlider").GetComponent<Slider>(); MouthSlider = GameObject.Find("MouthSizeSlider").GetComponent<Slider>(); EyeSizeSlider = GameObject.Find("EyeSizeSlider").GetComponent<Slider>(); EyeRotationSlider = GameObject.Find("EyeRotSlider").GetComponent<Slider>(); EyeSpacingSlider = GameObject.Find("EyeSpaceSlider").GetComponent<Slider>(); LowCheekPosSlider = GameObject.Find("LowCheekPosSlider").GetComponent<Slider>(); DnaPanel.SetActive(false); var oldUIMask = DnaPanel.GetComponent<Mask>(); if (oldUIMask != null) { DestroyImmediate(oldUIMask); DnaPanel.AddComponent<RectMask2D>(); } // Find the DNA hide button and hide it for now DnaHide = GameObject.Find("MessagePanel").GetComponentInChildren<Button>(); DnaHide.gameObject.SetActive(false); } protected virtual void Start() { //float vpWidth; // sliders = DnaScrollPanel.GetComponentsInChildren<Slider>(); // Create an array of the sliders to use for initialization //vpWidth = ((float)Screen.width - 175) / (float)Screen.width; // Get the width of the screen so that we can adjust the viewport //ViewPortReduced = new Rect(0, 0, vpWidth, 1); //Camera.main.rect = ViewPortFull; baseTarget = GameObject.Find("UMACrowd").transform; // Get the transform of the UMA Crown GO to use when retargeting the camera } void Update() { /*if (umaTutorialDna != null) EyeSpacingSlider.interactable = true; else EyeSpacingSlider.interactable = false;*/ // Don't raycast if the editor is open if (umaData != null) return; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1)) { if (Physics.Raycast(ray, out hit, 100)) { Transform tempTransform = hit.collider.transform; umaData = tempTransform.GetComponent<UMAData>(); if (umaData) { AvatarSetup(); } } } } // An avatar has been selected, setup the camera, sliders, retarget the camera, and adjust the viewport // to account for the DNA slider scroll panel public void AvatarSetup() { umaDynamicAvatar = umaData.gameObject.GetComponent<UMADynamicAvatar>(); if (cameraTrack) { cameraTrack.target = umaData.umaRoot.transform; } if (orbitor) { orbitor.target = umaData.umaRoot.transform; } umaDna = umaData.GetDna<UMADnaHumanoid>(); umaTutorialDna = umaData.GetDna<UMADnaTutorial>(); if (umaDna != null) { SetSliders(); } //SetUpDNASliders(); SetCamera(true); } // Set the camera target and viewport private void SetCamera(bool show) { if (DnaPanel == null) return; if (show) { DnaPanel.SetActive(true); DnaHide.gameObject.SetActive(true); // really Unity? Yes we change the value and set it back to trigger a ui recalculation... // because setting the damn game object active doesn't do that! var rt = DnaPanel.GetComponent<RectTransform>(); var pos = rt.offsetMin; rt.offsetMin = new Vector2(pos.x + 1, pos.y); rt.offsetMin = pos; } else { if (cameraTrack != null) cameraTrack.target = baseTarget; if (orbitor != null) orbitor.target = baseTarget; DnaPanel.SetActive(false); DnaHide.gameObject.SetActive(false); umaData = null; umaDna = null; umaTutorialDna = null; } } // Button callback to hide slider scroll panel public void HideDnaSlider() { SetCamera(false); } public void UpdateUMAAtlas() { if (umaData != null) { umaData.isTextureDirty = true; umaData.Dirty(); } } public void UpdateUMAShape() { if (umaData != null) { umaData.isShapeDirty = true; umaData.Dirty(); } } // Set all of the sliders to the values contained in the UMA Character public void SetSliders() { HeightSlider.value = umaDna.height; UpperMuscleSlider.value = umaDna.upperMuscle; UpperWeightSlider.value = umaDna.upperWeight; LowerMuscleSlider.value = umaDna.lowerMuscle; LowerWeightSlider.value = umaDna.lowerWeight; ArmLengthSlider.value = umaDna.armLength; ForearmLengthSlider.value = umaDna.forearmLength; LegSeparationSlider.value = umaDna.legSeparation; HandSizeSlider.value = umaDna.handsSize; FeetSizeSlider.value = umaDna.feetSize; LegSizeSlider.value = umaDna.legsSize; ArmWidthSlider.value = umaDna.armWidth; ForearmWidthSlider.value = umaDna.forearmWidth; BreastSlider.value = umaDna.breastSize; BellySlider.value = umaDna.belly; WaistSizeSlider.value = umaDna.waist; GlueteusSizeSlider.value = umaDna.gluteusSize; HeadSizeSlider.value = umaDna.headSize; HeadWidthSlider.value = umaDna.headWidth; NeckThickSlider.value = umaDna.neckThickness; EarSizeSlider.value = umaDna.earsSize; EarPositionSlider.value = umaDna.earsPosition; EarRotationSlider.value = umaDna.earsRotation; NoseSizeSlider.value = umaDna.noseSize; NoseCurveSlider.value = umaDna.noseCurve; NoseWidthSlider.value = umaDna.noseWidth; NoseInclinationSlider.value = umaDna.noseInclination; NosePositionSlider.value = umaDna.nosePosition; NosePronuncedSlider.value = umaDna.nosePronounced; NoseFlattenSlider.value = umaDna.noseFlatten; ChinSizeSlider.value = umaDna.chinSize; ChinPronouncedSlider.value = umaDna.chinPronounced; ChinPositionSlider.value = umaDna.chinPosition; MandibleSizeSlider.value = umaDna.mandibleSize; JawSizeSlider.value = umaDna.jawsSize; JawPositionSlider.value = umaDna.jawsPosition; CheekSizeSlider.value = umaDna.cheekSize; CheekPositionSlider.value = umaDna.cheekPosition; lowCheekPronSlider.value = umaDna.lowCheekPronounced; ForeHeadSizeSlider.value = umaDna.foreheadSize; ForeHeadPositionSlider.value = umaDna.foreheadPosition; LipSizeSlider.value = umaDna.lipsSize; MouthSlider.value = umaDna.mouthSize; EyeSizeSlider.value = umaDna.eyeSize; EyeRotationSlider.value = umaDna.eyeRotation; LowCheekPosSlider.value = umaDna.lowCheekPosition; if (umaTutorialDna != null) EyeSpacingSlider.value = umaTutorialDna.eyeSpacing; } // Slider callbacks public void OnHeightChange() { if (umaDna != null) umaDna.height = HeightSlider.value; UpdateUMAShape(); } public void OnUpperMuscleChange() { if (umaDna != null) umaDna.upperMuscle = UpperMuscleSlider.value; UpdateUMAShape(); } public void OnUpperWeightChange() { if (umaDna != null) umaDna.upperWeight = UpperWeightSlider.value; UpdateUMAShape(); } public void OnLowerMuscleChange() { if (umaDna != null) umaDna.lowerMuscle = LowerMuscleSlider.value; UpdateUMAShape(); } public void OnLowerWeightChange() { if (umaDna != null) umaDna.lowerWeight = LowerWeightSlider.value; UpdateUMAShape(); } public void OnArmLengthChange() { if (umaDna != null) umaDna.armLength = ArmLengthSlider.value; UpdateUMAShape(); } public void OnForearmLengthChange() { if (umaDna != null) umaDna.forearmLength = ForearmLengthSlider.value; UpdateUMAShape(); } public void OnLegSeparationChange() { if (umaDna != null) umaDna.legSeparation = LegSeparationSlider.value; UpdateUMAShape(); } public void OnHandSizeChange() { if (umaDna != null) umaDna.handsSize = HandSizeSlider.value; UpdateUMAShape(); } public void OnFootSizeChange() { if (umaDna != null) umaDna.feetSize = FeetSizeSlider.value; UpdateUMAShape(); } public void OnLegSizeChange() { if (umaDna != null) umaDna.legsSize = LegSizeSlider.value; UpdateUMAShape(); } public void OnArmWidthChange() { if (umaDna != null) umaDna.armWidth = ArmWidthSlider.value; UpdateUMAShape(); } public void OnForearmWidthChange() { if (umaDna != null) umaDna.forearmWidth = ForearmWidthSlider.value; UpdateUMAShape(); } public void OnBreastSizeChange() { if (umaDna != null) umaDna.breastSize = BreastSlider.value; UpdateUMAShape(); } public void OnBellySizeChange() { if (umaDna != null) umaDna.belly = BellySlider.value; UpdateUMAShape(); } public void OnWaistSizeChange() { if (umaDna != null) umaDna.waist = WaistSizeSlider.value; UpdateUMAShape(); } public void OnGluteusSizeChange() { if (umaDna != null) umaDna.gluteusSize = GlueteusSizeSlider.value; UpdateUMAShape(); } public void OnHeadSizeChange() { if (umaDna != null) umaDna.headSize = HeadSizeSlider.value; UpdateUMAShape(); } public void OnHeadWidthChange() { if (umaDna != null) umaDna.headWidth = HeadWidthSlider.value; UpdateUMAShape(); } public void OnNeckThicknessChange() { if (umaDna != null) umaDna.neckThickness = NeckThickSlider.value; UpdateUMAShape(); } public void OnEarSizeChange() { if (umaDna != null) umaDna.earsSize = EarSizeSlider.value; UpdateUMAShape(); } public void OnEarPositionChange() { if (umaDna != null) umaDna.earsPosition = EarPositionSlider.value; UpdateUMAShape(); } public void OnEarRotationChange() { if (umaDna != null) umaDna.earsRotation = EarRotationSlider.value; UpdateUMAShape(); } public void OnNoseSizeChange() { if (umaDna != null) umaDna.noseSize = NoseSizeSlider.value; UpdateUMAShape(); } public void OnNoseCurveChange() { if (umaDna != null) umaDna.noseCurve = NoseCurveSlider.value; UpdateUMAShape(); } public void OnNoseWidthChange() { if (umaDna != null) umaDna.noseWidth = NoseWidthSlider.value; UpdateUMAShape(); } public void OnNoseInclinationChange() { if (umaDna != null) umaDna.noseInclination = NoseInclinationSlider.value; UpdateUMAShape(); } public void OnNosePositionChange() { if (umaDna != null) umaDna.nosePosition = NosePositionSlider.value; UpdateUMAShape(); } public void OnNosePronouncedChange() { if (umaDna != null) umaDna.nosePronounced = NosePronuncedSlider.value; UpdateUMAShape(); } public void OnNoseFlattenChange() { if (umaDna != null) umaDna.noseFlatten = NoseFlattenSlider.value; UpdateUMAShape(); } public void OnChinSizeChange() { if (umaDna != null) umaDna.chinSize = ChinSizeSlider.value; UpdateUMAShape(); } public void OnChinPronouncedChange() { if (umaDna != null) umaDna.chinPronounced = ChinPronouncedSlider.value; UpdateUMAShape(); } public void OnChinPositionChange() { if (umaDna != null) umaDna.chinPosition = ChinPositionSlider.value; UpdateUMAShape(); } public void OnMandibleSizeChange() { if (umaDna != null) umaDna.mandibleSize = MandibleSizeSlider.value; UpdateUMAShape(); } public void OnJawSizeChange() { if (umaDna != null) umaDna.jawsSize = JawSizeSlider.value; UpdateUMAShape(); } public void OnJawPositionChange() { if (umaDna != null) umaDna.jawsPosition = JawPositionSlider.value; UpdateUMAShape(); } public void OnCheekSizeChange() { if (umaDna != null) umaDna.cheekSize = CheekSizeSlider.value; UpdateUMAShape(); } public void OnCheekPositionChange() { if (umaDna != null) umaDna.cheekPosition = CheekPositionSlider.value; UpdateUMAShape(); } public void OnCheekLowPronouncedChange() { if (umaDna != null) umaDna.lowCheekPronounced = lowCheekPronSlider.value; UpdateUMAShape(); } public void OnForeheadSizeChange() { if (umaDna != null) umaDna.foreheadSize = ForeHeadSizeSlider.value; UpdateUMAShape(); } public void OnForeheadPositionChange() { if (umaDna != null) umaDna.foreheadPosition = ForeHeadPositionSlider.value; UpdateUMAShape(); } public void OnLipSizeChange() { if (umaDna != null) umaDna.lipsSize = LipSizeSlider.value; UpdateUMAShape(); } public void OnMouthSizeChange() { if (umaDna != null) umaDna.mouthSize = MouthSlider.value; UpdateUMAShape(); } public void OnEyeSizechange() { if (umaDna != null) umaDna.eyeSize = EyeSizeSlider.value; UpdateUMAShape(); } public void OnEyeRotationChange() { if (umaDna != null) umaDna.eyeRotation = EyeRotationSlider.value; UpdateUMAShape(); } public void OnLowCheekPositionChange() { if (umaDna != null) umaDna.lowCheekPosition = LowCheekPosSlider.value; UpdateUMAShape(); } public void OnEyeSpacingChange() { if (umaTutorialDna != null) umaTutorialDna.eyeSpacing = EyeSpacingSlider.value; UpdateUMAShape(); } public void PerformDNAChange(string dnaName, float dnaValue) { if(umaData != null) { foreach(UMADnaBase dna in umaData.umaRecipe.GetAllDna()) { if(System.Array.IndexOf(dna.Names, dnaName) > -1) { int index = System.Array.IndexOf(dna.Names, dnaName); dna.SetValue(index, dnaValue); } } } } } }
// 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.Drawing; using System.Linq; using System.IO; using System.Threading.Tasks; using Android.App; using Android.OS; using Android.Widget; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks; using Esri.ArcGISRuntime.Tasks.Offline; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using ArcGISRuntimeXamarin.Managers; namespace ArcGISRuntimeXamarin.Samples.GenerateGeodatabase { [Activity] public class GenerateGeodatabase : Activity { // URI for a feature service that supports geodatabase generation private Uri _featureServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer"); // Path to the geodatabase file on disk private string _gdbPath; // Task to be used for generating the geodatabase private GeodatabaseSyncTask _gdbSyncTask; // Job used to generate the geodatabase private GenerateGeodatabaseJob _generateGdbJob; // Mapview private MapView myMapView; // Generate Button private Button myGenerateButton; // Progress bar private ProgressBar myProgressBar; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Generate geodatabase"; // Create the UI, setup the control references and execute initialization CreateLayout(); Initialize(); } private void CreateLayout() { // Create the layout LinearLayout layout = new LinearLayout(this); layout.Orientation = Orientation.Vertical; // Add the progress bar myProgressBar = new ProgressBar(this); myProgressBar.Visibility = Android.Views.ViewStates.Gone; layout.AddView(myProgressBar); // Add the generate button myGenerateButton = new Button(this); myGenerateButton.Text = "Generate"; myGenerateButton.Click += GenerateButton_Clicked; layout.AddView(myGenerateButton); // Add the mapview myMapView = new MapView(this); layout.AddView(myMapView); // Add the layout to the view SetContentView(layout); } private async void Initialize() { // Create a tile cache and load it with the SanFrancisco streets tpk TileCache _tileCache = new TileCache(await GetTpkPath()); // Create the corresponding layer based on the tile cache ArcGISTiledLayer _tileLayer = new ArcGISTiledLayer(_tileCache); // Create the basemap based on the tile cache Basemap _sfBasemap = new Basemap(_tileLayer); // Create the map with the tile-based basemap Map myMap = new Map(_sfBasemap); // Assign the map to the MapView myMapView.Map = myMap; // Create a new symbol for the extent graphic SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2); // Create graphics overlay for the extent graphic and apply a renderer GraphicsOverlay extentOverlay = new GraphicsOverlay(); extentOverlay.Renderer = new SimpleRenderer(lineSymbol); // Add graphics overlay to the map view myMapView.GraphicsOverlays.Add(extentOverlay); // Set up an event handler for when the viewpoint (extent) changes myMapView.ViewpointChanged += MapViewExtentChanged; // Update the local data path for the geodatabase file _gdbPath = GetGdbPath(); // Create a task for generating a geodatabase (GeodatabaseSyncTask) _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri); // Add all graphics from the service to the map foreach (var layer in _gdbSyncTask.ServiceInfo.LayerInfos) { // Create the ServiceFeatureTable for this particular layer ServiceFeatureTable onlineTable = new ServiceFeatureTable(new Uri(_featureServiceUri + "/" + layer.Id)); // Wait for the table to load await onlineTable.LoadAsync(); // Add the layer to the map's operational layers if load succeeds if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded) { myMap.OperationalLayers.Add(new FeatureLayer(onlineTable)); } } } private void UpdateMapExtent() { // Return if mapview is null if (myMapView == null) { return; } // Get the new viewpoint Viewpoint myViewPoint = myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); // Return if viewpoint is null if (myViewPoint == null) { return; } // Get the updated extent for the new viewpoint Envelope extent = myViewPoint.TargetGeometry as Envelope; // Return if extent is null if (extent == null) { return; } // Create an envelope that is a bit smaller than the extent EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent); envelopeBldr.Expand(0.80); // Get the (only) graphics overlay in the map view var extentOverlay = myMapView.GraphicsOverlays.FirstOrDefault(); // Return if the extent overlay is null if (extentOverlay == null) { return; } // Get the extent graphic Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault(); // Create the extent graphic and add it to the overlay if it doesn't exist if (extentGraphic == null) { extentGraphic = new Graphic(envelopeBldr.ToGeometry()); extentOverlay.Graphics.Add(extentGraphic); } else { // Otherwise, simply update the graphic's geometry extentGraphic.Geometry = envelopeBldr.ToGeometry(); } } private async void StartGeodatabaseGeneration() { // Create a task for generating a geodatabase (GeodatabaseSyncTask) _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri); // Get the current extent of the red preview box Envelope extent = myMapView.GraphicsOverlays.FirstOrDefault().Extent as Envelope; // Get the default parameters for the generate geodatabase task GenerateGeodatabaseParameters generateParams = await _gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent); // Create a generate geodatabase job _generateGdbJob = _gdbSyncTask.GenerateGeodatabase(generateParams, _gdbPath); // Handle the job changed event _generateGdbJob.JobChanged += GenerateGdbJobChanged; // Handle the progress changed event (to show progress bar) _generateGdbJob.ProgressChanged += ((object sender, EventArgs e) => { UpdateProgressBar(); }); // Start the job _generateGdbJob.Start(); } private async void HandleGenerationStatusChange(GenerateGeodatabaseJob job) { JobStatus status = job.Status; // If the job completed successfully, add the geodatabase data to the map if (status == JobStatus.Succeeded) { // Clear out the existing layers myMapView.Map.OperationalLayers.Clear(); // Get the new geodatabase Geodatabase resultGdb = await job.GetResultAsync(); // Loop through all feature tables in the geodatabase and add a new layer to the map foreach (GeodatabaseFeatureTable table in resultGdb.GeodatabaseFeatureTables) { // Create a new feature layer for the table FeatureLayer _layer = new FeatureLayer(table); // Add the new layer to the map myMapView.Map.OperationalLayers.Add(_layer); } // Best practice is to unregister the geodatabase await _gdbSyncTask.UnregisterGeodatabaseAsync(resultGdb); // Tell the user that the geodatabase was unregistered ShowStatusMessage("Since no edits will be made, the local geodatabase has been unregistered per best practice."); } // See if the job failed if (status == JobStatus.Failed) { // Create a message to show the user string message = "Generate geodatabase job failed"; // Show an error message (if there is one) if (job.Error != null) { message += ": " + job.Error.Message; } else { // If no error, show messages from the job var m = from msg in job.Messages select msg.Message; message += ": " + string.Join<string>("\n", m); } ShowStatusMessage(message); } } // Get the path to the tile package used for the basemap private async Task<string> GetTpkPath() { // The desired tpk is expected to be called SanFrancisco.tpk string filename = "SanFrancisco.tpk"; // The data manager provides a method to get the folder string folder = DataManager.GetDataFolder(); // Get the full path string filepath = Path.Combine(folder, "SampleData", "GenerateGeodatabase", filename); // Check if the file exists if (!File.Exists(filepath)) { // Download the map package file await DataManager.GetData("3f1bbf0ec70b409a975f5c91f363fe7d", "GenerateGeodatabase"); } return filepath; } private string GetGdbPath() { return GetFileStreamPath("wildfire.geodatabase").AbsolutePath; } private void ShowStatusMessage(string message) { // Display the message to the user var builder = new AlertDialog.Builder(this); builder.SetMessage(message).SetTitle("Alert").Show(); } // Handler for the generate button clicked event private void GenerateButton_Clicked(object sender, EventArgs e) { // Call the cross-platform geodatabase generation method StartGeodatabaseGeneration(); } // Handler for the MapView Extent Changed event private void MapViewExtentChanged(object sender, EventArgs e) { // Call the cross-platform map extent update method UpdateMapExtent(); } // Handler for the job changed event private void GenerateGdbJobChanged(object sender, EventArgs e) { // Get the job object; will be passed to HandleGenerationStatusChange GenerateGeodatabaseJob job = sender as GenerateGeodatabaseJob; // Due to the nature of the threading implementation, // the dispatcher needs to be used to interact with the UI RunOnUiThread(() => { // Update progress bar visibility if (job.Status == JobStatus.Started) { myProgressBar.Visibility = Android.Views.ViewStates.Visible; } else { myProgressBar.Visibility = Android.Views.ViewStates.Gone; } // Do the remainder of the job status changed work HandleGenerationStatusChange(job); }); } private void UpdateProgressBar() { // Due to the nature of the threading implementation, // the dispatcher needs to be used to interact with the UI RunOnUiThread(() => { // Update the progress bar value myProgressBar.Progress = _generateGdbJob.Progress; }); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.Serialization; using System.ComponentModel.DataAnnotations; namespace Sample.Contracts { #region Contact class definition /// <summary> /// Contact datacontract class. /// </summary> [DataContract(Namespace = "urn:Sample.Contracts", IsReference = true), Serializable()] public partial class Contact : BaseObject { /// <summary> /// Constructs a new Contact datacontract instance. /// </summary> public Contact() : base() { this.OnInstanceCreated(); } partial void OnInstanceCreated(); private System.Int32 _id; /// <summary> /// Id property. /// </summary> [DataMember()] public System.Int32 Id { get { return this._id; } set { this._id = value; this.OnAnIdentifierPropertyChanged(); this.OnIdPropertyChanged(value); this.OnPropertyChanged("Id", value); } } partial void OnIdPropertyChanged(System.Int32 newValue); private System.String _title; /// <summary> /// Title property. /// </summary> [DataMember()] public System.String Title { get { return this._title; } set { this._title = value; this.OnTitlePropertyChanged(value); this.OnPropertyChanged("Title", value); } } partial void OnTitlePropertyChanged(System.String newValue); private System.String _firstName; /// <summary> /// FirstName property. /// </summary> [DataMember()] public System.String FirstName { get { return this._firstName; } set { this._firstName = value; this.OnFirstNamePropertyChanged(value); this.OnPropertyChanged("FirstName", value); } } partial void OnFirstNamePropertyChanged(System.String newValue); private System.String _middleName; /// <summary> /// MiddleName property. /// </summary> [DataMember()] public System.String MiddleName { get { return this._middleName; } set { this._middleName = value; this.OnMiddleNamePropertyChanged(value); this.OnPropertyChanged("MiddleName", value); } } partial void OnMiddleNamePropertyChanged(System.String newValue); private System.String _lastName; /// <summary> /// LastName property. /// </summary> [DataMember()] public System.String LastName { get { return this._lastName; } set { this._lastName = value; this.OnLastNamePropertyChanged(value); this.OnPropertyChanged("LastName", value); } } partial void OnLastNamePropertyChanged(System.String newValue); private System.String _suffix; /// <summary> /// Suffix property. /// </summary> [DataMember()] public System.String Suffix { get { return this._suffix; } set { this._suffix = value; this.OnSuffixPropertyChanged(value); this.OnPropertyChanged("Suffix", value); } } partial void OnSuffixPropertyChanged(System.String newValue); private System.String _emailAddress; /// <summary> /// EmailAddress property. /// </summary> [DataMember()] public System.String EmailAddress { get { return this._emailAddress; } set { this._emailAddress = value; this.OnEmailAddressPropertyChanged(value); this.OnPropertyChanged("EmailAddress", value); } } partial void OnEmailAddressPropertyChanged(System.String newValue); private System.String _phone; /// <summary> /// Phone property. /// </summary> [DataMember()] public System.String Phone { get { return this._phone; } set { this._phone = value; this.OnPhonePropertyChanged(value); this.OnPropertyChanged("Phone", value); } } partial void OnPhonePropertyChanged(System.String newValue); partial void OnPropertyChanged(string propertyName, object newValue); // For internal use only: partial void OnAnIdentifierPropertyChanged(); } #endregion #region Employee class definition /// <summary> /// Employee datacontract class. /// </summary> [DataContract(Namespace = "urn:Sample.Contracts", IsReference = true), Serializable()] [KnownType(typeof(SalesPerson))] public partial class Employee : System.Object { /// <summary> /// Constructs a new Employee datacontract instance. /// </summary> public Employee() : base() { this.OnInstanceCreated(); } partial void OnInstanceCreated(); private System.Int32 _id; /// <summary> /// Id property. /// </summary> [DataMember()] public System.Int32 Id { get { return this._id; } set { this._id = value; this.OnAnIdentifierPropertyChanged(); this.OnIdPropertyChanged(value); this.OnPropertyChanged("Id", value); } } partial void OnIdPropertyChanged(System.Int32 newValue); private Contact _contact; /// <summary> /// Contact property. /// </summary> [DataMember()] public Contact Contact { get { return this._contact; } set { this._contact = value; this.OnContactPropertyChanged(value); this.OnPropertyChanged("Contact", value); } } partial void OnContactPropertyChanged(Contact newValue); private System.String _gender; /// <summary> /// Gender property. /// </summary> [DataMember()] public System.String Gender { get { return this._gender; } set { this._gender = value; this.OnGenderPropertyChanged(value); this.OnPropertyChanged("Gender", value); } } partial void OnGenderPropertyChanged(System.String newValue); private System.DateTime _birthDate; /// <summary> /// BirthDate property. /// </summary> [DataMember()] public System.DateTime BirthDate { get { return this._birthDate; } set { this._birthDate = value; this.OnBirthDatePropertyChanged(value); this.OnPropertyChanged("BirthDate", value); } } partial void OnBirthDatePropertyChanged(System.DateTime newValue); private System.DateTime _hireDate; /// <summary> /// HireDate property. /// </summary> [DataMember()] public System.DateTime HireDate { get { return this._hireDate; } set { this._hireDate = value; this.OnHireDatePropertyChanged(value); this.OnPropertyChanged("HireDate", value); } } partial void OnHireDatePropertyChanged(System.DateTime newValue); private System.Nullable<System.Int32> _managerId; /// <summary> /// ManagerId property. /// </summary> [DataMember()] public System.Nullable<System.Int32> ManagerId { get { return this._managerId; } set { this._managerId = value; this.OnManagerIdPropertyChanged(value); this.OnPropertyChanged("ManagerId", value); } } partial void OnManagerIdPropertyChanged(System.Nullable<System.Int32> newValue); partial void OnPropertyChanged(string propertyName, object newValue); // For internal use only: partial void OnAnIdentifierPropertyChanged(); } #endregion #region EmployeeItem class definition /// <summary> /// EmployeeItem datacontract class. /// </summary> [DataContract(Namespace = "urn:Sample.Contracts", IsReference = true), Serializable()] public partial class EmployeeItem : System.Object { /// <summary> /// Constructs a new EmployeeItem datacontract instance. /// </summary> public EmployeeItem() : base() { this.OnInstanceCreated(); } partial void OnInstanceCreated(); private System.Int32 _id; /// <summary> /// Id property. /// </summary> [DataMember()] public System.Int32 Id { get { return this._id; } set { this._id = value; this.OnAnIdentifierPropertyChanged(); this.OnIdPropertyChanged(value); this.OnPropertyChanged("Id", value); } } partial void OnIdPropertyChanged(System.Int32 newValue); private System.String _title; /// <summary> /// Title property. /// </summary> [DataMember()] public System.String Title { get { return this._title; } set { this._title = value; this.OnTitlePropertyChanged(value); this.OnPropertyChanged("Title", value); } } partial void OnTitlePropertyChanged(System.String newValue); private System.String _firstName; /// <summary> /// FirstName property. /// </summary> [DataMember()] public System.String FirstName { get { return this._firstName; } set { this._firstName = value; this.OnFirstNamePropertyChanged(value); this.OnPropertyChanged("FirstName", value); } } partial void OnFirstNamePropertyChanged(System.String newValue); private System.String _middleName; /// <summary> /// MiddleName property. /// </summary> [DataMember()] public System.String MiddleName { get { return this._middleName; } set { this._middleName = value; this.OnMiddleNamePropertyChanged(value); this.OnPropertyChanged("MiddleName", value); } } partial void OnMiddleNamePropertyChanged(System.String newValue); private System.String _lastName; /// <summary> /// LastName property. /// </summary> [DataMember()] public System.String LastName { get { return this._lastName; } set { this._lastName = value; this.OnLastNamePropertyChanged(value); this.OnPropertyChanged("LastName", value); } } partial void OnLastNamePropertyChanged(System.String newValue); private System.String _gender; /// <summary> /// Gender property. /// </summary> [DataMember()] public System.String Gender { get { return this._gender; } set { this._gender = value; this.OnGenderPropertyChanged(value); this.OnPropertyChanged("Gender", value); } } partial void OnGenderPropertyChanged(System.String newValue); private System.DateTime _birthDate; /// <summary> /// BirthDate property. /// </summary> [DataMember()] public System.DateTime BirthDate { get { return this._birthDate; } set { this._birthDate = value; this.OnBirthDatePropertyChanged(value); this.OnPropertyChanged("BirthDate", value); } } partial void OnBirthDatePropertyChanged(System.DateTime newValue); private System.Nullable<System.Int32> _managerId; /// <summary> /// ManagerId property. /// </summary> [DataMember()] public System.Nullable<System.Int32> ManagerId { get { return this._managerId; } set { this._managerId = value; this.OnManagerIdPropertyChanged(value); this.OnPropertyChanged("ManagerId", value); } } partial void OnManagerIdPropertyChanged(System.Nullable<System.Int32> newValue); private System.String _managerFirstName; /// <summary> /// ManagerFirstName property. /// </summary> [DataMember()] public System.String ManagerFirstName { get { return this._managerFirstName; } set { this._managerFirstName = value; this.OnManagerFirstNamePropertyChanged(value); this.OnPropertyChanged("ManagerFirstName", value); } } partial void OnManagerFirstNamePropertyChanged(System.String newValue); private System.String _managerMiddleName; /// <summary> /// ManagerMiddleName property. /// </summary> [DataMember()] public System.String ManagerMiddleName { get { return this._managerMiddleName; } set { this._managerMiddleName = value; this.OnManagerMiddleNamePropertyChanged(value); this.OnPropertyChanged("ManagerMiddleName", value); } } partial void OnManagerMiddleNamePropertyChanged(System.String newValue); private System.String _managerLastName; /// <summary> /// ManagerLastName property. /// </summary> [DataMember()] public System.String ManagerLastName { get { return this._managerLastName; } set { this._managerLastName = value; this.OnManagerLastNamePropertyChanged(value); this.OnPropertyChanged("ManagerLastName", value); } } partial void OnManagerLastNamePropertyChanged(System.String newValue); partial void OnPropertyChanged(string propertyName, object newValue); // For internal use only: partial void OnAnIdentifierPropertyChanged(); } #endregion #region Manager class definition /// <summary> /// Manager datacontract class. /// </summary> [DataContract(Namespace = "urn:Sample.Contracts", IsReference = true), Serializable()] public partial class Manager : System.Object { /// <summary> /// Constructs a new Manager datacontract instance. /// </summary> public Manager() : base() { this.Subordinates = new System.Collections.Generic.List<Subordinate>(); this.OnInstanceCreated(); } partial void OnInstanceCreated(); private System.Int32 _id; /// <summary> /// Id property. /// </summary> [DataMember()] public System.Int32 Id { get { return this._id; } set { this._id = value; this.OnAnIdentifierPropertyChanged(); this.OnIdPropertyChanged(value); this.OnPropertyChanged("Id", value); } } partial void OnIdPropertyChanged(System.Int32 newValue); private Contact _contact; /// <summary> /// Contact property. /// </summary> [DataMember()] public Contact Contact { get { return this._contact; } set { this._contact = value; this.OnContactPropertyChanged(value); this.OnPropertyChanged("Contact", value); } } partial void OnContactPropertyChanged(Contact newValue); private System.String _gender; /// <summary> /// Gender property. /// </summary> [DataMember()] public System.String Gender { get { return this._gender; } set { this._gender = value; this.OnGenderPropertyChanged(value); this.OnPropertyChanged("Gender", value); } } partial void OnGenderPropertyChanged(System.String newValue); private System.DateTime _birthDate; /// <summary> /// BirthDate property. /// </summary> [DataMember()] public System.DateTime BirthDate { get { return this._birthDate; } set { this._birthDate = value; this.OnBirthDatePropertyChanged(value); this.OnPropertyChanged("BirthDate", value); } } partial void OnBirthDatePropertyChanged(System.DateTime newValue); private System.DateTime _hireDate; /// <summary> /// HireDate property. /// </summary> [DataMember()] public System.DateTime HireDate { get { return this._hireDate; } set { this._hireDate = value; this.OnHireDatePropertyChanged(value); this.OnPropertyChanged("HireDate", value); } } partial void OnHireDatePropertyChanged(System.DateTime newValue); /// <summary> /// Subordinates property. /// </summary> [DataMember()] public System.Collections.Generic.List<Subordinate> Subordinates { get; set; } partial void OnPropertyChanged(string propertyName, object newValue); // For internal use only: partial void OnAnIdentifierPropertyChanged(); } #endregion #region SalesPerson class definition /// <summary> /// SalesPerson datacontract class. /// </summary> [DataContract(Namespace = "urn:Sample.Contracts"), Serializable()] public partial class SalesPerson : Employee { /// <summary> /// Constructs a new SalesPerson datacontract instance. /// </summary> public SalesPerson() : base() { this.OnInstanceCreated(); } partial void OnInstanceCreated(); private System.Nullable<System.Decimal> _salesQuota; /// <summary> /// SalesQuota property. /// </summary> [DataMember()] public System.Nullable<System.Decimal> SalesQuota { get { return this._salesQuota; } set { this._salesQuota = value; this.OnSalesQuotaPropertyChanged(value); this.OnPropertyChanged("SalesQuota", value); } } partial void OnSalesQuotaPropertyChanged(System.Nullable<System.Decimal> newValue); private System.Decimal _bonus; /// <summary> /// Bonus property. /// </summary> [DataMember()] public System.Decimal Bonus { get { return this._bonus; } set { this._bonus = value; this.OnBonusPropertyChanged(value); this.OnPropertyChanged("Bonus", value); } } partial void OnBonusPropertyChanged(System.Decimal newValue); private System.Decimal _commissionPct; /// <summary> /// CommissionPct property. /// </summary> [DataMember()] public System.Decimal CommissionPct { get { return this._commissionPct; } set { this._commissionPct = value; this.OnCommissionPctPropertyChanged(value); this.OnPropertyChanged("CommissionPct", value); } } partial void OnCommissionPctPropertyChanged(System.Decimal newValue); private System.Decimal _salesYTD; /// <summary> /// SalesYTD property. /// </summary> [DataMember()] public System.Decimal SalesYTD { get { return this._salesYTD; } set { this._salesYTD = value; this.OnSalesYTDPropertyChanged(value); this.OnPropertyChanged("SalesYTD", value); } } partial void OnSalesYTDPropertyChanged(System.Decimal newValue); private decimal? _territorySalesYTD; /// <summary> /// TerritorySalesYTD property. /// </summary> [DataMember()] public decimal? TerritorySalesYTD { get { return this._territorySalesYTD; } set { this._territorySalesYTD = value; this.OnTerritorySalesYTDPropertyChanged(value); this.OnPropertyChanged("TerritorySalesYTD", value); } } partial void OnTerritorySalesYTDPropertyChanged(decimal? newValue); partial void OnPropertyChanged(string propertyName, object newValue); // For internal use only: partial void OnAnIdentifierPropertyChanged(); } #endregion #region Subordinate class definition /// <summary> /// Subordinate datacontract class. /// </summary> [DataContract(Namespace = "urn:Sample.Contracts", IsReference = true), Serializable()] public partial class Subordinate : System.Object { /// <summary> /// Constructs a new Subordinate datacontract instance. /// </summary> public Subordinate() : base() { this.OnInstanceCreated(); } partial void OnInstanceCreated(); private System.Int32 _id; /// <summary> /// Id property. /// </summary> [DataMember()] public System.Int32 Id { get { return this._id; } set { this._id = value; this.OnAnIdentifierPropertyChanged(); this.OnIdPropertyChanged(value); this.OnPropertyChanged("Id", value); } } partial void OnIdPropertyChanged(System.Int32 newValue); private Contact _contact; /// <summary> /// Contact property. /// </summary> [DataMember()] public Contact Contact { get { return this._contact; } set { this._contact = value; this.OnContactPropertyChanged(value); this.OnPropertyChanged("Contact", value); } } partial void OnContactPropertyChanged(Contact newValue); private System.String _gender; /// <summary> /// Gender property. /// </summary> [DataMember()] public System.String Gender { get { return this._gender; } set { this._gender = value; this.OnGenderPropertyChanged(value); this.OnPropertyChanged("Gender", value); } } partial void OnGenderPropertyChanged(System.String newValue); private System.DateTime _birthDate; /// <summary> /// BirthDate property. /// </summary> [DataMember()] public System.DateTime BirthDate { get { return this._birthDate; } set { this._birthDate = value; this.OnBirthDatePropertyChanged(value); this.OnPropertyChanged("BirthDate", value); } } partial void OnBirthDatePropertyChanged(System.DateTime newValue); private System.DateTime _hireDate; /// <summary> /// HireDate property. /// </summary> [DataMember()] public System.DateTime HireDate { get { return this._hireDate; } set { this._hireDate = value; this.OnHireDatePropertyChanged(value); this.OnPropertyChanged("HireDate", value); } } partial void OnHireDatePropertyChanged(System.DateTime newValue); partial void OnPropertyChanged(string propertyName, object newValue); // For internal use only: partial void OnAnIdentifierPropertyChanged(); } #endregion }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace ActionableRestfulApiErrors.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Xml; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Globalization; namespace System.ServiceModel.Channels { public abstract class MessageFault { private static MessageFault s_defaultMessageFault; public static MessageFault CreateFault(FaultCode code, string reason) { return CreateFault(code, new FaultReason(reason)); } public static MessageFault CreateFault(FaultCode code, FaultReason reason) { return CreateFault(code, reason, null, null, "", ""); } public static MessageFault CreateFault(FaultCode code, FaultReason reason, object detail) { return CreateFault(code, reason, detail, DataContractSerializerDefaults.CreateSerializer( (detail == null ? typeof(object) : detail.GetType()), int.MaxValue/*maxItems*/), "", ""); } public static MessageFault CreateFault(FaultCode code, FaultReason reason, object detail, XmlObjectSerializer serializer) { return CreateFault(code, reason, detail, serializer, "", ""); } public static MessageFault CreateFault(FaultCode code, FaultReason reason, object detail, XmlObjectSerializer serializer, string actor) { if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); return CreateFault(code, reason, detail, serializer, actor, actor); } public static MessageFault CreateFault(FaultCode code, FaultReason reason, object detail, XmlObjectSerializer serializer, string actor, string node) { if (code == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("code")); if (reason == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reason")); if (actor == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("actor")); if (node == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("node")); return new XmlObjectSerializerFault(code, reason, detail, serializer, actor, node); } public static MessageFault CreateFault(Message message, int maxBufferSize) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message")); XmlDictionaryReader reader = message.GetReaderAtBodyContents(); using (reader) { try { EnvelopeVersion envelopeVersion = message.Version.Envelope; MessageFault fault; if (envelopeVersion == EnvelopeVersion.Soap12) { fault = ReceivedFault.CreateFault12(reader, maxBufferSize); } else if (envelopeVersion == EnvelopeVersion.Soap11) { fault = ReceivedFault.CreateFault11(reader, maxBufferSize); } else if (envelopeVersion == EnvelopeVersion.None) { fault = ReceivedFault.CreateFaultNone(reader, maxBufferSize); } else { throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.EnvelopeVersionUnknown, envelopeVersion.ToString())), message); } message.ReadFromBodyContentsToEnd(reader); return fault; } catch (InvalidOperationException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.SFxErrorDeserializingFault, e)); } catch (FormatException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.SFxErrorDeserializingFault, e)); } catch (XmlException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.SFxErrorDeserializingFault, e)); } } } internal static MessageFault Default { get { if (s_defaultMessageFault == null) { s_defaultMessageFault = MessageFault.CreateFault(new FaultCode("Default"), new FaultReason("", CultureInfo.CurrentCulture)); } return s_defaultMessageFault; } } public virtual string Actor { get { return ""; } } public abstract FaultCode Code { get; } public bool IsMustUnderstandFault { get { FaultCode code = this.Code; if (String.Compare(code.Name, MessageStrings.MustUnderstandFault, StringComparison.Ordinal) != 0) { return false; } if ((String.Compare(code.Namespace, EnvelopeVersion.Soap11.Namespace, StringComparison.Ordinal) != 0) && (String.Compare(code.Namespace, EnvelopeVersion.Soap12.Namespace, StringComparison.Ordinal) != 0)) { return false; } return true; } } public virtual string Node { get { return ""; } } public abstract bool HasDetail { get; } public abstract FaultReason Reason { get; } public T GetDetail<T>() { return GetDetail<T>(DataContractSerializerDefaults.CreateSerializer(typeof(T), int.MaxValue/*maxItems*/)); } public T GetDetail<T>(XmlObjectSerializer serializer) { if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); XmlDictionaryReader reader = GetReaderAtDetailContents(); T value = (T)serializer.ReadObject(reader); if (!reader.EOF) { reader.MoveToContent(); if (reader.NodeType != XmlNodeType.EndElement && !reader.EOF) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.ExtraContentIsPresentInFaultDetail)); } return value; } public XmlDictionaryReader GetReaderAtDetailContents() { if (!HasDetail) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FaultDoesNotHaveAnyDetail)); return OnGetReaderAtDetailContents(); } protected virtual void OnWriteDetail(XmlDictionaryWriter writer, EnvelopeVersion version) { OnWriteStartDetail(writer, version); OnWriteDetailContents(writer); writer.WriteEndElement(); } protected virtual void OnWriteStartDetail(XmlDictionaryWriter writer, EnvelopeVersion version) { if (version == EnvelopeVersion.Soap12) writer.WriteStartElement(XD.Message12Dictionary.FaultDetail, XD.Message12Dictionary.Namespace); else if (version == EnvelopeVersion.Soap11) writer.WriteStartElement(XD.Message11Dictionary.FaultDetail, XD.Message11Dictionary.FaultNamespace); else writer.WriteStartElement(XD.Message12Dictionary.FaultDetail, XD.MessageDictionary.Namespace); } protected abstract void OnWriteDetailContents(XmlDictionaryWriter writer); protected virtual XmlDictionaryReader OnGetReaderAtDetailContents() { XmlBuffer detailBuffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = detailBuffer.OpenSection(XmlDictionaryReaderQuotas.Max); OnWriteDetail(writer, EnvelopeVersion.Soap12); // Wrap in soap 1.2 by default detailBuffer.CloseSection(); detailBuffer.Close(); XmlDictionaryReader reader = detailBuffer.GetReader(0); reader.Read(); // Skip the detail element return reader; } public static bool WasHeaderNotUnderstood(MessageHeaders headers, string name, string ns) { if (headers == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("headers"); } for (int i = 0; i < headers.Count; i++) { MessageHeaderInfo headerInfo = headers[i]; if ((String.Compare(headerInfo.Name, Message12Strings.NotUnderstood, StringComparison.Ordinal) == 0) && (String.Compare(headerInfo.Namespace, Message12Strings.Namespace, StringComparison.Ordinal) == 0)) { using (XmlDictionaryReader reader = headers.GetReaderAtHeader(i)) { reader.MoveToAttribute(Message12Strings.QName, Message12Strings.Namespace); string actualName; string actualNamespace; reader.ReadContentAsQualifiedName(out actualName, out actualNamespace); if ((actualName != null) && (actualNamespace != null) && (String.Compare(name, actualName, StringComparison.Ordinal) == 0) && (String.Compare(ns, actualNamespace, StringComparison.Ordinal) == 0)) { return true; } } } } return false; } public void WriteTo(XmlWriter writer, EnvelopeVersion version) { WriteTo(XmlDictionaryWriter.CreateDictionaryWriter(writer), version); } public void WriteTo(XmlDictionaryWriter writer, EnvelopeVersion version) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (version == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version"); } if (version == EnvelopeVersion.Soap12) { WriteTo12(writer); } else if (version == EnvelopeVersion.Soap11) { WriteTo11(writer); } else if (version == EnvelopeVersion.None) { WriteToNone(writer); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.EnvelopeVersionUnknown, version.ToString()))); } } private void WriteToNone(XmlDictionaryWriter writer) { WriteTo12Driver(writer, EnvelopeVersion.None); } private void WriteTo12Driver(XmlDictionaryWriter writer, EnvelopeVersion version) { writer.WriteStartElement(XD.MessageDictionary.Fault, version.DictionaryNamespace); writer.WriteStartElement(XD.Message12Dictionary.FaultCode, version.DictionaryNamespace); WriteFaultCode12Driver(writer, Code, version); writer.WriteEndElement(); writer.WriteStartElement(XD.Message12Dictionary.FaultReason, version.DictionaryNamespace); FaultReason reason = Reason; for (int i = 0; i < reason.Translations.Count; i++) { FaultReasonText text = reason.Translations[i]; writer.WriteStartElement(XD.Message12Dictionary.FaultText, version.DictionaryNamespace); writer.WriteAttributeString("xml", "lang", XmlUtil.XmlNs, text.XmlLang); writer.WriteString(text.Text); writer.WriteEndElement(); } writer.WriteEndElement(); if (Node.Length > 0) writer.WriteElementString(XD.Message12Dictionary.FaultNode, version.DictionaryNamespace, Node); if (Actor.Length > 0) writer.WriteElementString(XD.Message12Dictionary.FaultRole, version.DictionaryNamespace, Actor); if (HasDetail) { OnWriteDetail(writer, version); } writer.WriteEndElement(); } private void WriteFaultCode12Driver(XmlDictionaryWriter writer, FaultCode faultCode, EnvelopeVersion version) { writer.WriteStartElement(XD.Message12Dictionary.FaultValue, version.DictionaryNamespace); string name; if (faultCode.IsSenderFault) name = version.SenderFaultName; else if (faultCode.IsReceiverFault) name = version.ReceiverFaultName; else name = faultCode.Name; string ns; if (faultCode.IsPredefinedFault) ns = version.Namespace; else ns = faultCode.Namespace; string prefix = writer.LookupPrefix(ns); if (prefix == null) writer.WriteAttributeString("xmlns", "a", XmlUtil.XmlNsNs, ns); writer.WriteQualifiedName(name, ns); writer.WriteEndElement(); if (faultCode.SubCode != null) { writer.WriteStartElement(XD.Message12Dictionary.FaultSubcode, version.DictionaryNamespace); WriteFaultCode12Driver(writer, faultCode.SubCode, version); writer.WriteEndElement(); } } private void WriteTo12(XmlDictionaryWriter writer) { WriteTo12Driver(writer, EnvelopeVersion.Soap12); } private void WriteTo11(XmlDictionaryWriter writer) { writer.WriteStartElement(XD.MessageDictionary.Fault, XD.Message11Dictionary.Namespace); writer.WriteStartElement(XD.Message11Dictionary.FaultCode, XD.Message11Dictionary.FaultNamespace); FaultCode faultCode = Code; if (faultCode.SubCode != null) faultCode = faultCode.SubCode; string name; if (faultCode.IsSenderFault) name = "Client"; else if (faultCode.IsReceiverFault) name = "Server"; else name = faultCode.Name; string ns; if (faultCode.IsPredefinedFault) ns = Message11Strings.Namespace; else ns = faultCode.Namespace; string prefix = writer.LookupPrefix(ns); if (prefix == null) writer.WriteAttributeString("xmlns", "a", XmlUtil.XmlNsNs, ns); writer.WriteQualifiedName(name, ns); writer.WriteEndElement(); FaultReasonText translation = Reason.Translations[0]; writer.WriteStartElement(XD.Message11Dictionary.FaultString, XD.Message11Dictionary.FaultNamespace); if (translation.XmlLang.Length > 0) writer.WriteAttributeString("xml", "lang", XmlUtil.XmlNs, translation.XmlLang); writer.WriteString(translation.Text); writer.WriteEndElement(); if (Actor.Length > 0) writer.WriteElementString(XD.Message11Dictionary.FaultActor, XD.Message11Dictionary.FaultNamespace, Actor); if (HasDetail) { OnWriteDetail(writer, EnvelopeVersion.Soap11); } writer.WriteEndElement(); } } internal class XmlObjectSerializerFault : MessageFault { private FaultCode _code; private FaultReason _reason; private string _actor; private string _node; private object _detail; private XmlObjectSerializer _serializer; public XmlObjectSerializerFault(FaultCode code, FaultReason reason, object detail, XmlObjectSerializer serializer, string actor, string node) { _code = code; _reason = reason; _detail = detail; _serializer = serializer; _actor = actor; _node = node; } public override string Actor { get { return _actor; } } public override FaultCode Code { get { return _code; } } public override bool HasDetail { get { return _serializer != null; } } public override string Node { get { return _node; } } public override FaultReason Reason { get { return _reason; } } private object ThisLock { get { return _code; } } protected override void OnWriteDetailContents(XmlDictionaryWriter writer) { if (_serializer != null) { lock (ThisLock) { _serializer.WriteObject(writer, _detail); } } } } internal class ReceivedFault : MessageFault { private FaultCode _code; private FaultReason _reason; private string _actor; private string _node; private XmlBuffer _detail; private bool _hasDetail; private EnvelopeVersion _receivedVersion; private ReceivedFault(FaultCode code, FaultReason reason, string actor, string node, XmlBuffer detail, EnvelopeVersion version) { _code = code; _reason = reason; _actor = actor; _node = node; _receivedVersion = version; _hasDetail = InferHasDetail(detail); _detail = _hasDetail ? detail : null; } public override string Actor { get { return _actor; } } public override FaultCode Code { get { return _code; } } public override bool HasDetail { get { return _hasDetail; } } public override string Node { get { return _node; } } public override FaultReason Reason { get { return _reason; } } private bool InferHasDetail(XmlBuffer detail) { bool hasDetail = false; if (detail != null) { XmlDictionaryReader reader = detail.GetReader(0); if (!reader.IsEmptyElement && reader.Read()) // check if the detail element contains data hasDetail = (reader.MoveToContent() != XmlNodeType.EndElement); reader.Dispose(); } return hasDetail; } protected override void OnWriteDetail(XmlDictionaryWriter writer, EnvelopeVersion version) { using (XmlReader r = _detail.GetReader(0)) { // Start the element base.OnWriteStartDetail(writer, version); // Copy the attributes while (r.MoveToNextAttribute()) { if (ShouldWriteDetailAttribute(version, r.Prefix, r.LocalName, r.Value)) { writer.WriteAttributeString(r.Prefix, r.LocalName, r.NamespaceURI, r.Value); } } r.MoveToElement(); r.Read(); // Copy the contents while (r.NodeType != XmlNodeType.EndElement) writer.WriteNode(r, false); // End the element writer.WriteEndElement(); } } protected override void OnWriteStartDetail(XmlDictionaryWriter writer, EnvelopeVersion version) { using (XmlReader r = _detail.GetReader(0)) { // Start the element base.OnWriteStartDetail(writer, version); // Copy the attributes while (r.MoveToNextAttribute()) { if (ShouldWriteDetailAttribute(version, r.Prefix, r.LocalName, r.Value)) { writer.WriteAttributeString(r.Prefix, r.LocalName, r.NamespaceURI, r.Value); } } } } protected override void OnWriteDetailContents(XmlDictionaryWriter writer) { using (XmlReader r = _detail.GetReader(0)) { r.Read(); while (r.NodeType != XmlNodeType.EndElement) writer.WriteNode(r, false); } } protected override XmlDictionaryReader OnGetReaderAtDetailContents() { XmlDictionaryReader reader = _detail.GetReader(0); reader.Read(); // Skip the detail element return reader; } private bool ShouldWriteDetailAttribute(EnvelopeVersion targetVersion, string prefix, string localName, string attributeValue) { // Handle fault detail version conversion from Soap12 to Soap11 -- scope tightly to only conversion from Soap12 -> Soap11 // SOAP 1.1 specifications allow an arbitrary element within <fault>, hence: // transform this IFF the SOAP namespace specified will affect the namespace of the <detail> element, // AND the namespace specified is exactly the Soap12 Namespace. bool shouldSkip = _receivedVersion == EnvelopeVersion.Soap12 // original incoming version && targetVersion == EnvelopeVersion.Soap11 // version to serialize to && string.IsNullOrEmpty(prefix) // attribute prefix && localName == "xmlns" // only transform namespace attributes, don't care about others && attributeValue == XD.Message12Dictionary.Namespace.Value; return !shouldSkip; } public static ReceivedFault CreateFaultNone(XmlDictionaryReader reader, int maxBufferSize) { return CreateFault12Driver(reader, maxBufferSize, EnvelopeVersion.None); } private static ReceivedFault CreateFault12Driver(XmlDictionaryReader reader, int maxBufferSize, EnvelopeVersion version) { reader.ReadStartElement(XD.MessageDictionary.Fault, version.DictionaryNamespace); reader.ReadStartElement(XD.Message12Dictionary.FaultCode, version.DictionaryNamespace); FaultCode code = ReadFaultCode12Driver(reader, version); reader.ReadEndElement(); List<FaultReasonText> translations = new List<FaultReasonText>(); if (reader.IsEmptyElement) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.AtLeastOneFaultReasonMustBeSpecified)); } else { reader.ReadStartElement(XD.Message12Dictionary.FaultReason, version.DictionaryNamespace); while (reader.IsStartElement(XD.Message12Dictionary.FaultText, version.DictionaryNamespace)) translations.Add(ReadTranslation12(reader)); reader.ReadEndElement(); } string actor = ""; string node = ""; if (reader.IsStartElement(XD.Message12Dictionary.FaultNode, version.DictionaryNamespace)) node = reader.ReadElementContentAsString(); if (reader.IsStartElement(XD.Message12Dictionary.FaultRole, version.DictionaryNamespace)) actor = reader.ReadElementContentAsString(); XmlBuffer detail = null; if (reader.IsStartElement(XD.Message12Dictionary.FaultDetail, version.DictionaryNamespace)) { detail = new XmlBuffer(maxBufferSize); XmlDictionaryWriter writer = detail.OpenSection(reader.Quotas); writer.WriteNode(reader, false); detail.CloseSection(); detail.Close(); } reader.ReadEndElement(); FaultReason reason = new FaultReason(translations); return new ReceivedFault(code, reason, actor, node, detail, version); } private static FaultCode ReadFaultCode12Driver(XmlDictionaryReader reader, EnvelopeVersion version) { string localName; string ns; FaultCode subCode = null; reader.ReadStartElement(XD.Message12Dictionary.FaultValue, version.DictionaryNamespace); XmlUtil.ReadContentAsQName(reader, out localName, out ns); reader.ReadEndElement(); if (reader.IsStartElement(XD.Message12Dictionary.FaultSubcode, version.DictionaryNamespace)) { reader.ReadStartElement(); subCode = ReadFaultCode12Driver(reader, version); reader.ReadEndElement(); return new FaultCode(localName, ns, subCode); } return new FaultCode(localName, ns); } public static ReceivedFault CreateFault12(XmlDictionaryReader reader, int maxBufferSize) { return CreateFault12Driver(reader, maxBufferSize, EnvelopeVersion.Soap12); } private static FaultReasonText ReadTranslation12(XmlDictionaryReader reader) { string xmlLang = XmlUtil.GetXmlLangAttribute(reader); string text = reader.ReadElementContentAsString(); return new FaultReasonText(text, xmlLang); } public static ReceivedFault CreateFault11(XmlDictionaryReader reader, int maxBufferSize) { reader.ReadStartElement(XD.MessageDictionary.Fault, XD.Message11Dictionary.Namespace); string ns; string name; reader.ReadStartElement(XD.Message11Dictionary.FaultCode, XD.Message11Dictionary.FaultNamespace); XmlUtil.ReadContentAsQName(reader, out name, out ns); FaultCode code = new FaultCode(name, ns); reader.ReadEndElement(); string xmlLang = reader.XmlLang; reader.MoveToContent(); // Don't do IsStartElement. FaultString is required, so let the reader throw. string text = reader.ReadElementContentAsString(XD.Message11Dictionary.FaultString.Value, XD.Message11Dictionary.FaultNamespace.Value); FaultReasonText translation = new FaultReasonText(text, xmlLang); string actor = ""; if (reader.IsStartElement(XD.Message11Dictionary.FaultActor, XD.Message11Dictionary.FaultNamespace)) actor = reader.ReadElementContentAsString(); XmlBuffer detail = null; if (reader.IsStartElement(XD.Message11Dictionary.FaultDetail, XD.Message11Dictionary.FaultNamespace)) { detail = new XmlBuffer(maxBufferSize); XmlDictionaryWriter writer = detail.OpenSection(reader.Quotas); writer.WriteNode(reader, false); detail.CloseSection(); detail.Close(); } reader.ReadEndElement(); FaultReason reason = new FaultReason(translation); return new ReceivedFault(code, reason, actor, actor, detail, EnvelopeVersion.Soap11); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.Composition; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Lean.Engine.Setup; using QuantConnect.Lean.Engine.TransactionHandlers; using QuantConnect.Orders; using QuantConnect.Packets; using QuantConnect.Statistics; namespace QuantConnect.Lean.Engine.Results { /// <summary> /// Handle the results of the backtest: where should we send the profit, portfolio updates: /// Backtester or the Live trading platform: /// </summary> [InheritedExport(typeof(IResultHandler))] public interface IResultHandler { /// <summary> /// Put messages to process into the queue so they are processed by this thread. /// </summary> ConcurrentQueue<Packet> Messages { get; set; } /// <summary> /// Charts collection for storing the master copy of user charting data. /// </summary> ConcurrentDictionary<string, Chart> Charts { get; set; } /// <summary> /// Sampling period for timespans between resamples of the charting equity. /// </summary> /// <remarks>Specifically critical for backtesting since with such long timeframes the sampled data can get extreme.</remarks> TimeSpan ResamplePeriod { get; } /// <summary> /// How frequently the backtests push messages to the browser. /// </summary> /// <remarks>Update frequency of notification packets</remarks> TimeSpan NotificationPeriod { get; } /// <summary> /// Boolean flag indicating the result hander thread is busy. /// False means it has completely finished and ready to dispose. /// </summary> bool IsActive { get; } /// <summary> /// Initialize the result handler with this result packet. /// </summary> /// <param name="job">Algorithm job packet for this result handler</param> /// <param name="messagingHandler"></param> /// <param name="api"></param> /// <param name="dataFeed"></param> /// <param name="setupHandler"></param> /// <param name="transactionHandler"></param> void Initialize(AlgorithmNodePacket job, IMessagingHandler messagingHandler, IApi api, IDataFeed dataFeed, ISetupHandler setupHandler, ITransactionHandler transactionHandler); /// <summary> /// Primary result thread entry point to process the result message queue and send it to whatever endpoint is set. /// </summary> void Run(); /// <summary> /// Process debug messages with the preconfigured settings. /// </summary> /// <param name="message">String debug message</param> void DebugMessage(string message); /// <summary> /// Send a list of security types to the browser /// </summary> /// <param name="types">Security types list inside algorithm</param> void SecurityType(List<SecurityType> types); /// <summary> /// Send a logging message to the log list for storage. /// </summary> /// <param name="message">Message we'd in the log.</param> void LogMessage(string message); /// <summary> /// Send an error message back to the browser highlighted in red with a stacktrace. /// </summary> /// <param name="error">Error message we'd like shown in console.</param> /// <param name="stacktrace">Stacktrace information string</param> void ErrorMessage(string error, string stacktrace = ""); /// <summary> /// Send a runtime error message back to the browser highlighted with in red /// </summary> /// <param name="message">Error message.</param> /// <param name="stacktrace">Stacktrace information string</param> void RuntimeError(string message, string stacktrace = ""); /// <summary> /// Add a sample to the chart specified by the chartName, and seriesName. /// </summary> /// <param name="chartName">String chart name to place the sample.</param> /// <param name="seriesName">Series name for the chart.</param> /// <param name="seriesType">Series type for the chart.</param> /// <param name="time">Time for the sample</param> /// <param name="value">Value for the chart sample.</param> /// <param name="unit">Unit for the sample chart</param> /// <param name="seriesIndex">Index of the series we're sampling</param> /// <remarks>Sample can be used to create new charts or sample equity - daily performance.</remarks> void Sample(string chartName, string seriesName, int seriesIndex, SeriesType seriesType, DateTime time, decimal value, string unit = "$"); /// <summary> /// Wrapper methond on sample to create the equity chart. /// </summary> /// <param name="time">Time of the sample.</param> /// <param name="value">Equity value at this moment in time.</param> /// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/> void SampleEquity(DateTime time, decimal value); /// <summary> /// Sample the current daily performance directly with a time-value pair. /// </summary> /// <param name="time">Current backtest date.</param> /// <param name="value">Current daily performance value.</param> /// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/> void SamplePerformance(DateTime time, decimal value); /// <summary> /// Sample the current benchmark performance directly with a time-value pair. /// </summary> /// <param name="time">Current backtest date.</param> /// <param name="value">Current benchmark value.</param> /// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/> void SampleBenchmark(DateTime time, decimal value); /// <summary> /// Sample the asset prices to generate plots. /// </summary> /// <param name="symbol">Symbol we're sampling.</param> /// <param name="time">Time of sample</param> /// <param name="value">Value of the asset price</param> /// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/> void SampleAssetPrices(Symbol symbol, DateTime time, decimal value); /// <summary> /// Add a range of samples from the users algorithms to the end of our current list. /// </summary> /// <param name="samples">Chart updates since the last request.</param> /// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/> void SampleRange(List<Chart> samples); /// <summary> /// Set the algorithm of the result handler after its been initialized. /// </summary> /// <param name="algorithm">Algorithm object matching IAlgorithm interface</param> void SetAlgorithm(IAlgorithm algorithm); /// <summary> /// Save the snapshot of the total results to storage. /// </summary> /// <param name="packet">Packet to store.</param> /// <param name="async">Store the packet asyncronously to speed up the thread.</param> /// <remarks>Async creates crashes in Mono 3.10 if the thread disappears before the upload is complete so it is disabled for now.</remarks> void StoreResult(Packet packet, bool async = false); /// <summary> /// Post the final result back to the controller worker if backtesting, or to console if local. /// </summary> /// <param name="job">Lean AlgorithmJob task</param> /// <param name="orders">Collection of orders from the algorithm</param> /// <param name="profitLoss">Collection of time-profit values for the algorithm</param> /// <param name="holdings">Current holdings state for the algorithm</param> /// <param name="statisticsResults">Statistics information for the algorithm (empty if not finished)</param> /// <param name="banner">Runtime statistics banner information</param> void SendFinalResult(AlgorithmNodePacket job, Dictionary<int, Order> orders, Dictionary<DateTime, decimal> profitLoss, Dictionary<string, Holding> holdings, StatisticsResults statisticsResults, Dictionary<string, string> banner); /// <summary> /// Send a algorithm status update to the user of the algorithms running state. /// </summary> /// <param name="status">Status enum of the algorithm.</param> /// <param name="message">Optional string message describing reason for status change.</param> void SendStatusUpdate(AlgorithmStatus status, string message = ""); /// <summary> /// Set the chart name: /// </summary> /// <param name="symbol">Symbol of the chart we want.</param> void SetChartSubscription(string symbol); /// <summary> /// Set a dynamic runtime statistic to show in the (live) algorithm header /// </summary> /// <param name="key">Runtime headline statistic name</param> /// <param name="value">Runtime headline statistic value</param> void RuntimeStatistic(string key, string value); /// <summary> /// Send a new order event. /// </summary> /// <param name="newEvent">Update, processing or cancellation of an order, update the IDE in live mode or ignore in backtesting.</param> void OrderEvent(OrderEvent newEvent); /// <summary> /// Terminate the result thread and apply any required exit proceedures. /// </summary> void Exit(); /// <summary> /// Purge/clear any outstanding messages in message queue. /// </summary> void PurgeQueue(); /// <summary> /// Process any synchronous events in here that are primarily triggered from the algorithm loop /// </summary> void ProcessSynchronousEvents(bool forceProcess = false); } }
/* The MIT License (MIT) Copyright (c) 2014 Microsoft Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Research.Naiad; using Microsoft.Research.Naiad.Input; using Microsoft.Research.Naiad.Dataflow; using Microsoft.Research.Naiad.Dataflow.PartitionBy; using Microsoft.Research.Naiad.Dataflow.StandardVertices; using Microsoft.Research.Naiad.Frameworks.Lindi; using Microsoft.Research.Naiad.Frameworks.GraphLINQ; namespace Algorithm3.Indices { public static class DenseKeyIndexExtensionMethods { /// <summary> /// Creates an index with a dense integer key. /// </summary> /// <typeparam name="TValue">The type of the values</typeparam> /// <typeparam name="TRecord">The type of the source records</typeparam> /// <param name="source">The source of records</param> /// <param name="controller">The controller</param> /// <param name="keySelector">A function from record to dense integer key</param> /// <param name="valueSelector">A function from record to value</param> /// <returns>An index of values keyed by a dense integer</returns> public static DenseKeyIndex<TValue, TRecord> ToDenseIndex<TValue, TRecord>(this InterGraphDataSink<TRecord> source, Controller controller, Func<TRecord, int> keySelector, Func<TRecord, TValue> valueSelector) where TValue : IComparable<TValue> { return new DenseKeyIndex<TValue, TRecord>(source, controller, keySelector, valueSelector); } } /// <summary> /// Builds PrefixExtenders based on dense integer keys. /// </summary> /// <typeparam name="TValue">Type of value to extend with.</typeparam> /// <typeparam name="TRecord">Type of record the builder is based on.</typeparam> public class DenseKeyIndex<TValue, TRecord> where TValue : IComparable<TValue> { private readonly InterGraphDataSink<Fragment> result; /// <summary> /// Constructs a PrefixExtender factory keyed on dense integers. /// </summary> /// <param name="relation">Source of data for the prefix extender.</param> /// <param name="controller">Controller from which computation can be rooted.</param> /// <param name="keySelector">Map from records to relatively dense integers.</param> /// <param name="valueSelector">Map from records to extending values.</param> public DenseKeyIndex(InterGraphDataSink<TRecord> relation, Controller controller, Func<TRecord, int> keySelector, Func<TRecord, TValue> valueSelector) { using (var computation = controller.NewComputation()) { var stream = computation.NewInput(relation.NewDataSource()) .Select(x => keySelector(x).PairWith(valueSelector(x))) .NewUnaryStage((i, s) => new FragmentBuilder(i, s), x => x.First, null, "IndexBuilder"); result = new InterGraphDataSink<Fragment>(stream); computation.Activate(); computation.Join(); } } /// <summary> /// Creates a dense integer keyed PrefixExtender. /// </summary> /// <typeparam name="TPrefix">Type of the prefix to extend</typeparam> /// <param name="computation">The computation </param> /// <param name="keySelector">Map from prefixes to relatively dense integers.</param> /// <returns>A PrefixExtender based on the supplied key selector and underlying index.</returns> public PrefixExtender<TPrefix, TValue> CreateExtender<TPrefix>(Func<TPrefix, int> keySelector) { return new Extender<TPrefix>(result, keySelector); } private class FragmentBuilder : UnaryVertex<Pair<int, TValue>, Fragment, Epoch> { Fragment Index = new Fragment(); public override void OnReceive(Message<Pair<int, TValue>, Epoch> message) { this.Index.AddRecords(message.payload, message.length); NotifyAt(message.time); } public override void OnNotify(Epoch time) { this.Output.GetBufferForTime(time).Send(this.Index.Build(this.Stage.Placement.Count)); } public FragmentBuilder(int index, Stage<Epoch> stage) : base(index, stage) { } } private class Fragment { private int[] Offsets = new int[] { }; private TValue[] Values; private int Parts; private List<Pair<int, TValue>> tempList = new List<Pair<int, TValue>>(); // private HashSet<Pair<int, TValue>> tempHash = new HashSet<Pair<int, TValue>>(); private TValue[] tempArray = new TValue[] { }; internal void AddRecords(Pair<int, TValue>[] records, int count) { for (int i = 0; i < count; i++) this.tempList.Add(records[i]); } internal Fragment Build(int parts) { this.Parts = parts; this.Offsets = new int[(this.tempList.Max(x => x.First) / this.Parts) + 2]; // determine the number of values associated with each key foreach (var pair in this.tempList) this.Offsets[pair.First / this.Parts] += 1; // determine offsets in the array of values for (int i = 1; i < this.Offsets.Length; i++) this.Offsets[i] += this.Offsets[i - 1]; // reset offsets for (int i = this.Offsets.Length - 1; i > 0; i--) this.Offsets[i] = this.Offsets[i - 1]; this.Offsets[0] = 0; // allocate and insert values at offsets this.Values = new TValue[tempList.Count]; foreach (var pair in this.tempList) this.Values[this.Offsets[pair.First / this.Parts]++] = pair.Second; // reset offsets for (int i = this.Offsets.Length - 1; i > 0; i--) this.Offsets[i] = this.Offsets[i - 1]; this.Offsets[0] = 0; // release temp storage this.tempList.Clear(); this.tempList = null; // reset offset cursors, sort associated values for (int i = 0; i < this.Offsets.Length - 1; i++) Array.Sort(this.Values, this.Offsets[i], this.Offsets[i + 1] - this.Offsets[i]); return this; } internal void Count<TPrefix>(TPrefix[] prefixes, int length, Func<TPrefix, int> keyFunc, VertexOutputBufferPerTime<ExtensionProposal<TPrefix>, Epoch> output, int identifier) { for (int i = 0; i < length; i++) { var localName = keyFunc(prefixes[i]) / this.Parts; if (localName < this.Offsets.Length - 1) output.Send(new ExtensionProposal<TPrefix>(identifier, prefixes[i], this.Offsets[localName + 1] - this.Offsets[localName])); } } internal void Improve<TPrefix>(ExtensionProposal<TPrefix>[] proposals, int length, Func<TPrefix, int> key, VertexOutputBufferPerTime<ExtensionProposal<TPrefix>, Epoch> output, int identifier) { for (int i = 0; i < length; i++) { var localName = key(proposals[i].Record) / this.Parts; if (localName < this.Offsets.Length - 1) { var count = this.Offsets[localName + 1] - this.Offsets[localName]; if (count < proposals[i].Count) output.Send(new ExtensionProposal<TPrefix>(identifier, proposals[i].Record, count)); else output.Send(proposals[i]); } } } internal void Extend<TPrefix>(TPrefix[] prefixes, int length, Func<TPrefix, int> keyFunc, VertexOutputBufferPerTime<Pair<TPrefix, TValue[]>, Epoch> output) { for (int i = 0; i < length; i++) { var localName = keyFunc(prefixes[i]) / this.Parts; if (localName < this.Offsets.Length - 1) { var result = new TValue[this.Offsets[localName + 1] - this.Offsets[localName]]; Array.Copy(this.Values, this.Offsets[localName], result, 0, result.Length); output.Send(prefixes[i].PairWith(result)); } } } internal void Validate<TPrefix>(Pair<TPrefix, TValue[]>[] extensions, int length, Func<TPrefix, int> keyFunc, VertexOutputBufferPerTime<Pair<TPrefix, TValue[]>, Epoch> output) { for (int i = 0; i < length; i++) { var localName = keyFunc(extensions[i].First) / this.Parts; if (localName < this.Offsets.Length - 1) { // reports number of intersections, written back in to the second array. var counter = IntersectSortedArrays(localName, extensions[i].Second); if (counter > 0) { if (counter == extensions[i].Second.Length) { output.Send(extensions[i]); } else { var resultArray = new TValue[counter]; Array.Copy(extensions[i].Second, resultArray, counter); output.Send(extensions[i].First.PairWith(resultArray)); } } } } } internal int IntersectSortedArrays(int localName, TValue[] array) { var cursor = this.Offsets[localName]; var extent = this.Offsets[localName + 1]; var counts = 0; var buffer = this.Values; for (int i = 0; i < array.Length; i++) { var value = array[i]; var comparison = buffer[cursor].CompareTo(value); if (comparison < 0) { cursor = AdvanceCursor(cursor, extent, value); if (cursor >= extent) return counts; comparison = buffer[cursor].CompareTo(value); } if (comparison == 0 && cursor < extent) { array[counts++] = value; cursor++; if (cursor >= extent) return counts; } } return counts; } #if false // returns the position of the first element at least as large as otherValue. // If no such element exists, returns extent. internal int AdvanceCursor(int cursor, int extent, TValue otherValue) { var values = this.Values; int step = 1; while (cursor + step < extent && values[cursor + step].CompareTo(otherValue) < 0) { cursor = cursor + step; step *= 2; } var limit = Math.Min(extent, cursor + step); // now we do binary search in [cursor, limit) while (cursor + 1 < limit) { var mid = (cursor + limit) / 2; var comparison = values[mid].CompareTo(otherValue); if (comparison == 0) return mid; else { if (comparison < 0) cursor = mid; else limit = mid; } } return limit; } #else // returns the position of the first element at least as large as otherValue. // If no such element exists, returns extent. internal int AdvanceCursor(int cursor, int extent, TValue otherValue) { var values = this.Values; int step = 1; while (cursor + step < extent && values[cursor + step].CompareTo(otherValue) < 0) { cursor = cursor + step; step *= 2; } step = step / 2; // either cursor + step is off the end of the array, or points at a value larger than otherValue while (step > 0) { if (cursor + step < extent) { var comparison = values[cursor + step].CompareTo(otherValue); if (comparison == 0) return cursor + step; if (comparison < 0) cursor = cursor + step; } step = step / 2; } return cursor + 1; } #endif } private class Extender<TPrefix> : PrefixExtender<TPrefix, TValue> { // private readonly Stream<Index, Epoch> Index; private readonly InterGraphDataSink<Fragment> Index; private readonly Func<TPrefix, int> keySelector; public Extender(InterGraphDataSink<Fragment> index, Func<TPrefix, int> tKey) { this.Index = index; this.keySelector = tKey; } private Stream<TOutput, Epoch> FragmentJoin<TInput, TOutput>(Stream<TInput, Epoch> stream, Func<TInput, int> keyFunc, Action<Fragment, TInput[], int, VertexOutputBufferPerTime<TOutput, Epoch>> action) { return stream.ForStage.Computation.NewInput(Index.NewDataSource()) .IndexJoin<Fragment, TInput, int, TOutput>(stream, keyFunc, action); } public Stream<ExtensionProposal<TPrefix>, Epoch> CountExtensions(Stream<TPrefix, Epoch> stream, int identifier) { return this.FragmentJoin<TPrefix, ExtensionProposal<TPrefix>>(stream, keySelector, (index, prefixes, length, output) => index.Count(prefixes, length, keySelector, output, identifier)); } public Stream<ExtensionProposal<TPrefix>, Epoch> ImproveExtensions(Stream<ExtensionProposal<TPrefix>, Epoch> stream, int identifier) { return this.FragmentJoin<ExtensionProposal<TPrefix>, ExtensionProposal<TPrefix>>(stream, proposal => keySelector(proposal.Record), (a, b, c, d) => a.Improve(b, c, keySelector, d, identifier)); } public Stream<Pair<TPrefix, TValue[]>, Epoch> ExtendPrefixes(Stream<ExtensionProposal<TPrefix>, Epoch> stream, int identifier) { return this.FragmentJoin<TPrefix, Pair<TPrefix, TValue[]>>(stream.Where(x => x.Index == identifier).Select(x => x.Record), keySelector, (a, b, c, d) => a.Extend(b, c, this.keySelector, d)); } public Stream<Pair<TPrefix, TValue[]>, Epoch> ValidateExtensions(Stream<Pair<TPrefix, TValue[]>, Epoch> stream) { return this.FragmentJoin<Pair<TPrefix, TValue[]>, Pair<TPrefix, TValue[]>>(stream, tuple => keySelector(tuple.First), (a, b, c, d) => a.Validate(b, c, this.keySelector, d)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Routing; using Cassette.HtmlTemplates; using Cassette.Scripts; using Cassette.Stylesheets; using Cassette.Views; namespace Cassette.Aspnet { class DiagnosticRequestHandler : IDiagnosticRequestHandler { readonly RequestContext requestContext; readonly BundleCollection bundles; readonly CassetteSettings settings; readonly IUrlGenerator urlGenerator; readonly IBundleCacheRebuilder bundleCacheRebuilder; public DiagnosticRequestHandler(RequestContext requestContext, BundleCollection bundles, CassetteSettings settings, IUrlGenerator urlGenerator, IBundleCacheRebuilder bundleCacheRebuilder) { this.requestContext = requestContext; this.bundles = bundles; this.settings = settings; this.urlGenerator = urlGenerator; this.bundleCacheRebuilder = bundleCacheRebuilder; } public void ProcessRequest() { var response = requestContext.HttpContext.Response; var request = requestContext.HttpContext.Request; if (!CanAccessHud(request)) { response.StatusCode = 404; return; } if (request.HttpMethod.Equals("post", StringComparison.OrdinalIgnoreCase)) { ProcessPost(); return; } Bundles.AddPageData("data", PageData()); Bundles.Reference("~/Cassette.Aspnet.Resources"); var html = Properties.Resources.hud; html = html.Replace("$scripts$", Bundles.RenderScripts().ToHtmlString()); response.ContentType = "text/html"; response.Write(html); } void ProcessPost() { if (requestContext.HttpContext.Request.Form["action"] == "rebuild-cache") { bundleCacheRebuilder.RebuildCache(); } } bool CanAccessHud(HttpRequestBase request) { return request.IsLocal || settings.AllowRemoteDiagnostics; } object PageData() { using (bundles.GetReadLock()) { var scripts = bundles.OfType<ScriptBundle>(); var stylesheets = bundles.OfType<StylesheetBundle>(); var htmlTemplates = bundles.OfType<HtmlTemplateBundle>(); var data = new { Scripts = scripts.Select(ScriptData), Stylesheets = stylesheets.Select(StylesheetData), HtmlTemplates = htmlTemplates.Select(HtmlTemplateData), StartupTrace = CassetteHttpModule.StartUpTrace, Cassette = new { Version = new AssemblyName(typeof(Bundle).Assembly.FullName).Version.ToString(), CacheDirectory = GetCacheDirectory(settings), SourceDirectory = GetSourceDirectory(settings), settings.IsHtmlRewritingEnabled, settings.IsDebuggingEnabled } }; return data; } } static string GetSourceDirectory(CassetteSettings settings) { if (settings.SourceDirectory == null) return "(none)"; return settings.SourceDirectory.FullPath + " (" + settings.SourceDirectory.GetType().FullName + ")"; } static string GetCacheDirectory(CassetteSettings settings) { if (settings.CacheDirectory == null) return "(none)"; return settings.CacheDirectory.FullPath + " (" + settings.CacheDirectory.GetType().FullName + ")"; } object HtmlTemplateData(HtmlTemplateBundle htmlTemplate) { return new { htmlTemplate.Path, Url = BundleUrl(htmlTemplate), Assets = AssetPaths(htmlTemplate), htmlTemplate.References, Size = BundleSize(htmlTemplate) }; } object StylesheetData(StylesheetBundle stylesheet) { return new { stylesheet.Path, Url = BundleUrl(stylesheet), stylesheet.Media, stylesheet.Condition, Assets = AssetPaths(stylesheet), stylesheet.References, Size = BundleSize(stylesheet) }; } object ScriptData(ScriptBundle script) { return new { script.Path, Url = BundleUrl(script), script.Condition, Assets = AssetPaths(script), script.References, Size = BundleSize(script) }; } string BundleUrl(Bundle bundle) { var external = bundle as IExternalBundle; if (external == null) { return urlGenerator.CreateBundleUrl(bundle); } else { return external.ExternalUrl; } } long BundleSize(Bundle bundle) { if (settings.IsDebuggingEnabled) { return -1; } if (bundle.Assets.Any()) { using (var s = bundle.OpenStream()) { return s.Length; } } return -1; } IEnumerable<AssetLink> AssetPaths(Bundle bundle) { var generateUrls = settings.IsDebuggingEnabled; var visitor = generateUrls ? new AssetLinkCreator(urlGenerator) : new AssetLinkCreator(); bundle.Accept(visitor); return visitor.AssetLinks; } public bool IsReusable { get { return false; } } class AssetLinkCreator : IBundleVisitor { readonly IUrlGenerator urlGenerator; readonly List<AssetLink> assetLinks = new List<AssetLink>(); string bundlePath; public AssetLinkCreator(IUrlGenerator urlGenerator) { this.urlGenerator = urlGenerator; } public AssetLinkCreator() { } public List<AssetLink> AssetLinks { get { return assetLinks; } } public void Visit(Bundle bundle) { bundlePath = bundle.Path; } public void Visit(IAsset asset) { var path = asset.Path; if (path.Length > bundlePath.Length && path.StartsWith(bundlePath, StringComparison.OrdinalIgnoreCase)) { path = path.Substring(bundlePath.Length + 1); } var url = urlGenerator != null ? urlGenerator.CreateAssetUrl(asset) : null; AssetLinks.Add(new AssetLink { Path = path, Url = url }); } } class AssetLink { public string Path { get; set; } public string Url { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Sockets; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { // Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary // to separately Dispose (or have a 'using' statement) for the handler. public class HttpClientHandlerTest { readonly ITestOutputHelper _output; private const string ExpectedContent = "Test contest"; private const string Username = "testuser"; private const string Password = "password"; private readonly NetworkCredential _credential = new NetworkCredential(Username, Password); public readonly static object[][] EchoServers = HttpTestServers.EchoServers; public readonly static object[][] VerifyUploadServers = HttpTestServers.VerifyUploadServers; public readonly static object[][] CompressedServers = HttpTestServers.CompressedServers; public readonly static object[][] HeaderValueAndUris = { new object[] { "X-CustomHeader", "x-value", HttpTestServers.RemoteEchoServer }, new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RemoteEchoServer }, new object[] { "X-CustomHeader", "x-value", HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1) }, new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1) }, }; public readonly static object[][] Http2Servers = HttpTestServers.Http2Servers; public readonly static object[][] RedirectStatusCodes = { new object[] { 300 }, new object[] { 301 }, new object[] { 302 }, new object[] { 303 }, new object[] { 307 } }; // Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3 // "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE" public readonly static IEnumerable<object[]> HttpMethods = GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1"); public readonly static IEnumerable<object[]> HttpMethodsThatAllowContent = GetMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "CUSTOM1"); public readonly static IEnumerable<object[]> HttpMethodsThatDontAllowContent = GetMethods("HEAD", "TRACE"); private static IEnumerable<object[]> GetMethods(params string[] methods) { foreach (string method in methods) { foreach (bool secure in new[] { true, false }) { yield return new object[] { method, secure }; } } } public HttpClientHandlerTest(ITestOutputHelper output) { _output = output; } [Fact] public void Ctor_ExpectedDefaultPropertyValues() { using (var handler = new HttpClientHandler()) { // Same as .NET Framework (Desktop). Assert.True(handler.AllowAutoRedirect); Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions); CookieContainer cookies = handler.CookieContainer; Assert.NotNull(cookies); Assert.Equal(0, cookies.Count); Assert.Null(handler.Credentials); Assert.Equal(50, handler.MaxAutomaticRedirections); Assert.False(handler.PreAuthenticate); Assert.Equal(null, handler.Proxy); Assert.True(handler.SupportsAutomaticDecompression); Assert.True(handler.SupportsProxy); Assert.True(handler.SupportsRedirectConfiguration); Assert.True(handler.UseCookies); Assert.False(handler.UseDefaultCredentials); Assert.True(handler.UseProxy); // Changes from .NET Framework (Desktop). Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression); Assert.Equal(0, handler.MaxRequestContentBufferSize); Assert.NotNull(handler.Properties); } } [Fact] public void MaxRequestContentBufferSize_Get_ReturnsZero() { using (var handler = new HttpClientHandler()) { Assert.Equal(0, handler.MaxRequestContentBufferSize); } } [Fact] public void MaxRequestContentBufferSize_Set_ThrowsPlatformNotSupportedException() { using (var handler = new HttpClientHandler()) { Assert.Throws<PlatformNotSupportedException>(() => handler.MaxRequestContentBufferSize = 1024); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy) { var handler = new HttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = false; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.NegotiateAuthUriForDefaultCreds(secure:false); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Fact] public void Properties_Get_CountIsZero() { var handler = new HttpClientHandler(); IDictionary<String, object> dict = handler.Properties; Assert.Same(dict, handler.Properties); Assert.Equal(0, dict.Count); } [Fact] public void Properties_AddItemToDictionary_ItemPresent() { var handler = new HttpClientHandler(); IDictionary<String, object> dict = handler.Properties; var item = new Object(); dict.Add("item", item); object value; Assert.True(dict.TryGetValue("item", out value)); Assert.Equal(item, value); } [Theory, MemberData(nameof(EchoServers))] public async Task SendAsync_SimpleGet_Success(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(remoteServer)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Theory] [MemberData(nameof(GetAsync_IPBasedUri_Success_MemberData))] public async Task GetAsync_IPBasedUri_Success(IPAddress address) { using (var client = new HttpClient()) { var options = new LoopbackServer.Options { Address = address }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options), client.GetAsync(url)); }, options); } } public static IEnumerable<object[]> GetAsync_IPBasedUri_Success_MemberData() { foreach (var addr in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback, LoopbackServer.GetIPv6LinkLocalAddress() }) { if (addr != null) { yield return new object[] { addr }; } } } [Fact] public async Task SendAsync_MultipleRequestsReusingSameClient_Success() { using (var client = new HttpClient()) { HttpResponseMessage response; for (int i = 0; i < 3; i++) { response = await client.GetAsync(HttpTestServers.RemoteEchoServer); Assert.Equal(HttpStatusCode.OK, response.StatusCode); response.Dispose(); } } } [Fact] public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success() { HttpResponseMessage response = null; using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer); } Assert.NotNull(response); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } [Fact] public async Task SendAsync_Cancel_CancellationTokenPropagates() { var cts = new CancellationTokenSource(); cts.Cancel(); using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, HttpTestServers.RemoteEchoServer); TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, cts.Token)); Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested"); Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested"); } } [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_DefaultAutomaticDecompression_ContentDecompressed(Uri server) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(server)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_DefaultAutomaticDecompression_HeadersRemoved(Uri server) { using (var client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found"); Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found"); } } [Fact] public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized() { using (var client = new HttpClient()) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode) { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:statusCode, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(statusCode, (int)response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode) { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:statusCode, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpTestServers.RemoteEchoServer, response.RequestMessage.RequestUri); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.SecureRemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpTestServers.SecureRemoteEchoServer, response.RequestMessage.RequestUri); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:true, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; Uri targetUri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:targetUri, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(targetUri, response.RequestMessage.RequestUri); } } } [ActiveIssue(8945, PlatformID.Windows)] [Theory] [InlineData(3, 2)] [InlineData(3, 3)] [InlineData(3, 4)] public async Task GetAsync_MaxAutomaticRedirectionsNServerHops_ThrowsIfTooMany(int maxHops, int hops) { using (var client = new HttpClient(new HttpClientHandler() { MaxAutomaticRedirections = maxHops })) { Task<HttpResponseMessage> t = client.GetAsync(HttpTestServers.RedirectUriForDestinationUri( secure: false, statusCode: 302, destinationUri: HttpTestServers.RemoteEchoServer, hops: hops)); if (hops <= maxHops) { using (HttpResponseMessage response = await t) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpTestServers.RemoteEchoServer, response.RequestMessage.RequestUri); } } else { await Assert.ThrowsAsync<HttpRequestException>(() => t); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectWithRelativeLocation() { using (var client = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = true })) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure: false, statusCode: 302, destinationUri: HttpTestServers.RemoteEchoServer, hops: 1, relative: true); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpTestServers.RemoteEchoServer, response.RequestMessage.RequestUri); } } } [Theory] [InlineData(200)] [InlineData(201)] [InlineData(400)] public async Task GetAsync_AllowAutoRedirectTrue_NonRedirectStatusCode_LocationHeader_NoRedirect(int statusCode) { using (var handler = new HttpClientHandler() { AllowAutoRedirect = true }) using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (origServer, origUrl) => { await LoopbackServer.CreateServerAsync(async (redirectServer, redirectUrl) => { Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl); Task redirectTask = LoopbackServer.ReadRequestAndSendResponseAsync(redirectServer); await LoopbackServer.ReadRequestAndSendResponseAsync(origServer, $"HTTP/1.1 {statusCode} OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Location: {redirectUrl}\r\n" + "\r\n"); using (HttpResponseMessage response = await getResponse) { Assert.Equal(statusCode, (int)response.StatusCode); Assert.Equal(origUrl, response.RequestMessage.RequestUri); Assert.False(redirectTask.IsCompleted, "Should not have redirected to Location"); } }); }); } } [Theory] [PlatformSpecific(PlatformID.AnyUnix)] [InlineData("#origFragment", "", "#origFragment", false)] [InlineData("#origFragment", "", "#origFragment", true)] [InlineData("", "#redirFragment", "#redirFragment", false)] [InlineData("", "#redirFragment", "#redirFragment", true)] [InlineData("#origFragment", "#redirFragment", "#redirFragment", false)] [InlineData("#origFragment", "#redirFragment", "#redirFragment", true)] public async Task GetAsync_AllowAutoRedirectTrue_RetainsOriginalFragmentIfAppropriate( string origFragment, string redirFragment, string expectedFragment, bool useRelativeRedirect) { using (var handler = new HttpClientHandler() { AllowAutoRedirect = true }) using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (origServer, origUrl) => { origUrl = new Uri(origUrl.ToString() + origFragment); Uri redirectUrl = useRelativeRedirect ? new Uri(origUrl.PathAndQuery + redirFragment, UriKind.Relative) : new Uri(origUrl.ToString() + redirFragment); Uri expectedUrl = new Uri(origUrl.ToString() + expectedFragment); Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl); Task firstRequest = LoopbackServer.ReadRequestAndSendResponseAsync(origServer, $"HTTP/1.1 302 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Location: {redirectUrl}\r\n" + "\r\n"); Assert.Equal(firstRequest, await Task.WhenAny(firstRequest, getResponse)); Task secondRequest = LoopbackServer.ReadRequestAndSendResponseAsync(origServer, $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "\r\n"); await TestHelper.WhenAllCompletedOrAnyFailed(secondRequest, getResponse); using (HttpResponseMessage response = await getResponse) { Assert.Equal(200, (int)response.StatusCode); Assert.Equal(expectedUrl, response.RequestMessage.RequestUri); } }); } } [Fact] public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri redirectUri = HttpTestServers.RedirectUriForCreds( secure:false, statusCode:302, userName:Username, password:Password); using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); Uri redirectUri = HttpTestServers.RedirectUriForCreds( secure:false, statusCode:statusCode, userName:Username, password:Password); _output.WriteLine(uri.AbsoluteUri); _output.WriteLine(redirectUri.AbsoluteUri); var credentialCache = new CredentialCache(); credentialCache.Add(uri, "Basic", _credential); var handler = new HttpClientHandler(); handler.Credentials = credentialCache; using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [Fact] public async Task GetAsync_DefaultCoookieContainer_NoCookieSent() { using (HttpClient client = new HttpClient()) { using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Cookie")); } } } [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue) { var handler = new HttpClientHandler(); var cookieContainer = new CookieContainer(); cookieContainer.Add(HttpTestServers.RemoteEchoServer, new Cookie(cookieName, cookieValue)); handler.CookieContainer = cookieContainer; using (var client = new HttpClient(handler)) { using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } } [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri(string cookieName, string cookieValue) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add( "X-SetCookie", string.Format("{0}={1};Path=/", cookieName, cookieValue)); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } } [Theory, MemberData(nameof(HeaderValueAndUris))] public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add(name, value); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value)); } } } private static KeyValuePair<string, string> GenerateCookie(string name, char repeat, int overallHeaderValueLength) { string emptyHeaderValue = $"{name}=; Path=/"; Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length); int valueCount = overallHeaderValueLength - emptyHeaderValue.Length; string value = new string(repeat, valueCount); return new KeyValuePair<string, string>(name, value); } public static object[][] CookieNameValues = { // WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values, // using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders // returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer. // Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the // iteration index, which would cause header values to be missed if not handled correctly. // // In particular, WinHttpQueryHeader behaves as follows for the following header value lengths: // * 0-127 chars: succeeds, index advances from 0 to 1. // * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1. // * 256+ chars: fails due to insufficient buffer, index stays at 0. // // The below overall header value lengths were chosen to exercise reading header values at these // edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers. new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257) }, new object[] { new KeyValuePair<string, string>( ".AspNetCore.Antiforgery.Xam7_OeLcN4", "CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM") } }; [Theory] [MemberData(nameof(CookieNameValues))] public async Task GetAsync_ResponseWithSetCookieHeaders_AllCookiesRead(KeyValuePair<string, string> cookie1) { var cookie2 = new KeyValuePair<string, string>(".AspNetCore.Session", "RAExEmXpoCbueP_QYM"); var cookie3 = new KeyValuePair<string, string>("name", "value"); await LoopbackServer.CreateServerAsync(async (server, url) => { using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponse = client.GetAsync(url); await LoopbackServer.ReadRequestAndSendResponseAsync(server, $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Set-Cookie: {cookie1.Key}={cookie1.Value}; Path=/\r\n" + $"Set-Cookie : {cookie2.Key}={cookie2.Value}; Path=/\r\n" + // space before colon to verify header is trimmed and recognized $"Set-Cookie: {cookie3.Key}={cookie3.Value}; Path=/\r\n" + "\r\n"); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); CookieCollection cookies = handler.CookieContainer.GetCookies(url); Assert.Equal(3, cookies.Count); Assert.Equal(cookie1.Value, cookies[cookie1.Key].Value); Assert.Equal(cookie2.Value, cookies[cookie2.Key].Value); Assert.Equal(cookie3.Value, cookies[cookie3.Key].Value); } } }); } [Fact] public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock() { using (var client = new HttpClient()) { const int NumGets = 5; Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets) select client.GetAsync(HttpTestServers.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead)).ToArray(); for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available { using (HttpResponseMessage response = await responseTasks[i]) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } } [Fact] public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, HttpTestServers.SecureRemoteEchoServer); using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Fact] public async Task SendAsync_ReadFromSlowStreamingServer_PartialDataReturned() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(reader.ReadLine())) ; await writer.WriteAsync( "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 16000\r\n" + "\r\n" + "less than 16000 bytes"); using (HttpResponseMessage response = await getResponse) { var buffer = new byte[8000]; using (Stream clientStream = await response.Content.ReadAsStreamAsync()) { int bytesRead = await clientStream.ReadAsync(buffer, 0, buffer.Length); _output.WriteLine($"Bytes read from stream: {bytesRead}"); Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length"); } } }); } }); } [Fact] public async Task Dispose_DisposingHandlerCancelsActiveOperationsWithoutResponses() { await LoopbackServer.CreateServerAsync(async (socket1, url1) => { await LoopbackServer.CreateServerAsync(async (socket2, url2) => { await LoopbackServer.CreateServerAsync(async (socket3, url3) => { var unblockServers = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously); // First server connects but doesn't send any response yet Task server1 = LoopbackServer.AcceptSocketAsync(socket1, async (s, stream, reader, writer) => { await unblockServers.Task; }); // Second server connects and sends some but not all headers Task server2 = LoopbackServer.AcceptSocketAsync(socket2, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; await writer.WriteAsync($"HTTP/1.1 200 OK\r\n"); await unblockServers.Task; }); // Third server connects and sends all headers and some but not all of the body Task server3 = LoopbackServer.AcceptSocketAsync(socket3, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 20\r\n\r\n"); await writer.WriteAsync("1234567890"); await unblockServers.Task; await writer.WriteAsync("1234567890"); s.Shutdown(SocketShutdown.Send); }); // Make three requests Task<HttpResponseMessage> get1, get2; HttpResponseMessage response3; using (var client = new HttpClient()) { get1 = client.GetAsync(url1, HttpCompletionOption.ResponseHeadersRead); get2 = client.GetAsync(url2, HttpCompletionOption.ResponseHeadersRead); response3 = await client.GetAsync(url3, HttpCompletionOption.ResponseHeadersRead); } // Requests 1 and 2 should be canceled as we haven't finished receiving their headers await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get1); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get2); // Request 3 should still be active, and we should be able to receive all of the data. unblockServers.SetResult(true); using (response3) { Assert.Equal("12345678901234567890", await response3.Content.ReadAsStringAsync()); } }); }); }); } #region Post Methods Tests [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer) { using (var client = new HttpClient()) { string data = "Test String"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); HttpResponseMessage response; using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Repeat call. content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer) { using (var client = new HttpClient()) { string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))] public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, HttpContent content, byte[] expectedData) { using (var client = new HttpClient()) { content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } private sealed class StreamContentWithSyncAsyncCopy : StreamContent { private readonly Stream _stream; private readonly bool _syncCopy; public StreamContentWithSyncAsyncCopy(Stream stream, bool syncCopy) : base(stream) { _stream = stream; _syncCopy = syncCopy; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { if (_syncCopy) { try { _stream.CopyTo(stream, 128); // arbitrary size likely to require multiple read/writes return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } } return base.SerializeToStreamAsync(stream, context); } } public static IEnumerable<object[]> VerifyUploadServersStreamsAndExpectedData { get { foreach (object[] serverArr in VerifyUploadServers) // target server foreach (bool syncCopy in new[] { true, false }) // force the content copy to happen via Read/Write or ReadAsync/WriteAsync { Uri server = (Uri)serverArr[0]; byte[] data = new byte[1234]; new Random(42).NextBytes(data); // A MemoryStream { var memStream = new MemoryStream(data, writable: false); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(memStream, syncCopy: syncCopy), data }; } // A multipart content that provides its own stream from CreateContentReadStreamAsync { var mc = new MultipartContent(); mc.Add(new ByteArrayContent(data)); var memStream = new MemoryStream(); mc.CopyToAsync(memStream).GetAwaiter().GetResult(); yield return new object[] { server, mc, memStream.ToArray() }; } // A stream that provides the data synchronously and has a known length { var wrappedMemStream = new MemoryStream(data, writable: false); var syncKnownLengthStream = new DelegateStream( canReadFunc: () => wrappedMemStream.CanRead, canSeekFunc: () => wrappedMemStream.CanSeek, lengthFunc: () => wrappedMemStream.Length, positionGetFunc: () => wrappedMemStream.Position, readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token)); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncKnownLengthStream, syncCopy: syncCopy), data }; } // A stream that provides the data synchronously and has an unknown length { int syncUnknownLengthStreamOffset = 0; var syncUnknownLengthStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readAsyncFunc: (buffer, offset, count, token) => { int bytesRemaining = data.Length - syncUnknownLengthStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, count); Array.Copy(data, syncUnknownLengthStreamOffset, buffer, offset, bytesToCopy); syncUnknownLengthStreamOffset += bytesToCopy; return Task.FromResult(bytesToCopy); }); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncUnknownLengthStream, syncCopy: syncCopy), data }; } // A stream that provides the data asynchronously { int asyncStreamOffset = 0, maxDataPerRead = 100; var asyncStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readAsyncFunc: async (buffer, offset, count, token) => { await Task.Delay(1).ConfigureAwait(false); int bytesRemaining = data.Length - asyncStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count)); Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy); asyncStreamOffset += bytesToCopy; return bytesToCopy; }); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(asyncStream, syncCopy: syncCopy), data }; } // Providing data from a FormUrlEncodedContent's stream { var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("key", "val") }); yield return new object[] { server, formContent, Encoding.GetEncoding("iso-8859-1").GetBytes("key=val") }; } } } } [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_NullContent(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.PostAsync(remoteServer, null)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer) { using (var client = new HttpClient()) { var content = new StringContent(string.Empty); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task PostAsync_Redirect_ResultingGetFormattedCorrectly(bool secure) { const string ContentString = "This is the content string."; var content = new StringContent(ContentString); Uri redirectUri = HttpTestServers.RedirectUriForDestinationUri( secure, 302, secure ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer, 1); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain(ContentString, responseContent); Assert.DoesNotContain("Content-Length", responseContent); } } [OuterLoop] // takes several seconds [Theory] [InlineData(302, false)] [InlineData(307, true)] public async Task PostAsync_Redirect_LargePayload(int statusCode, bool expectRedirectToPost) { using (var fs = new FileStream(Path.Combine(Path.GetTempPath(), Path.GetTempFileName()), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x1000, FileOptions.DeleteOnClose)) { string contentString = string.Join("", Enumerable.Repeat("Content", 100000)); byte[] contentBytes = Encoding.UTF32.GetBytes(contentString); fs.Write(contentBytes, 0, contentBytes.Length); fs.Flush(flushToDisk: true); fs.Position = 0; Uri redirectUri = HttpTestServers.RedirectUriForDestinationUri(false, statusCode, HttpTestServers.SecureRemoteEchoServer, 1); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, new StreamContent(fs))) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); if (expectRedirectToPost) { Assert.InRange(response.Content.Headers.ContentLength.GetValueOrDefault(), contentBytes.Length, int.MaxValue); } } } } [Fact] public async Task PostAsync_ResponseContentRead_RequestContentDisposedAfterResponseBuffered() { using (var client = new HttpClient()) { await LoopbackServer.CreateServerAsync(async (server, url) => { bool contentDisposed = false; Task<HttpResponseMessage> post = client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url) { Content = new DelegateContent { SerializeToStreamAsyncDelegate = (contentStream, contentTransport) => contentStream.WriteAsync(new byte[100], 0, 100), TryComputeLengthDelegate = () => Tuple.Create<bool, long>(true, 100), DisposeDelegate = _ => contentDisposed = true } }, HttpCompletionOption.ResponseContentRead); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { // Read headers from client while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; // Send back all headers and some but not all of the response await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 10\r\n\r\n"); await writer.WriteAsync("abcd"); // less than contentLength // The request content should not be disposed of until all of the response has been sent await Task.Delay(1); // a little time to let data propagate Assert.False(contentDisposed, "Expected request content not to be disposed"); // Send remaining response content await writer.WriteAsync("efghij"); s.Shutdown(SocketShutdown.Send); // The task should complete and the request content should be disposed using (HttpResponseMessage response = await post) { Assert.True(contentDisposed, "Expected request content to be disposed"); Assert.Equal("abcdefghij", await response.Content.ReadAsStringAsync()); } }); }); } } [Fact] public async Task PostAsync_ResponseHeadersRead_RequestContentDisposedAfterRequestFullySentAndResponseHeadersReceived() { using (var client = new HttpClient()) { await LoopbackServer.CreateServerAsync(async (server, url) => { var trigger = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); bool contentDisposed = false; Task<HttpResponseMessage> post = client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url) { Content = new DelegateContent { SerializeToStreamAsyncDelegate = async (contentStream, contentTransport) => { await contentStream.WriteAsync(new byte[50], 0, 50); await trigger.Task; await contentStream.WriteAsync(new byte[50], 0, 50); }, TryComputeLengthDelegate = () => Tuple.Create<bool, long>(true, 100), DisposeDelegate = _ => contentDisposed = true } }, HttpCompletionOption.ResponseHeadersRead); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { // Read headers from client while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; // Send back all headers and some but not all of the response await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 10\r\n\r\n"); await writer.WriteAsync("abcd"); // less than contentLength if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.False(contentDisposed, "Expected request content to not be disposed while request data still being sent"); } else // [ActiveIssue(9006, PlatformID.AnyUnix)] { await post; Assert.True(contentDisposed, "Current implementation will dispose of the request content once response headers arrive"); } // Allow request content to complete trigger.SetResult(true); // Send remaining response content await writer.WriteAsync("efghij"); s.Shutdown(SocketShutdown.Send); // The task should complete and the request content should be disposed using (HttpResponseMessage response = await post) { Assert.True(contentDisposed, "Expected request content to be disposed"); Assert.Equal("abcdefghij", await response.Content.ReadAsStringAsync()); } }); }); } } private sealed class DelegateContent : HttpContent { internal Func<Stream, TransportContext, Task> SerializeToStreamAsyncDelegate; internal Func<Tuple<bool, long>> TryComputeLengthDelegate; internal Action<bool> DisposeDelegate; protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { return SerializeToStreamAsyncDelegate != null ? SerializeToStreamAsyncDelegate(stream, context) : Task.CompletedTask; } protected override bool TryComputeLength(out long length) { if (TryComputeLengthDelegate != null) { var result = TryComputeLengthDelegate(); length = result.Item2; return result.Item1; } length = 0; return false; } protected override void Dispose(bool disposing) => DisposeDelegate?.Invoke(disposing); } [Theory] [InlineData(HttpStatusCode.MethodNotAllowed, "Custom description")] [InlineData(HttpStatusCode.MethodNotAllowed, "")] public async Task GetAsync_CallMethod_ExpectedStatusLine(HttpStatusCode statusCode, string reasonPhrase) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.StatusCodeUri( false, (int)statusCode, reasonPhrase))) { Assert.Equal(statusCode, response.StatusCode); Assert.Equal(reasonPhrase, response.ReasonPhrase); } } } [PlatformSpecific(PlatformID.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix [Fact] public async Task PostAsync_Post_ChannelBindingHasExpectedValue() { using (var client = new HttpClient()) { string expectedContent = "Test contest"; var content = new ChannelBindingAwareContent(expectedContent); using (HttpResponseMessage response = await client.PostAsync(HttpTestServers.SecureRemoteEchoServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); ChannelBinding channelBinding = content.ChannelBinding; Assert.NotNull(channelBinding); _output.WriteLine("Channel Binding: {0}", channelBinding); } } } #endregion #region Various HTTP Method Tests [Theory, MemberData(nameof(HttpMethods))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); } } } [Theory, MemberData(nameof(HttpMethodsThatAllowContent))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer); request.Content = new StringContent(ExpectedContent); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, ExpectedContent); } } } [Theory, MemberData(nameof(HttpMethodsThatDontAllowContent))] public async Task SendAsync_SendRequestUsingNoBodyMethodToEchoServerWithContent_NoBodySent( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer) { Content = new StringContent(ExpectedContent) }; using (HttpResponseMessage response = await client.SendAsync(request)) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && method == "TRACE") { // [ActiveIssue(9023, PlatformID.Windows)] Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } else { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); Assert.False(responseContent.Contains(ExpectedContent)); } } } } #endregion #region Version tests [Fact] public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request() { Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 0)); Assert.Equal(new Version(1, 0), receivedRequestVersion); } [Fact] public async Task SendAsync_RequestVersion11_ServerReceivesVersion11Request() { Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 1)); Assert.Equal(new Version(1, 1), receivedRequestVersion); } [Fact] public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request() { // The default value for HttpRequestMessage.Version is Version(1,1). // So, we need to set something different (0,0), to test the "unknown" version. Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(0,0)); Assert.Equal(new Version(1, 1), receivedRequestVersion); } [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported(Uri server) { // We don't currently have a good way to test whether HTTP/2 is supported without // using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses. var request = new HttpRequestMessage(HttpMethod.Get, server); request.Version = new Version(2, 0); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True( response.Version == new Version(2, 0) || response.Version == new Version(1, 1), "Response version " + response.Version); } } private async Task<Version> SendRequestAndGetRequestVersionAsync(Version requestVersion) { Version receivedRequestVersion = null; await LoopbackServer.CreateServerAsync(async (server, url) => { var request = new HttpRequestMessage(HttpMethod.Get, url); request.Version = requestVersion; using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.SendAsync(request); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { string statusLine = reader.ReadLine(); while (!string.IsNullOrEmpty(reader.ReadLine())) ; if (statusLine.Contains("/1.0")) { receivedRequestVersion = new Version(1, 0); } else if (statusLine.Contains("/1.1")) { receivedRequestVersion = new Version(1, 1); } else { Assert.True(false, "Invalid HTTP request version"); } await writer.WriteAsync( $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 0\r\n" + "\r\n"); s.Shutdown(SocketShutdown.Send); }); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } }); return receivedRequestVersion; } #endregion #region Proxy tests [Theory] [MemberData(nameof(CredentialsForProxy))] public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache) { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: creds != null && creds != CredentialCache.DefaultCredentials, expectCreds: true); Uri proxyUrl = new Uri($"http://localhost:{port}"); const string BasicAuth = "Basic"; if (wrapCredsInCache) { Assert.IsAssignableFrom<NetworkCredential>(creds); var cache = new CredentialCache(); cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds); creds = cache; } using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer); Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap(); Task.WaitAll(proxyTask, responseTask, responseStringTask); TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null); Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result); NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth); string expectedAuth = nc == null || nc == CredentialCache.DefaultCredentials ? null : string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" : $"{nc.Domain}\\{nc.UserName}:{nc.Password}"; Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue); } } [Theory] [MemberData(nameof(BypassedProxies))] public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy) { using (var client = new HttpClient(new HttpClientHandler() { Proxy = proxy })) using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } [Fact] public void Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode() { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: true, expectCreds: false); Uri proxyUrl = new Uri($"http://localhost:{port}"); using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer); Task.WaitAll(proxyTask, responseTask); Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode); } } private static IEnumerable<object[]> BypassedProxies() { yield return new object[] { null }; yield return new object[] { new PlatformNotSupportedWebProxy() }; yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) }; } private static IEnumerable<object[]> CredentialsForProxy() { yield return new object[] { null, false }; foreach (bool wrapCredsInCache in new[] { true, false }) { yield return new object[] { CredentialCache.DefaultCredentials, wrapCredsInCache }; yield return new object[] { new NetworkCredential("user:name", "password"), wrapCredsInCache }; yield return new object[] { new NetworkCredential("username", "password", "dom:\\ain"), wrapCredsInCache }; } } #endregion } }
using UnityEngine; [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public class SurfaceCreator : MonoBehaviour { [Range(1,200)] public int resolution = 10; public Vector3 offset; public Vector3 rotation; [Range(0f,1f)] public float strength = 1f; public bool damping; public float frequency = 1f; [Range(1, 8)] public int octaves = 1; [Range(1f, 4f)] public float lacunarity = 2f; [Range(0f, 1f)] public float persistence = 0.5f; [Range(1, 3)] public int dimensions = 3; public NoiseMethodType type; public Gradient coloring; public bool coloringForStrength; public bool analyticalDerivatives; public bool showNormals; // public bool showXTangents; // public bool showZTangents; // public bool showCrossProductNormals; private Vector3[] vertices; private Vector3[] normals; private Color[] colors; private int currentResolution; private Mesh mesh; private void OnEnable() { if(mesh == null) { mesh = new Mesh(); mesh.name = "Surface Mesh"; GetComponent<MeshFilter>().mesh = mesh; } Refresh(); } public void Refresh() { if(resolution != currentResolution) CreateGrid(); Quaternion q = Quaternion.Euler(rotation); Quaternion qInv = Quaternion.Inverse(q); Vector3 point00 = q * new Vector3(-0.5f,-0.5f) + offset; Vector3 point10 = q * new Vector3( 0.5f,-0.5f) + offset; Vector3 point01 = q * new Vector3(-0.5f, 0.5f) + offset; Vector3 point11 = q * new Vector3( 0.5f, 0.5f) + offset; // Vector3 point00 = transform.TransformPoint(new Vector3(-0.5f,-0.5f)); // Vector3 point10 = transform.TransformPoint(new Vector3( 0.5f,-0.5f)); // Vector3 point01 = transform.TransformPoint(new Vector3(-0.5f, 0.5f)); // Vector3 point11 = transform.TransformPoint(new Vector3( 0.5f, 0.5f)); NoiseMethod method = Noise.methods[(int)type][dimensions - 1]; float stepSize = 1f / resolution; float amplitude = damping ? strength / frequency : strength; for (int v=0,y=0; y<=resolution; y++) { Vector3 point0 = Vector3.Lerp(point00, point01, y * stepSize); Vector3 point1 = Vector3.Lerp(point10, point11, y * stepSize); for (int x=0; x<=resolution; x++,v++) { Vector3 point = Vector3.Lerp(point0, point1, x * stepSize); NoiseSample sample = Noise.Sum(method, point, frequency, octaves, lacunarity, persistence); sample = type == NoiseMethodType.Value ? (sample-0.5f) : (sample*0.5f); if(coloringForStrength) { colors[v] = coloring.Evaluate(sample.value+0.5f); sample *= amplitude; } else { sample *= amplitude; colors[v] = coloring.Evaluate(sample.value+0.5f); } // sample *= strength; vertices[v].y = sample.value; sample.derivative = qInv * sample.derivative; if(analyticalDerivatives) { normals[v] = new Vector3( -sample.derivative.x, 1f, -sample.derivative.y).normalized; } colors[v] = coloring.Evaluate(sample.value+0.5f); } } mesh.vertices = vertices; mesh.colors = colors; mesh.RecalculateNormals(); // normals = mesh.normals; if(!analyticalDerivatives) { CalculateNormals(); } mesh.normals = normals; } private void CreateGrid() { currentResolution = resolution; mesh.Clear(); vertices = new Vector3[(resolution+1)*(resolution+1)]; colors = new Color[vertices.Length]; normals = new Vector3[vertices.Length]; Vector2[] uv = new Vector2[vertices.Length]; float stepSize = 1f/resolution; for(int v=0, z=0; z<=resolution; z++) { for(int x=0; x<=resolution; x++, v++) { vertices[v] = new Vector3(x*stepSize - 0.5f, 0f, z*stepSize-0.5f); colors[v] = Color.black; normals[v] = Vector3.up; uv[v] = new Vector2(x*stepSize, z*stepSize); } } mesh.vertices = vertices; mesh.colors = colors; mesh.normals = normals; mesh.uv = uv; int[] triangles = new int[resolution*resolution*6]; for(int t=0,v=0,y=0; y<resolution; y++, v++) { for(int x=0; x<resolution; x++,v++,t+=6) { triangles[t] = v; triangles[t+1] = v+resolution+1; triangles[t+2] = v+1; triangles[t+3] = v+1; triangles[t+4] = v+resolution+1; triangles[t+5] = v+resolution+2; } } mesh.triangles = triangles; } private float GetXDerivative(int x, int z) { int rowOffset = z * (resolution+1); float left, right, scale; if(x>0) { left = vertices[rowOffset + x - 1].y; if(x<resolution) { right = vertices[rowOffset + x + 1].y; scale = 0.5f * resolution; } else { right = vertices[rowOffset + x].y; scale = resolution; } } else { left = vertices[rowOffset + x].y; right = vertices[rowOffset + x + 1].y; scale = resolution; } return (right - left) * scale; } private float GetZDerivative(int x, int z) { int rowLength = resolution + 1; float back, forward, scale; if(z>0) { back = vertices[(z-1) * rowLength+x].y; if(z<resolution) { forward = vertices[(z+1) * rowLength + x].y; scale = 0.5f * resolution; } else { forward = vertices[z * rowLength + x].y; scale = resolution; } } else { back = vertices[z * rowLength + x].y; forward = vertices[(z+1) * rowLength + x].y; scale = resolution; } return (forward - back) * scale; } private void CalculateNormals() { for(int v=0,z=0; z<=resolution; z++) { for(int x=0; x<=resolution; x++,v++) { normals[v] = new Vector3( (-1f*GetXDerivative(x,z)), 1f, (-1f*GetZDerivative(x,z))).normalized; } } // for(int v=0,z=0; z<=resolution; z++) // { // for(int x=0; x<=resolution; x++,v++) // { // if(showXTangents) // { // normals[v] = new Vector3(1f, GetXDerivative(x,z), 0f); // } // else if(showZTangents) // { // normals[v] = new Vector3(0f, GetZDerivative(x,z), 1f); // } // else if(showCrossProductNormals) // { // normals[v] = Vector3.Cross( // new Vector3(0f, GetZDerivative(x,z), 1f), // new Vector3(1f, GetXDerivative(x,z), 0f)); // } else { // normals[v] = Vector3.up * GetXDerivative(x,z); // } // } // } } private void OnDrawGizmosSelected() { float scale = 1f / resolution; if(showNormals && vertices != null) { Gizmos.color = Color.yellow; for(int v=0; v<vertices.Length; v++) { Gizmos.DrawRay(vertices[v], normals[v] * scale); } } } }
using System; using System.ComponentModel; using System.Drawing; #if __UNIFIED__ using UIKit; using Foundation; using ObjCRuntime; using PointF = CoreGraphics.CGPoint; using RectangleF = CoreGraphics.CGRect; #else using MonoTouch.Foundation; using MonoTouch.ObjCRuntime; using MonoTouch.UIKit; using nfloat=System.Single; #endif namespace Xamarin.Forms.Platform.iOS { public class ScrollViewRenderer : UIScrollView, IVisualElementRenderer { EventTracker _events; KeyboardInsetTracker _insetTracker; VisualElementPackager _packager; RectangleF _previousFrame; ScrollToRequestedEventArgs _requestedScroll; VisualElementTracker _tracker; public ScrollViewRenderer() : base(RectangleF.Empty) { ScrollAnimationEnded += HandleScrollAnimationEnded; Scrolled += HandleScrolled; } protected IScrollViewController Controller { get { return (IScrollViewController)Element; } } ScrollView ScrollView { get { return Element as ScrollView; } } public VisualElement Element { get; private set; } public event EventHandler<VisualElementChangedEventArgs> ElementChanged; public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint) { return NativeView.GetSizeRequest(widthConstraint, heightConstraint, 44, 44); } public UIView NativeView { get { return this; } } public void SetElement(VisualElement element) { _requestedScroll = null; var oldElement = Element; Element = element; if (oldElement != null) { oldElement.PropertyChanged -= HandlePropertyChanged; ((IScrollViewController)oldElement).ScrollToRequested -= OnScrollToRequested; } if (element != null) { element.PropertyChanged += HandlePropertyChanged; ((IScrollViewController)element).ScrollToRequested += OnScrollToRequested; if (_packager == null) { DelaysContentTouches = true; _packager = new VisualElementPackager(this); _packager.Load(); _tracker = new VisualElementTracker(this); _tracker.NativeControlUpdated += OnNativeControlUpdated; _events = new EventTracker(this); _events.LoadEvents(this); _insetTracker = new KeyboardInsetTracker(this, () => Window, insets => ContentInset = ScrollIndicatorInsets = insets, point => { var offset = ContentOffset; offset.Y += point.Y; SetContentOffset(offset, true); }); } UpdateContentSize(); UpdateBackgroundColor(); OnElementChanged(new VisualElementChangedEventArgs(oldElement, element)); if (element != null) element.SendViewInitialized(this); if (!string.IsNullOrEmpty(element.AutomationId)) AccessibilityIdentifier = element.AutomationId; } } public void SetElementSize(Size size) { Layout.LayoutChildIntoBoundingRegion(Element, new Rectangle(Element.X, Element.Y, size.Width, size.Height)); } public UIViewController ViewController { get { return null; } } public override void LayoutSubviews() { base.LayoutSubviews(); if (_requestedScroll != null && Superview != null) { var request = _requestedScroll; _requestedScroll = null; OnScrollToRequested(this, request); } if (_previousFrame != Frame) { _previousFrame = Frame; _insetTracker?.UpdateInsets(); } } protected override void Dispose(bool disposing) { if (disposing) { if (_packager == null) return; SetElement(null); _packager.Dispose(); _packager = null; _tracker.NativeControlUpdated -= OnNativeControlUpdated; _tracker.Dispose(); _tracker = null; _events.Dispose(); _events = null; _insetTracker.Dispose(); _insetTracker = null; ScrollAnimationEnded -= HandleScrollAnimationEnded; Scrolled -= HandleScrolled; } base.Dispose(disposing); } protected virtual void OnElementChanged(VisualElementChangedEventArgs e) { var changed = ElementChanged; if (changed != null) changed(this, e); } void HandlePropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == ScrollView.ContentSizeProperty.PropertyName) UpdateContentSize(); else if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName) UpdateBackgroundColor(); } void HandleScrollAnimationEnded(object sender, EventArgs e) { Controller.SendScrollFinished(); } void HandleScrolled(object sender, EventArgs e) { UpdateScrollPosition(); } void OnNativeControlUpdated(object sender, EventArgs eventArgs) { ContentSize = Bounds.Size; UpdateContentSize(); } void OnScrollToRequested(object sender, ScrollToRequestedEventArgs e) { if (Superview == null) { _requestedScroll = e; return; } if (e.Mode == ScrollToMode.Position) SetContentOffset(new PointF((nfloat)e.ScrollX, (nfloat)e.ScrollY), e.ShouldAnimate); else { var positionOnScroll = Controller.GetScrollPositionForElement(e.Element as VisualElement, e.Position); switch (ScrollView.Orientation) { case ScrollOrientation.Horizontal: SetContentOffset(new PointF((nfloat)positionOnScroll.X, ContentOffset.Y), e.ShouldAnimate); break; case ScrollOrientation.Vertical: SetContentOffset(new PointF(ContentOffset.X, (nfloat)positionOnScroll.Y), e.ShouldAnimate); break; case ScrollOrientation.Both: SetContentOffset(new PointF((nfloat)positionOnScroll.X, (nfloat)positionOnScroll.Y), e.ShouldAnimate); break; } } if (!e.ShouldAnimate) Controller.SendScrollFinished(); } void UpdateBackgroundColor() { BackgroundColor = Element.BackgroundColor.ToUIColor(Color.Transparent); } void UpdateContentSize() { var contentSize = ((ScrollView)Element).ContentSize.ToSizeF(); if (!contentSize.IsEmpty) ContentSize = contentSize; } void UpdateScrollPosition() { if (ScrollView != null) Controller.SetScrolledPosition(ContentOffset.X, ContentOffset.Y); } } }
/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class GetUsersSpectraS3Request : Ds3Request { private string _authId; public string AuthId { get { return _authId; } set { WithAuthId(value); } } private string _defaultDataPolicyId; public string DefaultDataPolicyId { get { return _defaultDataPolicyId; } set { WithDefaultDataPolicyId(value); } } private bool? _lastPage; public bool? LastPage { get { return _lastPage; } set { WithLastPage(value); } } private string _name; public string Name { get { return _name; } set { WithName(value); } } private int? _pageLength; public int? PageLength { get { return _pageLength; } set { WithPageLength(value); } } private int? _pageOffset; public int? PageOffset { get { return _pageOffset; } set { WithPageOffset(value); } } private string _pageStartMarker; public string PageStartMarker { get { return _pageStartMarker; } set { WithPageStartMarker(value); } } public GetUsersSpectraS3Request WithAuthId(string authId) { this._authId = authId; if (authId != null) { this.QueryParams.Add("auth_id", authId); } else { this.QueryParams.Remove("auth_id"); } return this; } public GetUsersSpectraS3Request WithDefaultDataPolicyId(Guid? defaultDataPolicyId) { this._defaultDataPolicyId = defaultDataPolicyId.ToString(); if (defaultDataPolicyId != null) { this.QueryParams.Add("default_data_policy_id", defaultDataPolicyId.ToString()); } else { this.QueryParams.Remove("default_data_policy_id"); } return this; } public GetUsersSpectraS3Request WithDefaultDataPolicyId(string defaultDataPolicyId) { this._defaultDataPolicyId = defaultDataPolicyId; if (defaultDataPolicyId != null) { this.QueryParams.Add("default_data_policy_id", defaultDataPolicyId); } else { this.QueryParams.Remove("default_data_policy_id"); } return this; } public GetUsersSpectraS3Request WithLastPage(bool? lastPage) { this._lastPage = lastPage; if (lastPage != null) { this.QueryParams.Add("last_page", lastPage.ToString()); } else { this.QueryParams.Remove("last_page"); } return this; } public GetUsersSpectraS3Request WithName(string name) { this._name = name; if (name != null) { this.QueryParams.Add("name", name); } else { this.QueryParams.Remove("name"); } return this; } public GetUsersSpectraS3Request WithPageLength(int? pageLength) { this._pageLength = pageLength; if (pageLength != null) { this.QueryParams.Add("page_length", pageLength.ToString()); } else { this.QueryParams.Remove("page_length"); } return this; } public GetUsersSpectraS3Request WithPageOffset(int? pageOffset) { this._pageOffset = pageOffset; if (pageOffset != null) { this.QueryParams.Add("page_offset", pageOffset.ToString()); } else { this.QueryParams.Remove("page_offset"); } return this; } public GetUsersSpectraS3Request WithPageStartMarker(Guid? pageStartMarker) { this._pageStartMarker = pageStartMarker.ToString(); if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker.ToString()); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetUsersSpectraS3Request WithPageStartMarker(string pageStartMarker) { this._pageStartMarker = pageStartMarker; if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetUsersSpectraS3Request() { } internal override HttpVerb Verb { get { return HttpVerb.GET; } } internal override string Path { get { return "/_rest_/user"; } } } }
//--------------------------------------------------------------------------- // // <copyright file="AutomationTestsCollection" company="Microsoft"> // (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Permissive License. // See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. // All other rights reserved. // </copyright> // // // Description: Definition of AutomationTestsCollection which is collection of all available // tests. // // History: // 09/18/2006 : Ondrej Lehecka, created // //--------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Reflection; using System.Windows.Forms; using WUILib=Microsoft.Test.UIAutomation.TestManager; namespace VisualUIAVerify.Features { /// <summary> /// this class is collection of all available automation tests /// </summary> class AutomationTestCollection { private const string WUITestLibratyAssemblyName = "WUIATestLibrary"; //we cache collection of all tests private static List<AutomationTest> _allTestsCache; #region Filter enumerator /// <summary> /// this class is used to enumerate thru the automation tests collection and returns all tests /// that fit into the filter /// </summary> class FilterEnumerator : IEnumerator<AutomationTest>, IEnumerable<AutomationTest> { //enumerator for all automation tests private IEnumerator<AutomationTest> _baseEnumerator; //filter to be applied private AutomationTestsFilter _filter; /// <summary> /// initializes new instance of filter enumerator /// </summary> public FilterEnumerator(IEnumerator<AutomationTest> baseEnumerator, AutomationTestsFilter filter) { this._baseEnumerator = baseEnumerator; this._filter = filter; } /// <summary> /// finds next item matching the filter /// </summary> private bool MoveToNextItemMatchingFilter() { while (this._baseEnumerator.MoveNext()) { if (this._filter.Fit(this._baseEnumerator.Current)) return true; } return false; } #region implementation of IEnumerator<AutomationTest> public AutomationTest Current { get { return this._baseEnumerator.Current; } } #endregion #region implementation of IDisposable public void Dispose() { this._baseEnumerator.Dispose(); } #endregion #region implementation of IEnumerator object System.Collections.IEnumerator.Current { get { return this._baseEnumerator.Current; } } public bool MoveNext() { return MoveToNextItemMatchingFilter(); } public void Reset() { this._baseEnumerator.Reset(); } #endregion #region IEnumerable<AutomationTest> Members public IEnumerator<AutomationTest> GetEnumerator() { return this; } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this; } #endregion } #endregion public static IEnumerable<AutomationTest> Filter(AutomationTestsFilter filter) { PrepareTestCollection(); return new FilterEnumerator(_allTestsCache.GetEnumerator(), filter); } public static void RefreshTests() { throw new NotImplementedException(); } /// <summary> /// this method creates the cache of all available automation tests. /// </summary> private static void PrepareTestCollection() { if (AutomationTestCollection._allTestsCache != null) return; //create the cache, expect 1500 tests AutomationTestCollection._allTestsCache = new List<AutomationTest>(1500); //this is unfortunately hard coded Assembly testAssembly = null; try { testAssembly = Assembly.Load(WUITestLibratyAssemblyName); } catch (Exception ex) { string message = "Cannon load assembly " + WUITestLibratyAssemblyName + " with automation tests.\n" + "There will be no tests to run!"; MessageBox.Show(message); Trace.Fail(message, ex.Message); } if(testAssembly != null) { Type[] mytypes = testAssembly.GetTypes(); //go thru all types in library foreach (Type type in mytypes) { //if the type has this field the assume this is the test class FieldInfo suite = type.GetField("TestSuite"); if (suite != null) { string TestSuite = suite.GetValue(null) as string; if (!string.IsNullOrEmpty(TestSuite)) { //go thru all methods and if it has TestCaseAttribute then it is test method foreach (MethodInfo method in type.GetMethods()) { foreach (Attribute attr in method.GetCustomAttributes(true)) { if (attr is WUILib.TestCaseAttribute) { WUILib.TestCaseAttribute test = (WUILib.TestCaseAttribute)attr; if(test.Status == WUILib.TestStatus.Works && (test.TestCaseType & WUILib.TestCaseType.Arguments) != WUILib.TestCaseType.Arguments) //TODO: sort items _allTestsCache.Add(new AutomationTest(test, method)); } } } } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Security; using System.Globalization; using System.Runtime; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; namespace System.Collections.Generic { [Serializable] [TypeDependencyAttribute("System.Collections.Generic.ObjectEqualityComparer`1")] public abstract class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T> { // To minimize generic instantiation overhead of creating the comparer per type, we keep the generic portion of the code as small // as possible and define most of the creation logic in a non-generic class. public static EqualityComparer<T> Default { get; } = (EqualityComparer<T>)ComparerHelpers.CreateDefaultEqualityComparer(typeof(T)); [Pure] public abstract bool Equals(T x, T y); [Pure] public abstract int GetHashCode(T obj); internal virtual int IndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { if (Equals(array[i], value)) return i; } return -1; } internal virtual int LastIndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex - count + 1; for (int i = startIndex; i >= endIndex; i--) { if (Equals(array[i], value)) return i; } return -1; } int IEqualityComparer.GetHashCode(object obj) { if (obj == null) return 0; if (obj is T) return GetHashCode((T)obj); ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison); return 0; } bool IEqualityComparer.Equals(object x, object y) { if (x == y) return true; if (x == null || y == null) return false; if ((x is T) && (y is T)) return Equals((T)x, (T)y); ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison); return false; } } // The methods in this class look identical to the inherited methods, but the calls // to Equal bind to IEquatable<T>.Equals(T) instead of Object.Equals(Object) [Serializable] internal class GenericEqualityComparer<T> : EqualityComparer<T> where T : IEquatable<T> { [Pure] public override bool Equals(T x, T y) { if (x != null) { if (y != null) return x.Equals(y); return false; } if (y != null) return false; return true; } [Pure] public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0; internal override int IndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex + count; if (value == null) { for (int i = startIndex; i < endIndex; i++) { if (array[i] == null) return i; } } else { for (int i = startIndex; i < endIndex; i++) { if (array[i] != null && array[i].Equals(value)) return i; } } return -1; } internal override int LastIndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex - count + 1; if (value == null) { for (int i = startIndex; i >= endIndex; i--) { if (array[i] == null) return i; } } else { for (int i = startIndex; i >= endIndex; i--) { if (array[i] != null && array[i].Equals(value)) return i; } } return -1; } // Equals method for the comparer itself. // If in the future this type is made sealed, change the is check to obj != null && GetType() == obj.GetType(). public override bool Equals(Object obj) => obj is GenericEqualityComparer<T>; // If in the future this type is made sealed, change typeof(...) to GetType(). public override int GetHashCode() => typeof(GenericEqualityComparer<T>).GetHashCode(); } [Serializable] internal sealed class NullableEqualityComparer<T> : EqualityComparer<T?> where T : struct, IEquatable<T> { [Pure] public override bool Equals(T? x, T? y) { if (x.HasValue) { if (y.HasValue) return x.value.Equals(y.value); return false; } if (y.HasValue) return false; return true; } [Pure] public override int GetHashCode(T? obj) => obj.GetHashCode(); internal override int IndexOf(T?[] array, T? value, int startIndex, int count) { int endIndex = startIndex + count; if (!value.HasValue) { for (int i = startIndex; i < endIndex; i++) { if (!array[i].HasValue) return i; } } else { for (int i = startIndex; i < endIndex; i++) { if (array[i].HasValue && array[i].value.Equals(value.value)) return i; } } return -1; } internal override int LastIndexOf(T?[] array, T? value, int startIndex, int count) { int endIndex = startIndex - count + 1; if (!value.HasValue) { for (int i = startIndex; i >= endIndex; i--) { if (!array[i].HasValue) return i; } } else { for (int i = startIndex; i >= endIndex; i--) { if (array[i].HasValue && array[i].value.Equals(value.value)) return i; } } return -1; } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } [Serializable] internal sealed class ObjectEqualityComparer<T> : EqualityComparer<T> { [Pure] public override bool Equals(T x, T y) { if (x != null) { if (y != null) return x.Equals(y); return false; } if (y != null) return false; return true; } [Pure] public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0; internal override int IndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex + count; if (value == null) { for (int i = startIndex; i < endIndex; i++) { if (array[i] == null) return i; } } else { for (int i = startIndex; i < endIndex; i++) { if (array[i] != null && array[i].Equals(value)) return i; } } return -1; } internal override int LastIndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex - count + 1; if (value == null) { for (int i = startIndex; i >= endIndex; i--) { if (array[i] == null) return i; } } else { for (int i = startIndex; i >= endIndex; i--) { if (array[i] != null && array[i].Equals(value)) return i; } } return -1; } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } // NonRandomizedStringEqualityComparer is the comparer used by default with the Dictionary<string,...> // As the randomized string hashing is turned on by default on coreclr, we need to keep the performance not affected // as much as possible in the main stream scenarios like Dictionary<string,> // We use NonRandomizedStringEqualityComparer as default comparer as it doesnt use the randomized string hashing which // keep the perofrmance not affected till we hit collision threshold and then we switch to the comparer which is using // randomized string hashing GenericEqualityComparer<string> [Serializable] internal class NonRandomizedStringEqualityComparer : GenericEqualityComparer<string> { private static IEqualityComparer<string> s_nonRandomizedComparer; internal static new IEqualityComparer<string> Default { get { if (s_nonRandomizedComparer == null) { s_nonRandomizedComparer = new NonRandomizedStringEqualityComparer(); } return s_nonRandomizedComparer; } } [Pure] public override int GetHashCode(string obj) { if (obj == null) return 0; return obj.GetLegacyNonRandomizedHashCode(); } } // Performance of IndexOf on byte array is very important for some scenarios. // We will call the C runtime function memchr, which is optimized. [Serializable] internal sealed class ByteEqualityComparer : EqualityComparer<byte> { [Pure] public override bool Equals(byte x, byte y) { return x == y; } [Pure] public override int GetHashCode(byte b) { return b.GetHashCode(); } internal unsafe override int IndexOf(byte[] array, byte value, int startIndex, int count) { if (array == null) throw new ArgumentNullException(nameof(array)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (count > array.Length - startIndex) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (count == 0) return -1; fixed (byte* pbytes = array) { return Buffer.IndexOfByte(pbytes, value, startIndex, count); } } internal override int LastIndexOf(byte[] array, byte value, int startIndex, int count) { int endIndex = startIndex - count + 1; for (int i = startIndex; i >= endIndex; i--) { if (array[i] == value) return i; } return -1; } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } [Serializable] internal class EnumEqualityComparer<T> : EqualityComparer<T> where T : struct { [Pure] public override bool Equals(T x, T y) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(x); int y_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(y); return x_final == y_final; } [Pure] public override int GetHashCode(T obj) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj); return x_final.GetHashCode(); } public EnumEqualityComparer() { } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); internal override int IndexOf(T[] array, T value, int startIndex, int count) { int toFind = JitHelpers.UnsafeEnumCast(value); int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { int current = JitHelpers.UnsafeEnumCast(array[i]); if (toFind == current) return i; } return -1; } internal override int LastIndexOf(T[] array, T value, int startIndex, int count) { int toFind = JitHelpers.UnsafeEnumCast(value); int endIndex = startIndex - count + 1; for (int i = startIndex; i >= endIndex; i--) { int current = JitHelpers.UnsafeEnumCast(array[i]); if (toFind == current) return i; } return -1; } } [Serializable] internal sealed class SByteEnumEqualityComparer<T> : EnumEqualityComparer<T> where T : struct { public SByteEnumEqualityComparer() { } [Pure] public override int GetHashCode(T obj) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj); return ((sbyte)x_final).GetHashCode(); } } [Serializable] internal sealed class ShortEnumEqualityComparer<T> : EnumEqualityComparer<T> where T : struct { public ShortEnumEqualityComparer() { } [Pure] public override int GetHashCode(T obj) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj); return ((short)x_final).GetHashCode(); } } [Serializable] internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T> where T : struct { [Pure] public override bool Equals(T x, T y) { long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(x); long y_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(y); return x_final == y_final; } [Pure] public override int GetHashCode(T obj) { long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(obj); return x_final.GetHashCode(); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); public LongEnumEqualityComparer() { } internal override int IndexOf(T[] array, T value, int startIndex, int count) { long toFind = JitHelpers.UnsafeEnumCastLong(value); int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { long current = JitHelpers.UnsafeEnumCastLong(array[i]); if (toFind == current) return i; } return -1; } internal override int LastIndexOf(T[] array, T value, int startIndex, int count) { long toFind = JitHelpers.UnsafeEnumCastLong(value); int endIndex = startIndex - count + 1; for (int i = startIndex; i >= endIndex; i--) { long current = JitHelpers.UnsafeEnumCastLong(array[i]); if (toFind == current) return i; } return -1; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace AutoMapper.Configuration { using static Expression; public class MemberConfigurationExpression<TSource, TDestination, TMember> : IMemberConfigurationExpression<TSource, TDestination, TMember>, IPropertyMapConfiguration { private readonly MemberInfo _destinationMember; private LambdaExpression _sourceMember; private readonly Type _sourceType; protected List<Action<PropertyMap>> PropertyMapActions { get; } = new List<Action<PropertyMap>>(); public MemberConfigurationExpression(MemberInfo destinationMember, Type sourceType) { _destinationMember = destinationMember; _sourceType = sourceType; } public MemberInfo DestinationMember => _destinationMember; public void MapAtRuntime() { PropertyMapActions.Add(pm => pm.Inline = false); } public void NullSubstitute(object nullSubstitute) { PropertyMapActions.Add(pm => pm.NullSubstitute = nullSubstitute); } public void ResolveUsing<TValueResolver>() where TValueResolver : IValueResolver<TSource, TDestination, TMember> { var config = new ValueResolverConfiguration(typeof(TValueResolver), typeof(IValueResolver<TSource, TDestination, TMember>)); PropertyMapActions.Add(pm => pm.ValueResolverConfig = config); } public void ResolveUsing<TValueResolver, TSourceMember>(Expression<Func<TSource, TSourceMember>> sourceMember) where TValueResolver : IMemberValueResolver<TSource, TDestination, TSourceMember, TMember> { var config = new ValueResolverConfiguration(typeof(TValueResolver), typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>)) { SourceMember = sourceMember }; PropertyMapActions.Add(pm => pm.ValueResolverConfig = config); } public void ResolveUsing<TValueResolver, TSourceMember>(string sourceMemberName) where TValueResolver : IMemberValueResolver<TSource, TDestination, TSourceMember, TMember> { var config = new ValueResolverConfiguration(typeof(TValueResolver), typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>)) { SourceMemberName = sourceMemberName }; PropertyMapActions.Add(pm => pm.ValueResolverConfig = config); } public void ResolveUsing(IValueResolver<TSource, TDestination, TMember> valueResolver) { var config = new ValueResolverConfiguration(valueResolver, typeof(IValueResolver<TSource, TDestination, TMember>)); PropertyMapActions.Add(pm => pm.ValueResolverConfig = config); } public void ResolveUsing<TSourceMember>(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember> valueResolver, Expression<Func<TSource, TSourceMember>> sourceMember) { var config = new ValueResolverConfiguration(valueResolver, typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>)) { SourceMember = sourceMember }; PropertyMapActions.Add(pm => pm.ValueResolverConfig = config); } public void ResolveUsing<TResult>(Func<TSource, TResult> resolver) { PropertyMapActions.Add(pm => { Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => resolver(src); pm.CustomResolver = expr; }); } public void ResolveUsing<TResult>(Func<TSource, TDestination, TResult> resolver) { PropertyMapActions.Add(pm => { Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => resolver(src, dest); pm.CustomResolver = expr; }); } public void ResolveUsing<TResult>(Func<TSource, TDestination, TMember, TResult> resolver) { PropertyMapActions.Add(pm => { Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => resolver(src, dest, destMember); pm.CustomResolver = expr; }); } public void ResolveUsing<TResult>(Func<TSource, TDestination, TMember, ResolutionContext, TResult> resolver) { PropertyMapActions.Add(pm => { Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => resolver(src, dest, destMember, ctxt); pm.CustomResolver = expr; }); } public void MapFrom<TSourceMember>(Expression<Func<TSource, TSourceMember>> sourceMember) { MapFromUntyped(sourceMember); } internal void MapFromUntyped(LambdaExpression sourceExpression) { _sourceMember = sourceExpression; PropertyMapActions.Add(pm => pm.MapFrom(sourceExpression)); } public void MapFrom(string sourceMember) { _sourceType.GetFieldOrProperty(sourceMember); PropertyMapActions.Add(pm => pm.CustomSourceMemberName = sourceMember); } public void UseValue<TValue>(TValue value) { MapFrom(s => value); } public void Condition(Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool> condition) { PropertyMapActions.Add(pm => { Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr = (src, dest, srcMember, destMember, ctxt) => condition(src, dest, srcMember, destMember, ctxt); pm.Condition = expr; }); } public void Condition(Func<TSource, TDestination, TMember, TMember, bool> condition) { PropertyMapActions.Add(pm => { Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr = (src, dest, srcMember, destMember, ctxt) => condition(src, dest, srcMember, destMember); pm.Condition = expr; }); } public void Condition(Func<TSource, TDestination, TMember, bool> condition) { PropertyMapActions.Add(pm => { Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr = (src, dest, srcMember, destMember, ctxt) => condition(src, dest, srcMember); pm.Condition = expr; }); } public void Condition(Func<TSource, TDestination, bool> condition) { PropertyMapActions.Add(pm => { Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr = (src, dest, srcMember, destMember, ctxt) => condition(src, dest); pm.Condition = expr; }); } public void Condition(Func<TSource, bool> condition) { PropertyMapActions.Add(pm => { Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr = (src, dest, srcMember, destMember, ctxt) => condition(src); pm.Condition = expr; }); } public void PreCondition(Func<TSource, bool> condition) { PropertyMapActions.Add(pm => { Expression<Func<TSource, ResolutionContext, bool>> expr = (src, ctxt) => condition(src); pm.PreCondition = expr; }); } public void PreCondition(Func<ResolutionContext, bool> condition) { PropertyMapActions.Add(pm => { Expression<Func<TSource, ResolutionContext, bool>> expr = (src, ctxt) => condition(ctxt); pm.PreCondition = expr; }); } public void PreCondition(Func<TSource, ResolutionContext, bool> condition) { PropertyMapActions.Add(pm => { Expression<Func<TSource, ResolutionContext, bool>> expr = (src, ctxt) => condition(src, ctxt); pm.PreCondition = expr; }); } public void ExplicitExpansion() { PropertyMapActions.Add(pm => pm.ExplicitExpansion = true); } public void Ignore() => Ignore(ignorePaths: true); internal void Ignore(bool ignorePaths) => PropertyMapActions.Add(pm => { pm.Ignored = true; if(ignorePaths) { pm.TypeMap.IgnorePaths(DestinationMember); } }); public void AllowNull() { PropertyMapActions.Add(pm => pm.AllowNull = true); } public void UseDestinationValue() { PropertyMapActions.Add(pm => pm.UseDestinationValue = true); } public void SetMappingOrder(int mappingOrder) { PropertyMapActions.Add(pm => pm.MappingOrder = mappingOrder); } public void Configure(TypeMap typeMap) { var destMember = _destinationMember; if(destMember.DeclaringType.IsGenericType()) { destMember = typeMap.DestinationTypeDetails.PublicReadAccessors.Single(m => m.Name == destMember.Name); } var propertyMap = typeMap.FindOrCreatePropertyMapFor(destMember); Apply(propertyMap); } private void Apply(PropertyMap propertyMap) { foreach(var action in PropertyMapActions) { action(propertyMap); } } public IPropertyMapConfiguration Reverse() { var newSource = Parameter(DestinationMember.DeclaringType, "source"); var newSourceProperty = MakeMemberAccess(newSource, _destinationMember); var newSourceExpression = Lambda(newSourceProperty, newSource); return PathConfigurationExpression<TDestination, TSource>.Create(_sourceMember, newSourceExpression); } } }
// 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.ComponentModel.DataAnnotations { public class RangeAttributeTests { private static readonly ValidationContext s_testValidationContext = new ValidationContext(new object()); [Fact] public static void Can_construct_and_get_minimum_and_maximum_for_int_constructor() { var attribute = new RangeAttribute(1, 3); Assert.Equal(1, attribute.Minimum); Assert.Equal(3, attribute.Maximum); Assert.Equal(typeof(int), attribute.OperandType); } [Fact] public static void Can_construct_and_get_minimum_and_maximum_for_double_constructor() { var attribute = new RangeAttribute(1.0, 3.0); Assert.Equal(1.0, attribute.Minimum); Assert.Equal(3.0, attribute.Maximum); Assert.Equal(typeof(double), attribute.OperandType); } [Fact] public static void Can_construct_and_get_minimum_and_maximum_for_type_with_strings_constructor() { var attribute = new RangeAttribute(null, "SomeMinimum", "SomeMaximum"); Assert.Equal("SomeMinimum", attribute.Minimum); Assert.Equal("SomeMaximum", attribute.Maximum); Assert.Equal(null, attribute.OperandType); } [Fact] public static void Can_validate_valid_values_for_int_constructor() { var attribute = new RangeAttribute(1, 3); AssertEx.DoesNotThrow(() => attribute.Validate(null, s_testValidationContext)); // null is valid AssertEx.DoesNotThrow(() => attribute.Validate(string.Empty, s_testValidationContext)); // empty string is valid AssertEx.DoesNotThrow(() => attribute.Validate(1, s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate(2, s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate(3, s_testValidationContext)); } [Fact] public static void Can_validate_invalid_values_for_int_constructor() { var attribute = new RangeAttribute(1, 3); Assert.Throws<ValidationException>(() => attribute.Validate(0, s_testValidationContext)); Assert.Throws<ValidationException>(() => attribute.Validate(4, s_testValidationContext)); } [Fact] public static void Can_validate_valid_values_for_double_constructor() { var attribute = new RangeAttribute(1.0, 3.0); AssertEx.DoesNotThrow(() => attribute.Validate(null, s_testValidationContext)); // null is valid AssertEx.DoesNotThrow(() => attribute.Validate(string.Empty, s_testValidationContext)); // empty string is valid AssertEx.DoesNotThrow(() => attribute.Validate(1.0, s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate(2.0, s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate(3.0, s_testValidationContext)); } [Fact] public static void Can_validate_invalid_values_for_double_constructor() { var attribute = new RangeAttribute(1.0, 3.0); Assert.Throws<ValidationException>(() => attribute.Validate(0.9999999, s_testValidationContext)); Assert.Throws<ValidationException>(() => attribute.Validate(3.0000001, s_testValidationContext)); } [Fact] public static void Can_validate_valid_values_for_integers_using_type_and_strings_constructor() { var attribute = new RangeAttribute(typeof(int), "1", "3"); AssertEx.DoesNotThrow(() => attribute.Validate(null, s_testValidationContext)); // null is valid AssertEx.DoesNotThrow(() => attribute.Validate(string.Empty, s_testValidationContext)); // empty string is valid AssertEx.DoesNotThrow(() => attribute.Validate(1, s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate("1", s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate(2, s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate("2", s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate(3, s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate("3", s_testValidationContext)); } [Fact] public static void Can_validate_invalid_values_for_integers_using_type_and_strings_constructor() { var attribute = new RangeAttribute(typeof(int), "1", "3"); Assert.Throws<ValidationException>(() => attribute.Validate(0, s_testValidationContext)); Assert.Throws<ValidationException>(() => attribute.Validate("0", s_testValidationContext)); Assert.Throws<ValidationException>(() => attribute.Validate(4, s_testValidationContext)); Assert.Throws<ValidationException>(() => attribute.Validate("4", s_testValidationContext)); } [Fact] public static void Can_validate_valid_values_for_doubles_using_type_and_strings_constructor() { var attribute = new RangeAttribute(typeof(double), (1.0).ToString("F1"), (3.0).ToString("F1")); AssertEx.DoesNotThrow(() => attribute.Validate(null, s_testValidationContext)); // null is valid AssertEx.DoesNotThrow(() => attribute.Validate(string.Empty, s_testValidationContext)); // empty string is valid AssertEx.DoesNotThrow(() => attribute.Validate(1.0, s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate((1.0).ToString("F1"), s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate(2.0, s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate((2.0).ToString("F1"), s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate(3.0, s_testValidationContext)); AssertEx.DoesNotThrow(() => attribute.Validate((3.0).ToString("F1"), s_testValidationContext)); } [Fact] public static void Can_validate_invalid_values_for_doubles_using_type_and_strings_constructor() { var attribute = new RangeAttribute(typeof(double), (1.0).ToString("F1"), (3.0).ToString("F1")); Assert.Throws<ValidationException>(() => attribute.Validate(0.9999999, s_testValidationContext)); Assert.Throws<ValidationException>(() => attribute.Validate((0.9999999).ToString(), s_testValidationContext)); Assert.Throws<ValidationException>(() => attribute.Validate(3.0000001, s_testValidationContext)); Assert.Throws<ValidationException>(() => attribute.Validate((3.0000001).ToString(), s_testValidationContext)); } [Fact] public static void Validation_throws_InvalidOperationException_for_null_OperandType() { var attribute = new RangeAttribute(null, "someMinimum", "someMaximum"); Assert.Null(attribute.OperandType); Assert.Throws<InvalidOperationException>( () => attribute.Validate("Does not matter - OperandType is null", s_testValidationContext)); } [Fact] public static void Validation_throws_InvalidOperationException_for_OperandType_which_is_not_assignable_from_IComparable() { var attribute = new RangeAttribute(typeof(InvalidOperandType), "someMinimum", "someMaximum"); Assert.Equal(typeof(InvalidOperandType), attribute.OperandType); Assert.Throws<InvalidOperationException>( () => attribute.Validate("Does not matter - OperandType is not assignable from IComparable", s_testValidationContext)); } [Fact] public static void Validation_throws_InvalidOperationException_if_minimum_is_greater_than_maximum() { var attribute = new RangeAttribute(3, 1); Assert.Throws<InvalidOperationException>( () => attribute.Validate("Does not matter - minimum > maximum", s_testValidationContext)); attribute = new RangeAttribute(3.0, 1.0); Assert.Throws<InvalidOperationException>( () => attribute.Validate("Does not matter - minimum > maximum", s_testValidationContext)); attribute = new RangeAttribute(typeof(int), "3", "1"); Assert.Throws<InvalidOperationException>( () => attribute.Validate("Does not matter - minimum > maximum", s_testValidationContext)); attribute = new RangeAttribute(typeof(double), (3.0).ToString("F1"), (1.0).ToString("F1")); Assert.Throws<InvalidOperationException>( () => attribute.Validate("Does not matter - minimum > maximum", s_testValidationContext)); attribute = new RangeAttribute(typeof(string), "z", "a"); Assert.Throws<InvalidOperationException>( () => attribute.Validate("Does not matter - minimum > maximum", s_testValidationContext)); } [Fact] public static void Validation_throws_FormatException_if_min_and_max_values_cannot_be_converted_to_DateTime_OperandType() { var attribute = new RangeAttribute(typeof(DateTime), "Cannot Convert", "2014-03-19"); Assert.Throws<FormatException>( () => attribute.Validate("Does not matter - cannot convert minimum to DateTime", s_testValidationContext)); attribute = new RangeAttribute(typeof(DateTime), "2014-03-19", "Cannot Convert"); Assert.Throws<FormatException>( () => attribute.Validate("Does not matter - cannot convert maximum to DateTime", s_testValidationContext)); } [Fact] public static void Validation_throws_Exception_if_min_and_max_values_cannot_be_converted_to_int_OperandType() { var attribute = new RangeAttribute(typeof(int), "Cannot Convert", "3"); Assert.Throws<FormatException>( () => attribute.Validate("Does not matter - cannot convert minimum to int", s_testValidationContext)); attribute = new RangeAttribute(typeof(int), "1", "Cannot Convert"); Assert.Throws<FormatException>( () => attribute.Validate("Does not matter - cannot convert maximum to int", s_testValidationContext)); } [Fact] public static void Validation_throws_Exception_if_min_and_max_values_cannot_be_converted_to_double_OperandType() { var attribute = new RangeAttribute(typeof(double), "Cannot Convert", (3.0).ToString("F1")); Assert.Throws<FormatException>( () => attribute.Validate("Does not matter - cannot convert minimum to double", s_testValidationContext)); attribute = new RangeAttribute(typeof(double), (1.0).ToString("F1"), "Cannot Convert"); Assert.Throws<FormatException>( () => attribute.Validate("Does not matter - cannot convert maximum to double", s_testValidationContext)); } public class InvalidOperandType // does not implement IComparable { public InvalidOperandType(string message) { } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using log4net; namespace OpenSim.Region.ClientStack.LindenUDP { /// <summary> /// A hierarchical token bucket for bandwidth throttling. See /// http://en.wikipedia.org/wiki/Token_bucket for more information /// </summary> public class TokenBucket { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static Int32 m_counter = 0; // private Int32 m_identifier; protected const float m_timeScale = 1e-3f; /// <summary> /// This is the number of m_minimumDripRate bytes /// allowed in a burst /// roughtly, with this settings, the maximum time system will take /// to recheck a bucket in ms /// /// </summary> protected const float m_quantumsPerBurst = 5; /// <summary> /// </summary> protected const float m_minimumDripRate = 1500; /// <summary>Time of the last drip, in system ticks</summary> protected Int32 m_lastDrip; /// <summary> /// The number of bytes that can be sent at this moment. This is the /// current number of tokens in the bucket /// </summary> protected float m_tokenCount; /// <summary> /// Map of children buckets and their requested maximum burst rate /// </summary> protected Dictionary<TokenBucket, float> m_children = new Dictionary<TokenBucket, float>(); #region Properties /// <summary> /// The parent bucket of this bucket, or null if this bucket has no /// parent. The parent bucket will limit the aggregate bandwidth of all /// of its children buckets /// </summary> protected TokenBucket m_parent; public TokenBucket Parent { get { return m_parent; } set { m_parent = value; } } /// <summary> /// This is the maximum number /// of tokens that can accumulate in the bucket at any one time. This /// also sets the total request for leaf nodes /// </summary> protected float m_burst; public virtual float MaxDripRate { get; set; } public float RequestedBurst { get { return m_burst; } set { float rate = (value < 0 ? 0 : value); if (rate < 1.5f * m_minimumDripRate) rate = 1.5f * m_minimumDripRate; else if (rate > m_minimumDripRate * m_quantumsPerBurst) rate = m_minimumDripRate * m_quantumsPerBurst; m_burst = rate; } } public float Burst { get { float rate = RequestedBurst * BurstModifier(); if (rate < m_minimumDripRate) rate = m_minimumDripRate; return (float)rate; } } /// <summary> /// The requested drip rate for this particular bucket. /// </summary> /// <remarks> /// 0 then TotalDripRequest is used instead. /// Can never be above MaxDripRate. /// Tokens are added to the bucket at any time /// <seealso cref="RemoveTokens"/> is called, at the granularity of /// the system tick interval (typically around 15-22ms)</remarks> protected float m_dripRate; public virtual float RequestedDripRate { get { return (m_dripRate == 0 ? m_totalDripRequest : m_dripRate); } set { m_dripRate = (value < 0 ? 0 : value); m_totalDripRequest = m_dripRate; if (m_parent != null) m_parent.RegisterRequest(this,m_dripRate); } } public virtual float DripRate { get { float rate = Math.Min(RequestedDripRate,TotalDripRequest); if (m_parent == null) return rate; rate *= m_parent.DripRateModifier(); if (rate < m_minimumDripRate) rate = m_minimumDripRate; return (float)rate; } } /// <summary> /// The current total of the requested maximum burst rates of children buckets. /// </summary> protected float m_totalDripRequest; public float TotalDripRequest { get { return m_totalDripRequest; } set { m_totalDripRequest = value; } } #endregion Properties #region Constructor /// <summary> /// Default constructor /// </summary> /// <param name="identifier">Identifier for this token bucket</param> /// <param name="parent">Parent bucket if this is a child bucket, or /// null if this is a root bucket</param> /// <param name="maxBurst">Maximum size of the bucket in bytes, or /// zero if this bucket has no maximum capacity</param> /// <param name="dripRate">Rate that the bucket fills, in bytes per /// second. If zero, the bucket always remains full</param> public TokenBucket(TokenBucket parent, float dripRate, float MaxBurst) { m_counter++; Parent = parent; RequestedDripRate = dripRate; RequestedBurst = MaxBurst; // TotalDripRequest = dripRate; // this will be overwritten when a child node registers // MaxBurst = (Int64)((double)dripRate * m_quantumsPerBurst); m_lastDrip = Util.EnvironmentTickCount() + 100000; } #endregion Constructor /// <summary> /// Compute a modifier for the MaxBurst rate. This is 1.0, meaning /// no modification if the requested bandwidth is less than the /// max burst bandwidth all the way to the root of the throttle /// hierarchy. However, if any of the parents is over-booked, then /// the modifier will be less than 1. /// </summary> protected float DripRateModifier() { float driprate = DripRate; return driprate >= TotalDripRequest ? 1.0f : driprate / TotalDripRequest; } /// <summary> /// </summary> protected float BurstModifier() { // for now... burst rate is always m_quantumsPerBurst (constant) // larger than drip rate so the ratio of burst requests is the // same as the drip ratio return DripRateModifier(); } /// <summary> /// Register drip rate requested by a child of this throttle. Pass the /// changes up the hierarchy. /// </summary> public void RegisterRequest(TokenBucket child, float request) { lock (m_children) { m_children[child] = request; m_totalDripRequest = 0; foreach (KeyValuePair<TokenBucket, float> cref in m_children) m_totalDripRequest += cref.Value; } // Pass the new values up to the parent if (m_parent != null) m_parent.RegisterRequest(this, Math.Min(RequestedDripRate, TotalDripRequest)); } /// <summary> /// Remove the rate requested by a child of this throttle. Pass the /// changes up the hierarchy. /// </summary> public void UnregisterRequest(TokenBucket child) { lock (m_children) { m_children.Remove(child); m_totalDripRequest = 0; foreach (KeyValuePair<TokenBucket, float> cref in m_children) m_totalDripRequest += cref.Value; } // Pass the new values up to the parent if (Parent != null) Parent.RegisterRequest(this,Math.Min(RequestedDripRate, TotalDripRequest)); } /// <summary> /// Remove a given number of tokens from the bucket /// </summary> /// <param name="amount">Number of tokens to remove from the bucket</param> /// <returns>True if the requested number of tokens were removed from /// the bucket, otherwise false</returns> public bool RemoveTokens(int amount) { // Deposit tokens for this interval Drip(); // If we have enough tokens then remove them and return if (m_tokenCount - amount >= 0) { // we don't have to remove from the parent, the drip rate is already // reflective of the drip rate limits in the parent m_tokenCount -= amount; return true; } return false; } public bool CheckTokens(int amount) { return (m_tokenCount - amount >= 0); } public int GetCatBytesCanSend(int timeMS) { // return (int)(m_tokenCount + timeMS * m_dripRate * 1e-3); return (int)(timeMS * DripRate * 1e-3); } /// <summary> /// Add tokens to the bucket over time. The number of tokens added each /// call depends on the length of time that has passed since the last /// call to Drip /// </summary> /// <returns>True if tokens were added to the bucket, otherwise false</returns> protected void Drip() { // This should never happen... means we are a leaf node and were created // with no drip rate... if (DripRate == 0) { m_log.WarnFormat("[TOKENBUCKET] something odd is happening and drip rate is 0 for {0}", m_counter); return; } Int32 now = Util.EnvironmentTickCount(); Int32 deltaMS = now - m_lastDrip; m_lastDrip = now; if (deltaMS <= 0) return; m_tokenCount += deltaMS * DripRate * m_timeScale; float burst = Burst; if (m_tokenCount > burst) m_tokenCount = burst; } } public class AdaptiveTokenBucket : TokenBucket { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public bool AdaptiveEnabled { get; set; } /// <summary> /// The minimum rate for flow control. Minimum drip rate is one /// packet per second. /// </summary> protected const float m_minimumFlow = 50000; // <summary> // The maximum rate for flow control. Drip rate can never be // greater than this. // </summary> protected float m_maxDripRate = 0; public override float MaxDripRate { get { return (m_maxDripRate == 0 ? m_totalDripRequest : m_maxDripRate); } set { m_maxDripRate = (value == 0 ? m_totalDripRequest : Math.Max(value, m_minimumFlow)); } } private bool m_enabled = false; // <summary> // Adjust drip rate in response to network conditions. // </summary> public virtual float AdjustedDripRate { get { return m_dripRate; } set { m_dripRate = OpenSim.Framework.Util.Clamp<float>(value, m_minimumFlow, MaxDripRate); if (m_parent != null) m_parent.RegisterRequest(this, m_dripRate); } } // <summary> // // </summary> public AdaptiveTokenBucket(TokenBucket parent, float maxDripRate, float maxBurst, bool enabled) : base(parent, maxDripRate, maxBurst) { m_enabled = enabled; MaxDripRate = maxDripRate; if (enabled) AdjustedDripRate = m_maxDripRate * .5f; else AdjustedDripRate = m_maxDripRate; } /// <summary> /// Reliable packets sent to the client for which we never received an ack adjust the drip rate down. /// <param name="packets">Number of packets that expired without successful delivery</param> /// </summary> public void ExpirePackets(Int32 count) { // m_log.WarnFormat("[ADAPTIVEBUCKET] drop {0} by {1} expired packets",AdjustedDripRate,count); if (m_enabled) AdjustedDripRate = (Int64)(AdjustedDripRate / Math.Pow(2, count)); } // <summary> // // </summary> public void AcknowledgePackets(Int32 count) { if (m_enabled) AdjustedDripRate = AdjustedDripRate + count; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { [ToolboxItem(false)] public partial class DockPane : UserControl, IDockDragSource { public enum AppearanceStyle { ToolWindow, Document } private enum HitTestArea { Caption, TabStrip, Content, None } private struct HitTestResult { public HitTestArea HitArea; public int Index; public HitTestResult(HitTestArea hitTestArea, int index) { HitArea = hitTestArea; Index = index; } } private DockPaneCaptionBase m_captionControl; private DockPaneCaptionBase CaptionControl { get { return m_captionControl; } } private DockPaneStripBase m_tabStripControl; internal DockPaneStripBase TabStripControl { get { return m_tabStripControl; } } internal protected DockPane(IDockContent content, DockState visibleState, bool show) { InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show) { if (floatWindow == null) throw new ArgumentNullException("floatWindow"); InternalConstruct(content, DockState.Float, false, Rectangle.Empty, floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show); } internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show) { if (previousPane == null) throw (new ArgumentNullException("previousPane")); InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, proportion, show); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show) { InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show); } private void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show) { if (dockState == DockState.Hidden || dockState == DockState.Unknown) throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState); if (content == null) throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent); if (content.DockHandler.DockPanel == null) throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel); SuspendLayout(); SetStyle(ControlStyles.Selectable, false); m_isFloat = (dockState == DockState.Float); m_contents = new DockContentCollection(); m_displayingContents = new DockContentCollection(this); m_dockPanel = content.DockHandler.DockPanel; m_dockPanel.AddPane(this); m_splitter = new SplitterControl(this); m_nestedDockingStatus = new NestedDockingStatus(this); m_captionControl = DockPanel.DockPaneCaptionFactory.CreateDockPaneCaption(this); m_tabStripControl = DockPanel.DockPaneStripFactory.CreateDockPaneStrip(this); Controls.AddRange(new Control[] { m_captionControl, m_tabStripControl }); DockPanel.SuspendLayout(true); if (flagBounds) FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); else if (prevPane != null) DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion); SetDockState(dockState); if (show) content.DockHandler.Pane = this; else if (this.IsFloat) content.DockHandler.FloatPane = this; else content.DockHandler.PanelPane = this; ResumeLayout(); DockPanel.ResumeLayout(true, true); } private bool m_isDisposing; protected override void Dispose(bool disposing) { if (disposing) { // IMPORTANT: avoid nested call into this method on Mono. // https://github.com/dockpanelsuite/dockpanelsuite/issues/16 if (Win32Helper.IsRunningOnMono) { if (m_isDisposing) return; m_isDisposing = true; } m_dockState = DockState.Unknown; if (NestedPanesContainer != null) NestedPanesContainer.NestedPanes.Remove(this); if (DockPanel != null) { DockPanel.RemovePane(this); m_dockPanel = null; } Splitter.Dispose(); if (m_autoHidePane != null) m_autoHidePane.Dispose(); } base.Dispose(disposing); } private IDockContent m_activeContent = null; public virtual IDockContent ActiveContent { get { return m_activeContent; } set { if (ActiveContent == value) return; if (value != null) { if (!DisplayingContents.Contains(value)) throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue)); } else { if (DisplayingContents.Count != 0) throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue)); } IDockContent oldValue = m_activeContent; if (DockPanel.ActiveAutoHideContent == oldValue) DockPanel.ActiveAutoHideContent = null; m_activeContent = value; if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) { if (m_activeContent != null) m_activeContent.DockHandler.Form.BringToFront(); } else { if (m_activeContent != null) m_activeContent.DockHandler.SetVisible(); if (oldValue != null && DisplayingContents.Contains(oldValue)) oldValue.DockHandler.SetVisible(); if (IsActivated && m_activeContent != null) m_activeContent.DockHandler.Activate(); } if (FloatWindow != null) FloatWindow.SetText(); if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) RefreshChanges(false); // delayed layout to reduce screen flicker else RefreshChanges(); if (m_activeContent != null) TabStripControl.EnsureTabVisible(m_activeContent); } } private bool m_allowDockDragAndDrop = true; public virtual bool AllowDockDragAndDrop { get { return m_allowDockDragAndDrop; } set { m_allowDockDragAndDrop = value; } } private IDisposable m_autoHidePane = null; internal IDisposable AutoHidePane { get { return m_autoHidePane; } set { m_autoHidePane = value; } } private object m_autoHideTabs = null; internal object AutoHideTabs { get { return m_autoHideTabs; } set { m_autoHideTabs = value; } } private object TabPageContextMenu { get { IDockContent content = ActiveContent; if (content == null) return null; if (content.DockHandler.TabPageContextMenuStrip != null) return content.DockHandler.TabPageContextMenuStrip; else if (content.DockHandler.TabPageContextMenu != null) return content.DockHandler.TabPageContextMenu; else return null; } } internal bool HasTabPageContextMenu { get { return TabPageContextMenu != null; } } internal void ShowTabPageContextMenu(Control control, Point position) { object menu = TabPageContextMenu; if (menu == null) return; ContextMenuStrip contextMenuStrip = menu as ContextMenuStrip; if (contextMenuStrip != null) { contextMenuStrip.Show(control, position); return; } ContextMenu contextMenu = menu as ContextMenu; if (contextMenu != null) contextMenu.Show(this, position); } private Rectangle CaptionRectangle { get { if (!HasCaption) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int x, y, width; x = rectWindow.X; y = rectWindow.Y; width = rectWindow.Width; int height = CaptionControl.MeasureHeight(); return new Rectangle(x, y, width, height); } } internal Rectangle ContentRectangle { get { Rectangle rectWindow = DisplayingRectangle; Rectangle rectCaption = CaptionRectangle; Rectangle rectTabStrip = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height); if (DockState == DockState.Document && DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Top) y += rectTabStrip.Height; int width = rectWindow.Width; int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height; return new Rectangle(x, y, width, height); } } internal Rectangle TabStripRectangle { get { if (Appearance == AppearanceStyle.ToolWindow) return TabStripRectangle_ToolWindow; else return TabStripRectangle_Document; } } private Rectangle TabStripRectangle_ToolWindow { get { if (DisplayingContents.Count <= 1 || IsAutoHide) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int width = rectWindow.Width; int height = TabStripControl.MeasureHeight(); int x = rectWindow.X; int y = rectWindow.Bottom - height; Rectangle rectCaption = CaptionRectangle; if (rectCaption.Contains(x, y)) y = rectCaption.Y + rectCaption.Height; return new Rectangle(x, y, width, height); } } private Rectangle TabStripRectangle_Document { get { if (DisplayingContents.Count == 0) return Rectangle.Empty; if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int x = rectWindow.X; int width = rectWindow.Width; int height = TabStripControl.MeasureHeight(); int y = 0; if (DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) y = rectWindow.Height - height; else y = rectWindow.Y; return new Rectangle(x, y, width, height); } } public virtual string CaptionText { get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; } } private DockContentCollection m_contents; public DockContentCollection Contents { get { return m_contents; } } private DockContentCollection m_displayingContents; public DockContentCollection DisplayingContents { get { return m_displayingContents; } } private DockPanel m_dockPanel; public DockPanel DockPanel { get { return m_dockPanel; } } private bool HasCaption { get { if (DockState == DockState.Document || DockState == DockState.Hidden || DockState == DockState.Unknown || (DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1)) return false; else return true; } } private bool m_isActivated = false; public bool IsActivated { get { return m_isActivated; } } internal void SetIsActivated(bool value) { if (m_isActivated == value) return; m_isActivated = value; if (DockState != DockState.Document) RefreshChanges(false); OnIsActivatedChanged(EventArgs.Empty); } private bool m_isActiveDocumentPane = false; public bool IsActiveDocumentPane { get { return m_isActiveDocumentPane; } } internal void SetIsActiveDocumentPane(bool value) { if (m_isActiveDocumentPane == value) return; m_isActiveDocumentPane = value; if (DockState == DockState.Document) RefreshChanges(); OnIsActiveDocumentPaneChanged(EventArgs.Empty); } public bool IsDockStateValid(DockState dockState) { foreach (IDockContent content in Contents) if (!content.DockHandler.IsDockStateValid(dockState)) return false; return true; } public bool IsAutoHide { get { return DockHelper.IsDockStateAutoHide(DockState); } } public AppearanceStyle Appearance { get { return (DockState == DockState.Document) ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; } } internal Rectangle DisplayingRectangle { get { return ClientRectangle; } } public void Activate() { if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent) DockPanel.ActiveAutoHideContent = ActiveContent; else if (!IsActivated && ActiveContent != null) ActiveContent.DockHandler.Activate(); } internal void AddContent(IDockContent content) { if (Contents.Contains(content)) return; Contents.Add(content); } internal void Close() { Dispose(); } public void CloseActiveContent() { CloseContent(ActiveContent); } internal void CloseContent(IDockContent content) { if (content == null) return; if (!content.DockHandler.CloseButton) return; DockPanel dockPanel = DockPanel; dockPanel.SuspendLayout(true); try { if (content.DockHandler.HideOnClose) { content.DockHandler.Hide(); NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } else content.DockHandler.Close(); } finally { dockPanel.ResumeLayout(true, true); } } private HitTestResult GetHitTest(Point ptMouse) { Point ptMouseClient = PointToClient(ptMouse); Rectangle rectCaption = CaptionRectangle; if (rectCaption.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.Caption, -1); Rectangle rectContent = ContentRectangle; if (rectContent.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.Content, -1); Rectangle rectTabStrip = TabStripRectangle; if (rectTabStrip.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.TabStrip, TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse))); return new HitTestResult(HitTestArea.None, -1); } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } } private void SetIsHidden(bool value) { if (m_isHidden == value) return; m_isHidden = value; if (DockHelper.IsDockStateAutoHide(DockState)) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } else if (NestedPanesContainer != null) ((Control)NestedPanesContainer).PerformLayout(); } protected override void OnLayout(LayoutEventArgs levent) { SetIsHidden(DisplayingContents.Count == 0); if (!IsHidden) { CaptionControl.Bounds = CaptionRectangle; TabStripControl.Bounds = TabStripRectangle; SetContentBounds(); foreach (IDockContent content in Contents) { if (DisplayingContents.Contains(content)) if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible) content.DockHandler.FlagClipWindow = false; } } base.OnLayout(levent); } internal void SetContentBounds() { Rectangle rectContent = ContentRectangle; if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent)); Rectangle rectInactive = new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height); foreach (IDockContent content in Contents) if (content.DockHandler.Pane == this) { if (content == ActiveContent) content.DockHandler.Form.Bounds = rectContent; else content.DockHandler.Form.Bounds = rectInactive; } } internal void RefreshChanges() { RefreshChanges(true); } private void RefreshChanges(bool performLayout) { if (IsDisposed) return; CaptionControl.RefreshChanges(); TabStripControl.RefreshChanges(); if (DockState == DockState.Float && FloatWindow != null) FloatWindow.RefreshChanges(); if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } if (performLayout) PerformLayout(); } internal void RemoveContent(IDockContent content) { if (!Contents.Contains(content)) return; Contents.Remove(content); } public void SetContentIndex(IDockContent content, int index) { int oldIndex = Contents.IndexOf(content); if (oldIndex == -1) throw (new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent)); if (index < 0 || index > Contents.Count - 1) if (index != -1) throw (new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex)); if (oldIndex == index) return; if (oldIndex == Contents.Count - 1 && index == -1) return; Contents.Remove(content); if (index == -1) Contents.Add(content); else if (oldIndex < index) Contents.AddAt(content, index - 1); else Contents.AddAt(content, index); RefreshChanges(); } private void SetParent() { if (DockState == DockState.Unknown || DockState == DockState.Hidden) { SetParent(null); Splitter.Parent = null; } else if (DockState == DockState.Float) { SetParent(FloatWindow); Splitter.Parent = FloatWindow; } else if (DockHelper.IsDockStateAutoHide(DockState)) { SetParent(DockPanel.AutoHideControl); Splitter.Parent = null; } else { SetParent(DockPanel.DockWindows[DockState]); Splitter.Parent = Parent; } } private void SetParent(Control value) { if (Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Parent = value; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (contentFocused != null) contentFocused.DockHandler.Activate(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public new void Show() { Activate(); } internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline) { if (!dragSource.CanDockTo(this)) return; Point ptMouse = Control.MousePosition; HitTestResult hitTestResult = GetHitTest(ptMouse); if (hitTestResult.HitArea == HitTestArea.Caption) dockOutline.Show(this, -1); else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1) dockOutline.Show(this, hitTestResult.Index); } internal void ValidateActiveContent() { if (ActiveContent == null) { if (DisplayingContents.Count != 0) ActiveContent = DisplayingContents[0]; return; } if (DisplayingContents.IndexOf(ActiveContent) >= 0) return; IDockContent prevVisible = null; for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--) if (Contents[i].DockHandler.DockState == DockState) { prevVisible = Contents[i]; break; } IDockContent nextVisible = null; for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++) if (Contents[i].DockHandler.DockState == DockState) { nextVisible = Contents[i]; break; } if (prevVisible != null) ActiveContent = prevVisible; else if (nextVisible != null) ActiveContent = nextVisible; else ActiveContent = null; } private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } private static readonly object IsActivatedChangedEvent = new object(); public event EventHandler IsActivatedChanged { add { Events.AddHandler(IsActivatedChangedEvent, value); } remove { Events.RemoveHandler(IsActivatedChangedEvent, value); } } protected virtual void OnIsActivatedChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[IsActivatedChangedEvent]; if (handler != null) handler(this, e); } private static readonly object IsActiveDocumentPaneChangedEvent = new object(); public event EventHandler IsActiveDocumentPaneChanged { add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); } remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); } } protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[IsActiveDocumentPaneChangedEvent]; if (handler != null) handler(this, e); } public DockWindow DockWindow { get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as DockWindow; } set { DockWindow oldValue = DockWindow; if (oldValue == value) return; DockTo(value); } } public FloatWindow FloatWindow { get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as FloatWindow; } set { FloatWindow oldValue = FloatWindow; if (oldValue == value) return; DockTo(value); } } private NestedDockingStatus m_nestedDockingStatus; public NestedDockingStatus NestedDockingStatus { get { return m_nestedDockingStatus; } } private bool m_isFloat; public bool IsFloat { get { return m_isFloat; } } public INestedPanesContainer NestedPanesContainer { get { if (NestedDockingStatus.NestedPanes == null) return null; else return NestedDockingStatus.NestedPanes.Container; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { SetDockState(value); } } public DockPane SetDockState(DockState value) { if (value == DockState.Unknown || value == DockState.Hidden) throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState); if ((value == DockState.Float) == this.IsFloat) { InternalSetDockState(value); return this; } if (DisplayingContents.Count == 0) return null; IDockContent firstContent = null; for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(value)) { firstContent = content; break; } } if (firstContent == null) return null; firstContent.DockHandler.DockState = value; DockPane pane = firstContent.DockHandler.Pane; DockPanel.SuspendLayout(true); for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(value)) content.DockHandler.Pane = pane; } DockPanel.ResumeLayout(true, true); return pane; } private void InternalSetDockState(DockState value) { if (m_dockState == value) return; DockState oldDockState = m_dockState; INestedPanesContainer oldContainer = NestedPanesContainer; m_dockState = value; SuspendRefreshStateChange(); IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); if (!IsFloat) DockWindow = DockPanel.DockWindows[DockState]; else if (FloatWindow == null) FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this); if (contentFocused != null) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.Activate(contentFocused); } } ResumeRefreshStateChange(oldContainer, oldDockState); } private int m_countRefreshStateChange = 0; private void SuspendRefreshStateChange() { m_countRefreshStateChange++; DockPanel.SuspendLayout(true); } private void ResumeRefreshStateChange() { m_countRefreshStateChange--; System.Diagnostics.Debug.Assert(m_countRefreshStateChange >= 0); DockPanel.ResumeLayout(true, true); } private bool IsRefreshStateChangeSuspended { get { return m_countRefreshStateChange != 0; } } private void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) { ResumeRefreshStateChange(); RefreshStateChange(oldContainer, oldDockState); } private void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) { if (IsRefreshStateChangeSuspended) return; SuspendRefreshStateChange(); DockPanel.SuspendLayout(true); IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); SetParent(); if (ActiveContent != null) ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, ActiveContent.DockHandler.Pane); foreach (IDockContent content in Contents) { if (content.DockHandler.Pane == this) content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane); } if (oldContainer != null) { Control oldContainerControl = (Control)oldContainer; if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed) oldContainerControl.PerformLayout(); } if (DockHelper.IsDockStateAutoHide(oldDockState)) DockPanel.RefreshActiveAutoHideContent(); if (NestedPanesContainer.DockState == DockState) ((Control)NestedPanesContainer).PerformLayout(); if (DockHelper.IsDockStateAutoHide(DockState)) DockPanel.RefreshActiveAutoHideContent(); if (DockHelper.IsDockStateAutoHide(oldDockState) || DockHelper.IsDockStateAutoHide(DockState)) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } ResumeRefreshStateChange(); if (contentFocused != null) contentFocused.DockHandler.Activate(); DockPanel.ResumeLayout(true, true); if (oldDockState != DockState) OnDockStateChanged(EventArgs.Empty); } private IDockContent GetFocusedContent() { IDockContent contentFocused = null; foreach (IDockContent content in Contents) { if (content.DockHandler.Form.ContainsFocus) { contentFocused = content; break; } } return contentFocused; } public DockPane DockTo(INestedPanesContainer container) { if (container == null) throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); DockAlignment alignment; if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight) alignment = DockAlignment.Bottom; else alignment = DockAlignment.Right; return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5); } public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, double proportion) { if (container == null) throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); if (container.IsFloat == this.IsFloat) { InternalAddToDockList(container, previousPane, alignment, proportion); return this; } IDockContent firstContent = GetFirstContent(container.DockState); if (firstContent == null) return null; DockPane pane; DockPanel.DummyContent.DockPanel = DockPanel; if (container.IsFloat) pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow)container, true); else pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true); pane.DockTo(container, previousPane, alignment, proportion); SetVisibleContentsToPane(pane); DockPanel.DummyContent.DockPanel = null; return pane; } private void SetVisibleContentsToPane(DockPane pane) { SetVisibleContentsToPane(pane, ActiveContent); } private void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent) { for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(pane.DockState)) { content.DockHandler.Pane = pane; i--; } } if (activeContent.DockHandler.Pane == pane) pane.ActiveContent = activeContent; } private void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, double proportion) { if ((container.DockState == DockState.Float) != IsFloat) throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer); int count = container.NestedPanes.Count; if (container.NestedPanes.Contains(this)) count--; if (prevPane == null && count > 0) throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane); if (prevPane != null && !container.NestedPanes.Contains(prevPane)) throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane); if (prevPane == this) throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane); INestedPanesContainer oldContainer = NestedPanesContainer; DockState oldDockState = DockState; container.NestedPanes.Add(this); NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion); if (DockHelper.IsDockWindowState(DockState)) m_dockState = container.DockState; RefreshStateChange(oldContainer, oldDockState); } public void SetNestedDockingProportion(double proportion) { NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, NestedDockingStatus.Alignment, proportion); if (NestedPanesContainer != null) ((Control)NestedPanesContainer).PerformLayout(); } public DockPane Float() { DockPanel.SuspendLayout(true); IDockContent activeContent = ActiveContent; DockPane floatPane = GetFloatPaneFromContents(); if (floatPane == null) { IDockContent firstContent = GetFirstContent(DockState.Float); if (firstContent == null) { DockPanel.ResumeLayout(true, true); return null; } floatPane = DockPanel.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true); } SetVisibleContentsToPane(floatPane, activeContent); DockPanel.ResumeLayout(true, true); return floatPane; } private DockPane GetFloatPaneFromContents() { DockPane floatPane = null; for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (!content.DockHandler.IsDockStateValid(DockState.Float)) continue; if (floatPane != null && content.DockHandler.FloatPane != floatPane) return null; else floatPane = content.DockHandler.FloatPane; } return floatPane; } private IDockContent GetFirstContent(DockState dockState) { for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(dockState)) return content; } return null; } public void RestoreToPanel() { DockPanel.SuspendLayout(true); IDockContent activeContent = DockPanel.ActiveContent; for (int i = DisplayingContents.Count - 1; i >= 0; i--) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.CheckDockState(false) != DockState.Unknown) content.DockHandler.IsFloat = false; } DockPanel.ResumeLayout(true, true); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { if (m.Msg == (int)Win32.Msgs.WM_MOUSEACTIVATE) Activate(); base.WndProc(ref m); } #region IDockDragSource Members #region IDragSource Members Control IDragSource.DragControl { get { return this; } } #endregion bool IDockDragSource.IsDockStateValid(DockState dockState) { return IsDockStateValid(dockState); } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (pane == this) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Point location = PointToScreen(new Point(0, 0)); Size size; DockPane floatPane = ActiveContent.DockHandler.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1) FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); else FloatWindow.Bounds = floatWindowBounds; DockState = DockState.Float; NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { IDockContent activeContent = ActiveContent; for (int i = Contents.Count - 1; i >= 0; i--) { IDockContent c = Contents[i]; if (c.DockHandler.DockState == DockState) { c.DockHandler.Pane = pane; if (contentIndex != -1) pane.SetContentIndex(c, contentIndex); } } pane.ActiveContent = activeContent; } else { if (dockStyle == DockStyle.Left) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5); DockState = pane.DockState; } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); if (dockStyle == DockStyle.Top) DockState = DockState.DockTop; else if (dockStyle == DockStyle.Bottom) DockState = DockState.DockBottom; else if (dockStyle == DockStyle.Left) DockState = DockState.DockLeft; else if (dockStyle == DockStyle.Right) DockState = DockState.DockRight; else if (dockStyle == DockStyle.Fill) DockState = DockState.Document; } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans; using Orleans.LogConsistency; using Orleans.Storage; using Orleans.EventSourcing.Common; using Orleans.Runtime; namespace Orleans.EventSourcing.StateStorage { /// <summary> /// A log view adaptor that wraps around a traditional storage adaptor, and uses batching and e-tags /// to append entries. ///<para> /// The log itself is transient, i.e. not actually saved to storage - only the latest view and some /// metadata (the log position, and write flags) are stored. /// </para> /// </summary> /// <typeparam name="TLogView">Type of log view</typeparam> /// <typeparam name="TLogEntry">Type of log entry</typeparam> internal class LogViewAdaptor<TLogView, TLogEntry> : PrimaryBasedLogViewAdaptor<TLogView, TLogEntry, SubmissionEntry<TLogEntry>> where TLogView : class, new() where TLogEntry : class { /// <summary> /// Initialize a StorageProviderLogViewAdaptor class /// </summary> public LogViewAdaptor(ILogViewAdaptorHost<TLogView, TLogEntry> host, TLogView initialState, IGrainStorage globalGrainStorage, string grainTypeName, ILogConsistencyProtocolServices services) : base(host, initialState, services) { this.globalGrainStorage = globalGrainStorage; this.grainTypeName = grainTypeName; } private const int maxEntriesInNotifications = 200; IGrainStorage globalGrainStorage; string grainTypeName; // stores the confirmed state including metadata GrainStateWithMetaDataAndETag<TLogView> GlobalStateCache; /// <inheritdoc/> protected override TLogView LastConfirmedView() { return GlobalStateCache.StateAndMetaData.State; } /// <inheritdoc/> protected override int GetConfirmedVersion() { return GlobalStateCache.StateAndMetaData.GlobalVersion; } /// <inheritdoc/> protected override void InitializeConfirmedView(TLogView initialstate) { GlobalStateCache = new GrainStateWithMetaDataAndETag<TLogView>(initialstate); } // no special tagging is required, thus we create a plain submission entry /// <inheritdoc/> protected override SubmissionEntry<TLogEntry> MakeSubmissionEntry(TLogEntry entry) { return new SubmissionEntry<TLogEntry>() { Entry = entry }; } /// <inheritdoc/> protected override async Task ReadAsync() { enter_operation("ReadAsync"); while (true) { try { // for manual testing //await Task.Delay(5000); var readState = new GrainStateWithMetaDataAndETag<TLogView>(); await globalGrainStorage.ReadStateAsync(grainTypeName, Services.GrainReference, readState); GlobalStateCache = readState; Services.Log(LogLevel.Debug, "read success {0}", GlobalStateCache); LastPrimaryIssue.Resolve(Host, Services); break; // successful } catch (Exception e) { LastPrimaryIssue.Record(new ReadFromStateStorageFailed() { Exception = e }, Host, Services); } Services.Log(LogLevel.Debug, "read failed {0}", LastPrimaryIssue); await LastPrimaryIssue.DelayBeforeRetry(); } exit_operation("ReadAsync"); } /// <inheritdoc/> protected override async Task<int> WriteAsync() { enter_operation("WriteAsync"); var state = CopyTentativeState(); var updates = GetCurrentBatchOfUpdates(); bool batchsuccessfullywritten = false; var nextglobalstate = new GrainStateWithMetaDataAndETag<TLogView>(state); nextglobalstate.StateAndMetaData.WriteVector = GlobalStateCache.StateAndMetaData.WriteVector; nextglobalstate.StateAndMetaData.GlobalVersion = GlobalStateCache.StateAndMetaData.GlobalVersion + updates.Length; nextglobalstate.ETag = GlobalStateCache.ETag; var writebit = nextglobalstate.StateAndMetaData.FlipBit(Services.MyClusterId); try { // for manual testing //await Task.Delay(5000); await globalGrainStorage.WriteStateAsync(grainTypeName, Services.GrainReference, nextglobalstate); batchsuccessfullywritten = true; GlobalStateCache = nextglobalstate; Services.Log(LogLevel.Debug, "write ({0} updates) success {1}", updates.Length, GlobalStateCache); LastPrimaryIssue.Resolve(Host, Services); } catch (Exception e) { LastPrimaryIssue.Record(new UpdateStateStorageFailed() { Exception = e }, Host, Services); } if (!batchsuccessfullywritten) { Services.Log(LogLevel.Debug, "write apparently failed {0} {1}", nextglobalstate, LastPrimaryIssue); while (true) // be stubborn until we can read what is there { await LastPrimaryIssue.DelayBeforeRetry(); try { await globalGrainStorage.ReadStateAsync(grainTypeName, Services.GrainReference, GlobalStateCache); Services.Log(LogLevel.Debug, "read success {0}", GlobalStateCache); LastPrimaryIssue.Resolve(Host, Services); break; } catch (Exception e) { LastPrimaryIssue.Record(new ReadFromStateStorageFailed() { Exception = e }, Host, Services); } Services.Log(LogLevel.Debug, "read failed {0}", LastPrimaryIssue); } // check if last apparently failed write was in fact successful if (writebit == GlobalStateCache.StateAndMetaData.GetBit(Services.MyClusterId)) { GlobalStateCache = nextglobalstate; Services.Log(LogLevel.Debug, "last write ({0} updates) was actually a success {1}", updates.Length, GlobalStateCache); batchsuccessfullywritten = true; } } exit_operation("WriteAsync"); if (!batchsuccessfullywritten) return 0; return updates.Length; } /// <summary> /// Describes a connection issue that occurred when updating the primary storage. /// </summary> [Serializable] public class UpdateStateStorageFailed : PrimaryOperationFailed { /// <inheritdoc/> public override string ToString() { return $"write state to storage failed: caught {Exception.GetType().Name}: {Exception.Message}"; } } /// <summary> /// Describes a connection issue that occurred when reading from the primary storage. /// </summary> [Serializable] public class ReadFromStateStorageFailed : PrimaryOperationFailed { /// <inheritdoc/> public override string ToString() { return $"read state from storage failed: caught {Exception.GetType().Name}: {Exception.Message}"; } } /// <summary> /// A notification message sent to remote instances after updating this grain in storage. /// </summary> [Serializable] protected class UpdateNotificationMessage : INotificationMessage { /// <inheritdoc/> public int Version { get; set; } /// <summary> The cluster that performed the update </summary> public string Origin { get; set; } /// <summary> The list of updates that were applied </summary> public List<TLogEntry> Updates { get; set; } /// <summary> The e-tag of the storage after applying the updates</summary> public string ETag { get; set; } /// <inheritdoc/> public override string ToString() { return string.Format("v{0} ({1} updates by {2}) etag={3}", Version, Updates.Count, Origin, ETag); } } /// <inheritdoc/> protected override INotificationMessage Merge(INotificationMessage earlierMessage, INotificationMessage laterMessage) { var earlier = earlierMessage as UpdateNotificationMessage; var later = laterMessage as UpdateNotificationMessage; if (earlier != null && later != null && earlier.Origin == later.Origin && earlier.Version + later.Updates.Count == later.Version && earlier.Updates.Count + later.Updates.Count < maxEntriesInNotifications) return new UpdateNotificationMessage() { Version = later.Version, Origin = later.Origin, Updates = earlier.Updates.Concat(later.Updates).ToList(), ETag = later.ETag }; else return base.Merge(earlierMessage, laterMessage); // keep only the version number } private SortedList<long, UpdateNotificationMessage> notifications = new SortedList<long,UpdateNotificationMessage>(); /// <inheritdoc/> protected override void OnNotificationReceived(INotificationMessage payload) { var um = payload as UpdateNotificationMessage; if (um != null) notifications.Add(um.Version - um.Updates.Count, um); else base.OnNotificationReceived(payload); } /// <inheritdoc/> protected override void ProcessNotifications() { // discard notifications that are behind our already confirmed state while (notifications.Count > 0 && notifications.ElementAt(0).Key < GlobalStateCache.StateAndMetaData.GlobalVersion) { Services.Log(LogLevel.Debug, "discarding notification {0}", notifications.ElementAt(0).Value); notifications.RemoveAt(0); } // process notifications that reflect next global version while (notifications.Count > 0 && notifications.ElementAt(0).Key == GlobalStateCache.StateAndMetaData.GlobalVersion) { var updateNotification = notifications.ElementAt(0).Value; notifications.RemoveAt(0); // Apply all operations in pending foreach (var u in updateNotification.Updates) try { Host.UpdateView(GlobalStateCache.StateAndMetaData.State, u); } catch (Exception e) { Services.CaughtUserCodeException("UpdateView", nameof(ProcessNotifications), e); } GlobalStateCache.StateAndMetaData.GlobalVersion = updateNotification.Version; GlobalStateCache.StateAndMetaData.FlipBit(updateNotification.Origin); GlobalStateCache.ETag = updateNotification.ETag; Services.Log(LogLevel.Debug, "notification success ({0} updates) {1}", updateNotification.Updates.Count, GlobalStateCache); } Services.Log(LogLevel.Trace, "unprocessed notifications in queue: {0}", notifications.Count); base.ProcessNotifications(); } #if DEBUG bool operation_in_progress; #endif [Conditional("DEBUG")] private void enter_operation(string name) { #if DEBUG Services.Log(LogLevel.Trace, "/-- enter {0}", name); Debug.Assert(!operation_in_progress); operation_in_progress = true; #endif } [Conditional("DEBUG")] private void exit_operation(string name) { #if DEBUG Services.Log(LogLevel.Trace, "\\-- exit {0}", name); Debug.Assert(operation_in_progress); operation_in_progress = false; #endif } } }
using System; using System.Collections.Generic; using System.Net.Http; using EmsApi.Client.V2.Access; using Microsoft.Extensions.Http; using Newtonsoft.Json.Linq; using Polly; using Polly.Extensions.Http; using Refit; namespace EmsApi.Client.V2 { /// <summary> /// The client side representation of the EMS API. /// </summary> /// <remarks> /// This assembly targets .NET standard, which is supported on all /// flavors of .NET (Framework, Core, Xamarin, etc). /// </remarks> public class EmsApiService : IDisposable { /// <summary> /// Provides access to the EMS API. The <seealso cref="ServiceConfig"/> property /// must be set on this class before any API methods can be used. /// </summary> public EmsApiService() { Initialize( httpClientConfig: null ); // As noted above ServiceConfig must be set before making any API calls. } /// <summary> /// Provides access to the EMS API using the provided configuration settings. /// The first and last handlers, if provided, will be added to the standard HttpMessageHandler /// stack used. This can be useful for tracing or testing purposes. /// </summary> public EmsApiService( EmsApiServiceConfiguration config, EmsApiServiceHttpClientConfiguration httpClientConfig = null ) { Initialize( httpClientConfig ); ServiceConfig = config; } /// <summary> /// Access to the swagger specification. /// </summary> public SwaggerAccess Swagger { get; set; } /// <summary> /// Access to ems-system routes. /// </summary> public EmsSystemAccess EmsSystem { get; set; } /// <summary> /// Access to securables routes. /// </summary> public EmsSecurablesAccess EmsSecurables { get; set; } /// <summary> /// Access to the admin securables routes. /// </summary> public AdminEmsSecurablesAccess AdminEmsSecurables { get; set; } /// <summary> /// Access to assets routes. /// </summary> public AssetsAccess Assets { get; set; } /// <summary> /// Access to trajectory routes. /// </summary> public TrajectoriesAccess Trajectories { get; set; } /// <summary> /// Access to APM profile routes. /// </summary> public ProfilesAccess Profiles { get; set; } /// <summary> /// Access to parameter-sets routes /// </summary> public ParameterSetsAccess ParameterSets { get; set; } /// <summary> /// Access to analytics routes. /// </summary> public AnalyticsAccess Analytics { get; set; } /// <summary> /// Access to the analytic sets routes. /// </summary> public AnalyticSetAccess AnalyticSets { get; set; } /// <summary> /// Access to database routes. /// </summary> public DatabaseAccess Databases { get; set; } /// <summary> /// Access to transfer (uploads) routes. /// </summary> public TransfersAccess Transfers { get; set; } /// <summary> /// Access to admin user routes. /// </summary> public AdminUserAccess AdminUser { get; set; } /// <summary> /// The raw refit interface. This is internal and private set so that the /// access classes can use it without having to hold their own references, /// because this can change when the endpoint changes. /// </summary> internal IEmsApi RefitApi { get; private set; } private void InitializeHttpClient( EmsApiServiceHttpClientConfiguration httpClientConfig ) { // If no client configuration was provided then generate a new one to get the default settings. httpClientConfig = httpClientConfig ?? new EmsApiServiceHttpClientConfiguration(); // This builds up our message handler stack from back to front. // The nextHandler variable is what to assign to the InnerHandler of the latest handler created. HttpMessageHandler nextHandler = new HttpClientHandler { AutomaticDecompression = System.Net.DecompressionMethods.GZip }; if( httpClientConfig.LastHandler != null ) { httpClientConfig.LastHandler.InnerHandler = nextHandler; nextHandler = httpClientConfig.LastHandler; } if( httpClientConfig.RetryTransientFailures ) { // If we are configured to retry transient failures set that up now. // We add this *after* the MessageHandler in the stack so that we get retries on // both token request calls as well as normal API calls. // This will retry and 408 (request timeout), 5XX (server error), or network failures (HttpRequestException). var policyBuilder = HttpPolicyExtensions.HandleTransientHttpError(); var policy = policyBuilder.WaitAndRetryAsync( new[] { // Retry 3 times with slightly longer retry periods each time. TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10) } ); nextHandler = new PolicyHttpMessageHandler( policy ) { InnerHandler = nextHandler }; } nextHandler = m_messageHandler = new MessageHandler { InnerHandler = nextHandler }; if( httpClientConfig.FirstHandler != null ) { httpClientConfig.FirstHandler.InnerHandler = nextHandler; nextHandler = httpClientConfig.FirstHandler; } m_httpClient = new HttpClient( nextHandler ) { // The HttpClient default of 100 seconds is not long enough for some of our longer EMS API calls. For // instance a gnarly database query can take longer than that to return on query creation or first result // extraction time, especially if the SQL server is already busy. // The value we opted for here is the value used for timeouts at the application gateway level and // therefore seems like a reasonable default to use. Timeout = TimeSpan.FromSeconds( 600 ) }; } /// <summary> /// Sets up our API interface and access properties. /// </summary> private void Initialize( EmsApiServiceHttpClientConfiguration httpClientConfig ) { m_cleanup = new List<Action>(); m_authCallbacks = new List<Action<string>>(); m_exceptionCallbacks = new List<Action<string>>(); // Set up the HTTP client. This includes enabling automatic GZip decompression as the // EMS API will use that if requested. InitializeHttpClient( httpClientConfig ); // Set up access properties for external clients to use. InitializeAccessProperties(); // Subscribe to authentication failure events. m_messageHandler.AuthenticationFailedEvent += AuthenticationFailedHandler; m_cleanup.Add( () => m_messageHandler.AuthenticationFailedEvent -= AuthenticationFailedHandler ); } /// <summary> /// Initializes all the known access classes, hooks their API method failed event, /// and adds a cleanup function to remove the event handler on shutdown. /// </summary> private void InitializeAccessProperties() { Swagger = InitializeAccessClass<SwaggerAccess>(); EmsSystem = InitializeAccessClass<EmsSystemAccess>(); EmsSecurables = InitializeAccessClass<EmsSecurablesAccess>(); Assets = InitializeAccessClass<AssetsAccess>(); Trajectories = InitializeAccessClass<TrajectoriesAccess>(); Profiles = InitializeAccessClass<ProfilesAccess>(); ParameterSets = InitializeAccessClass<ParameterSetsAccess>(); Analytics = InitializeAccessClass<AnalyticsAccess>(); AnalyticSets = InitializeAccessClass<AnalyticSetAccess>(); Databases = InitializeAccessClass<DatabaseAccess>(); Transfers = InitializeAccessClass<TransfersAccess>(); AdminUser = InitializeAccessClass<AdminUserAccess>(); AdminEmsSecurables = InitializeAccessClass<AdminEmsSecurablesAccess>(); } private TAccess InitializeAccessClass<TAccess>() where TAccess : RouteAccess, new() { RouteAccess access = new TAccess(); access.SetService( this ); access.ApiMethodFailedEvent += ApiExceptionHandler; m_cleanup.Add( () => access.ApiMethodFailedEvent -= ApiExceptionHandler ); return (TAccess)access; } /// <summary> /// Gets or sets the current service configuration. When setting this value, everything /// including the base <seealso cref="HttpClient"/> is re-configured, since the endpoint /// or authentication properties may have changed. /// </summary> public EmsApiServiceConfiguration ServiceConfig { get { return m_config; } set { ValidateConfigOrThrow( value ); SetServiceConfigInternal( value ); } } /// <summary> /// Internally sets the current service configuration without validation. This is used /// with the default constructor so that the user can specify a configuration using the /// ServiceConfig property without forcing a validation (because the default config is /// invalid without a credential). /// </summary> private void SetServiceConfigInternal( EmsApiServiceConfiguration config ) { m_config = config; m_messageHandler.ServiceConfig = config; // Reset the default headers, they may have changed with the config. m_httpClient.DefaultRequestHeaders.Clear(); m_config.AddDefaultRequestHeaders( m_httpClient.DefaultRequestHeaders ); // See if the endpoint has changed. if( m_config.Endpoint != m_endpoint ) { m_endpoint = m_config.Endpoint; // Reset the BaseAddress, and create a new refit service stub. // It's bound to the HttpClient's base address when it's constructed. m_httpClient.BaseAddress = new Uri( m_config.Endpoint ); var refitSettings = new RefitSettings { // In Refit v6 they switched to using System.Text.Json by default. We did not // want to go through the hassle of converting our DTOs to that so we are // going to still use Newtonsoft. ContentSerializer = new NewtonsoftJsonContentSerializer() }; RefitApi = RestService.For<IEmsApi>( m_httpClient, refitSettings ); } } /// <summary> /// Returns true if the current service is authenticated for password authentication. If /// the service is not currently password authenticated, but has performed trusted /// authentication, this will return false. This is by design as this property was intended /// for use with password authentication only. Re-authentication may still be required if /// this returns true, as the token may have timed out or may time out by the time the next /// EMS API request is made. /// </summary> public bool Authenticated { get { return m_messageHandler.HasAuthenticatedWithPassword(); } } /// <summary> /// Returns true if the specified trusted name/value pair has authenticated. /// </summary> public bool HasAuthenticatedWithTrusted( string authName, string authValue ) { return m_messageHandler.HasAuthenticatedWithTrusted( authName, authValue ); } /// <summary> /// Manually initiate password authentication. Returns true if authentication succeeded, /// or false otherwise. Normally authentication is performed on the first API /// request or on the next request after the current token has timed out. /// </summary> public bool Authenticate() { return m_messageHandler.AuthenticateWithPassword(); } /// <summary> /// Clear out the authentication token cache. /// </summary> public void ClearAuthenticationCache() { m_messageHandler.ClearAuthenticationCache(); } /// <summary> /// Expires the entries in the autnetication cache. /// </summary> /// <remarks> /// This is intended for testing purposes. If you want to clear the authentication cache /// use <seealso cref="ClearAuthenticationCache"/>. /// </remarks> public void ExpireAuthenticationCacheEntries() { m_messageHandler.ExpireAuthenticationCacheEntries(); } /// <summary> /// Registers a callback to be notified when API authentication fails. The callback will /// be executed for every authentication failure, even subsequent failures in rapid succession. /// All callbacks will be automatically unregistered when the service is disposed, or they may /// be manually unregistered with <seealso cref="UnregisterAuthFailedCallback( Action{ string } )"/> /// </summary> public void RegisterAuthFailedCallback( Action<string> callback ) { m_authCallbacks.Add( callback ); } /// <summary> /// Unregisters a callback for API authentication failed notifications. /// </summary> public void UnregisterAuthFailedCallback( Action<string> callback ) { m_authCallbacks.Remove( callback ); } /// <summary> /// Registers a callback to be notified when an API exception occurs. All callbacks will be automatically /// unregistered when the service is disposed, or they may /// </summary> public void RegisterApiExceptionCallback( Action<string> callback ) { m_exceptionCallbacks.Add( callback ); } /// <summary> /// Unregisters a callback for API authentication failed notifications. /// </summary> public void UnregisterApiExceptionCallback( Action<string> callback ) { m_exceptionCallbacks.Remove( callback ); } /// <summary> /// Free up used resources. /// </summary> public void Dispose() { // Perform cleanup actions. if( m_cleanup != null ) { foreach( Action action in m_cleanup ) action(); } if( m_messageHandler != null ) m_messageHandler.Dispose(); } /// <summary> /// Executed when an underlying API exception occurs. /// </summary> private void ApiExceptionHandler( object sender, ApiExceptionEventArgs args ) { // Execute our callbacks. We don't handle exceptions since this is client code anyway. foreach( var callback in m_exceptionCallbacks ) callback( args.Message ); if( !m_config.ThrowExceptionOnApiFailure ) return; if( !(args.Exception is ApiException apiEx) ) { // If we got an EmsApiException already, then we should just rethrow that here. if( args.Exception is EmsApiException ) throw args.Exception; throw new EmsApiException( args.Exception.Message, args.Exception ); } // Note: This object is a Dto.V2.Error, but in that class the messageDetail // field is marked as required, so it will not deserialize if the details // are not there. In many cases the details are empty, so we parse the json // manually instead. JObject details = null; try { details = JObject.Parse( apiEx.Content ); } catch( Exception ) { } // We want the details if available. string message = null; if( details != null ) { message = details.GetValue( "messageDetail" )?.ToString(); if( string.IsNullOrEmpty( message ) ) message = details.GetValue( "message" )?.ToString(); } if( string.IsNullOrEmpty( message ) ) message = apiEx.Message; System.Diagnostics.Debug.WriteLine( "EMS API client encountered Refit.ApiException ({0}): {1}", args.ApiException.ReasonPhrase, message ); throw new EmsApiException( message, args.Exception ); } /// <summary> /// Executed when a API authentication fails. /// </summary> private void AuthenticationFailedHandler( object sender, AuthenticationFailedEventArgs args ) { // Execute our callbacks. We don't handle exceptions since this is client code anyway. foreach( var callback in m_authCallbacks ) callback( args.Message ); if( m_config.ThrowExceptionOnAuthFailure ) throw new EmsApiAuthenticationException( args.Message ); System.Diagnostics.Debug.WriteLine( "EMS API client encountered authentication failure: {0}", args.Message ); } /// <summary> /// Throws an exception if the given service configuration cannot be validated. /// </summary> private void ValidateConfigOrThrow( EmsApiServiceConfiguration config ) { if( !config.Validate( out string error ) ) throw new EmsApiConfigurationException( error ); } /// <summary> /// The callbacks to execute when authentication fails. /// </summary> private List<Action<string>> m_authCallbacks; /// <summary> /// The callbacks to execute when a low level API exception occurs. /// </summary> private List<Action<string>> m_exceptionCallbacks; /// <summary> /// A list of actions to perform when the service is disposed. /// </summary> private List<Action> m_cleanup; /// <summary> /// The configuration for the service. /// </summary> private EmsApiServiceConfiguration m_config; /// <summary> /// The message handler, which handles authentication and other needs. /// </summary> private MessageHandler m_messageHandler; /// <summary> /// The current http client. /// </summary> private HttpClient m_httpClient; /// <summary> /// The last API endpoint specified. This is used to track when the /// endpoint changes, since we need to do a more thorough reset when /// that happens, due to the fact that the refit implementation gets /// bound to the endpoint url. /// </summary> private string m_endpoint = string.Empty; } }