context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// using System; using System.Linq; using NUnit.Framework; using Realms; using ExplicitAttribute = NUnit.Framework.ExplicitAttribute; namespace Tests.Database { [TestFixture, Preserve(AllMembers = true)] internal class SimpleLINQtests : PeopleTestsBase { protected override void CustomSetUp() { base.CustomSetUp(); MakeThreePeople(); } [Test] public void CreateList() { var s0 = _realm.All<Person>().Where(p => p.Score == 42.42f).ToList(); Assert.That(s0.Count(), Is.EqualTo(1)); Assert.That(s0[0].Score, Is.EqualTo(42.42f)); var s1 = _realm.All<Person>().Where(p => p.Longitude < -70.0 && p.Longitude > -90.0).ToList(); Assert.That(s1[0].Email, Is.EqualTo("john@doe.com")); var s2 = _realm.All<Person>().Where(p => p.Longitude < 0).ToList(); Assert.That(s2.Count(), Is.EqualTo(2)); Assert.That(s2[0].Email, Is.EqualTo("john@doe.com")); Assert.That(s2[1].Email, Is.EqualTo("peter@jameson.net")); var s3 = _realm.All<Person>().Where(p => p.Email != string.Empty); Assert.That(s3.Count(), Is.EqualTo(3)); } [Test] public void CountWithNot() { var countSimpleNot = _realm.All<Person>().Where(p => !p.IsInteresting).Count(); Assert.That(countSimpleNot, Is.EqualTo(1)); var countSimpleNot2 = _realm.All<Person>().Count(p => !p.IsInteresting); Assert.That(countSimpleNot2, Is.EqualTo(1)); var countNotEqual = _realm.All<Person>().Where(p => !(p.Score == 42.42f)).Count(); Assert.That(countNotEqual, Is.EqualTo(2)); var countNotComplex = _realm.All<Person>().Where(p => !(p.Longitude < -70.0 && p.Longitude > -90.0)).Count(); Assert.That(countNotComplex, Is.EqualTo(2)); } [Test] public void CountFoundItems() { var r0 = _realm.All<Person>().Where(p => p.Score == 42.42f); var c0 = r0.Count(); // defer so can check in debugger if RealmResults.Count() evaluated correctly Assert.That(c0, Is.EqualTo(1)); var c1 = _realm.All<Person>().Where(p => p.Latitude <= 50).Count(); Assert.That(c1, Is.EqualTo(2)); var c2 = _realm.All<Person>().Where(p => p.IsInteresting).Count(); Assert.That(c2, Is.EqualTo(2)); var c3 = _realm.All<Person>().Where(p => p.FirstName == "John").Count(); Assert.That(c3, Is.EqualTo(2)); var c4 = _realm.All<Person>().Count(p => p.FirstName == "John"); Assert.That(c4, Is.EqualTo(2)); } [Test] public void CountFails() { var c0 = _realm.All<Person>().Where(p => p.Score == 3.14159f).Count(); Assert.That(c0, Is.EqualTo(0)); var c1 = _realm.All<Person>().Where(p => p.Latitude > 88).Count(); Assert.That(c1, Is.EqualTo(0)); var c3 = _realm.All<Person>().Where(p => p.FirstName == "Samantha").Count(); Assert.That(c3, Is.EqualTo(0)); } // Extension method rather than SQL-style LINQ // Also tests the Count on results, ElementOf, First and Single methods [Test] public void SearchComparingFloat() { var s0 = _realm.All<Person>().Where(p => p.Score == 42.42f); var s0l = s0.ToList(); Assert.That(s0.Count(), Is.EqualTo(1)); Assert.That(s0l[0].Score, Is.EqualTo(42.42f)); var s1 = _realm.All<Person>().Where(p => p.Score != 100.0f).ToList(); Assert.That(s1.Count, Is.EqualTo(2)); Assert.That(s1[0].Score, Is.EqualTo(-0.9907f)); Assert.That(s1[1].Score, Is.EqualTo(42.42f)); var s2 = _realm.All<Person>().Where(p => p.Score < 0).ToList(); Assert.That(s2.Count, Is.EqualTo(1)); Assert.That(s2[0].Score, Is.EqualTo(-0.9907f)); var s3 = _realm.All<Person>().Where(p => p.Score <= 42.42f).ToList(); Assert.That(s3.Count, Is.EqualTo(2)); Assert.That(s3[0].Score, Is.EqualTo(-0.9907f)); Assert.That(s3[1].Score, Is.EqualTo(42.42f)); var s4 = _realm.All<Person>().Where(p => p.Score > 99.0f).ToList(); Assert.That(s4.Count, Is.EqualTo(1)); Assert.That(s4[0].Score, Is.EqualTo(100.0f)); var s5 = _realm.All<Person>().Where(p => p.Score >= 100).ToList(); Assert.That(s5.Count, Is.EqualTo(1)); Assert.That(s5[0].Score, Is.EqualTo(100.0f)); } [Test] public void SearchComparingDouble() { var s0 = _realm.All<Person>().Where(p => p.Latitude == 40.7637286); Assert.That(s0.Count, Is.EqualTo(1)); Assert.That(s0.ToList()[0].Latitude, Is.EqualTo(40.7637286)); var s1 = _realm.All<Person>().Where(p => p.Latitude != 40.7637286).ToList(); Assert.That(s1.Count, Is.EqualTo(2)); Assert.That(s1[0].Latitude, Is.EqualTo(51.508530)); Assert.That(s1[1].Latitude, Is.EqualTo(37.7798657)); var s2 = _realm.All<Person>().Where(p => p.Latitude < 40).ToList(); Assert.That(s2.Count, Is.EqualTo(1)); Assert.That(s2[0].Latitude, Is.EqualTo(37.7798657)); var s3 = _realm.All<Person>().Where(p => p.Latitude <= 40.7637286).ToList(); Assert.That(s3.Count, Is.EqualTo(2)); Assert.That(s3[0].Latitude, Is.EqualTo(40.7637286)); Assert.That(s3[1].Latitude, Is.EqualTo(37.7798657)); var s4 = _realm.All<Person>().Where(p => p.Latitude > 50).ToList(); Assert.That(s4.Count, Is.EqualTo(1)); Assert.That(s4[0].Latitude, Is.EqualTo(51.508530)); var s5 = _realm.All<Person>().Where(p => p.Latitude >= 51.508530).ToList(); Assert.That(s5.Count, Is.EqualTo(1)); Assert.That(s5[0].Latitude, Is.EqualTo(51.508530)); } [Test] public void SearchComparingLong() { var equality = _realm.All<Person>().Where(p => p.Salary == 60000).ToArray(); Assert.That(equality.Length, Is.EqualTo(1)); Assert.That(equality[0].FullName, Is.EqualTo("John Doe")); var lessThan = _realm.All<Person>().Where(p => p.Salary < 50000).ToArray(); Assert.That(lessThan.Length, Is.EqualTo(1)); Assert.That(lessThan[0].FullName, Is.EqualTo("John Smith")); var lessOrEqualThan = _realm.All<Person>().Where(p => p.Salary <= 60000).ToArray(); Assert.That(lessOrEqualThan.Length, Is.EqualTo(2)); Assert.That(lessOrEqualThan.All(p => p.FirstName == "John"), Is.True); var greaterThan = _realm.All<Person>().Where(p => p.Salary > 80000).ToArray(); Assert.That(greaterThan.Length, Is.EqualTo(1)); Assert.That(greaterThan[0].FullName, Is.EqualTo("Peter Jameson")); var greaterOrEqualThan = _realm.All<Person>().Where(p => p.Salary >= 60000).ToArray(); Assert.That(greaterOrEqualThan.Length, Is.EqualTo(2)); Assert.That(greaterOrEqualThan.Any(p => p.FullName == "John Doe") && greaterOrEqualThan.Any(p => p.FullName == "Peter Jameson"), Is.True); var between = _realm.All<Person>().Where(p => p.Salary > 30000 && p.Salary < 87000).ToArray(); Assert.That(between.Length, Is.EqualTo(1)); Assert.That(between[0].FullName, Is.EqualTo("John Doe")); } [Test] public void SearchComparingString() { var equality = _realm.All<Person>().Where(p => p.LastName == "Smith").ToArray(); Assert.That(equality.Length, Is.EqualTo(1)); Assert.That(equality[0].FullName, Is.EqualTo("John Smith")); var contains = _realm.All<Person>().Where(p => p.FirstName.Contains("et")).ToArray(); Assert.That(contains.Length, Is.EqualTo(1)); Assert.That(contains[0].FullName, Is.EqualTo("Peter Jameson")); var startsWith = _realm.All<Person>().Where(p => p.Email.StartsWith("john@")).ToArray(); Assert.That(startsWith.Length, Is.EqualTo(2)); Assert.That(startsWith.All(p => p.FirstName == "John"), Is.True); var endsWith = _realm.All<Person>().Where(p => p.Email.EndsWith(".net")).ToArray(); Assert.That(endsWith.Length, Is.EqualTo(1)); Assert.That(endsWith[0].FullName, Is.EqualTo("Peter Jameson")); var @null = _realm.All<Person>().Where(p => p.OptionalAddress == null).ToArray(); Assert.That(@null[0].FullName, Is.EqualTo("Peter Jameson")); var empty = _realm.All<Person>().Where(p => p.OptionalAddress == string.Empty).ToArray(); Assert.That(empty[0].FullName, Is.EqualTo("John Doe")); var null_or_empty = _realm.All<Person>().Where(p => string.IsNullOrEmpty(p.OptionalAddress)); Assert.That(null_or_empty.Count(), Is.EqualTo(2)); } [Test] public void SearchComparingDateTimeOffset() { var d1960 = new DateTimeOffset(1960, 1, 1, 0, 0, 0, TimeSpan.Zero); var d1970 = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); var bdayJohnDoe = new DateTimeOffset(1963, 4, 14, 0, 0, 0, TimeSpan.Zero); var bdayPeterJameson = new DateTimeOffset(1989, 2, 25, 0, 0, 0, TimeSpan.Zero); var equality = _realm.All<Person>().Where(p => p.Birthday == bdayPeterJameson).ToArray(); Assert.That(equality.Length, Is.EqualTo(1)); Assert.That(equality[0].FullName, Is.EqualTo("Peter Jameson")); var lessThan = _realm.All<Person>().Where(p => p.Birthday < d1960).ToArray(); Assert.That(lessThan.Length, Is.EqualTo(1)); Assert.That(lessThan[0].FullName, Is.EqualTo("John Smith")); var lessOrEqualThan = _realm.All<Person>().Where(p => p.Birthday <= bdayJohnDoe).ToArray(); Assert.That(lessOrEqualThan.Length, Is.EqualTo(2)); Assert.That(lessOrEqualThan.All(p => p.FirstName == "John"), Is.True); var greaterThan = _realm.All<Person>().Where(p => p.Birthday > d1970).ToArray(); Assert.That(greaterThan.Length, Is.EqualTo(1)); Assert.That(greaterThan[0].FullName, Is.EqualTo("Peter Jameson")); var greaterOrEqualThan = _realm.All<Person>().Where(p => p.Birthday >= bdayJohnDoe).ToArray(); Assert.That(greaterOrEqualThan.Length, Is.EqualTo(2)); Assert.That(greaterOrEqualThan.Any(p => p.FullName == "John Doe") && greaterOrEqualThan.Any(p => p.FullName == "Peter Jameson"), Is.True); var between = _realm.All<Person>().Where(p => p.Birthday > d1960 && p.Birthday < d1970).ToArray(); Assert.That(between.Length, Is.EqualTo(1)); Assert.That(between[0].FullName, Is.EqualTo("John Doe")); } [Test] public void SearchComparingNullable() { var @null = _realm.All<Person>().Where(p => p.IsAmbivalent == null); Assert.That(@null.Single().FullName, Is.EqualTo("Peter Jameson")); var not_null = _realm.All<Person>().Where(p => p.IsAmbivalent != null); Assert.That(not_null.Count(), Is.EqualTo(2)); var @true = _realm.All<Person>().Where(p => p.IsAmbivalent == true); Assert.That(@true.Single().FullName, Is.EqualTo("John Smith")); var @false = _realm.All<Person>().Where(p => p.IsAmbivalent == false); Assert.That(@false.Single().FullName, Is.EqualTo("John Doe")); } [Test] public void SearchComparingByteArrays() { var deadbeef = new byte[] { 0xde, 0xad, 0xbe, 0xef }; var cafebabe = new byte[] { 0xca, 0xfe, 0xba, 0xbe }; var empty = new byte[0]; var equality = _realm.All<Person>().Where(p => p.PublicCertificateBytes == cafebabe); Assert.That(equality.Single().PublicCertificateBytes, Is.EqualTo(cafebabe)); var unequality = _realm.All<Person>().Where(p => p.PublicCertificateBytes != deadbeef); Assert.That(unequality.Count(), Is.EqualTo(2)); var emptyness = _realm.All<Person>().Where(p => p.PublicCertificateBytes == empty); Assert.That(emptyness, Is.Empty); // we should support this as well - see #570 // var @null = _realm.All<Person>().Where(p => p.PublicCertificateBytes == null); // Assert.That(@null.Count(), Is.EqualTo(1)); } [Test] public void SearchComparingChar() { _realm.Write(() => { _realm.Add(new PrimaryKeyCharObject { CharProperty = 'A' }); _realm.Add(new PrimaryKeyCharObject { CharProperty = 'B' }); _realm.Add(new PrimaryKeyCharObject { CharProperty = 'c' }); _realm.Add(new PrimaryKeyCharObject { CharProperty = 'a' }); }); var equality = _realm.All<PrimaryKeyCharObject>().Where(p => p.CharProperty == 'A').ToArray(); Assert.That(equality.Select(p => p.CharProperty), Is.EquivalentTo(new[] { 'A' })); var inequality = _realm.All<PrimaryKeyCharObject>().Where(p => p.CharProperty != 'c').ToArray(); Assert.That(inequality.Select(p => p.CharProperty), Is.EquivalentTo(new[] { 'A', 'B', 'a' })); var lessThan = _realm.All<PrimaryKeyCharObject>().Where(p => p.CharProperty < 'c').ToArray(); Assert.That(lessThan.Select(p => p.CharProperty), Is.EquivalentTo(new[] { 'A', 'B', 'a' })); var lessOrEqualThan = _realm.All<PrimaryKeyCharObject>().Where(p => p.CharProperty <= 'c').ToArray(); Assert.That(lessOrEqualThan.Select(p => p.CharProperty), Is.EquivalentTo(new[] { 'A', 'B', 'a', 'c' })); var greaterThan = _realm.All<PrimaryKeyCharObject>().Where(p => p.CharProperty > 'a').ToArray(); Assert.That(greaterThan.Select(p => p.CharProperty), Is.EquivalentTo(new[] { 'c' })); var greaterOrEqualThan = _realm.All<PrimaryKeyCharObject>().Where(p => p.CharProperty >= 'B').ToArray(); Assert.That(greaterOrEqualThan.Select(p => p.CharProperty), Is.EquivalentTo(new[] { 'B', 'a', 'c' })); var between = _realm.All<PrimaryKeyCharObject>().Where(p => p.CharProperty > 'A' && p.CharProperty < 'a').ToArray(); Assert.That(between.Select(p => p.CharProperty), Is.EquivalentTo(new[] { 'B' })); var missing = _realm.All<PrimaryKeyCharObject>().Where(p => p.CharProperty == 'X').ToArray(); Assert.That(missing.Length, Is.EqualTo(0)); } [Test] public void SearchComparingConstants() { // Verify that constants in LINQ work var equality = _realm.All<Person>().Where(p => p.Salary == Constants.SixtyThousandConstant).ToArray(); Assert.That(equality.Length, Is.EqualTo(1)); Assert.That(equality[0].FullName, Is.EqualTo("John Doe")); } [Test] public void SearchComparingStaticFields() { // Verify that static field in LINQ work var equality = _realm.All<Person>().Where(p => p.Salary == Constants.SixtyThousandField).ToArray(); Assert.That(equality.Length, Is.EqualTo(1)); Assert.That(equality[0].FullName, Is.EqualTo("John Doe")); } [Test] public void SearchComparingStaticProperties() { // Verify that static properties in LINQ work var equality = _realm.All<Person>().Where(p => p.Salary == Constants.SixtyThousandProperty).ToArray(); Assert.That(equality.Length, Is.EqualTo(1)); Assert.That(equality[0].FullName, Is.EqualTo("John Doe")); } [Test] public void SearchComparingInstanceFields() { var constants = new InstanceConstants(); // Verify that instance fields in LINQ work var equality = _realm.All<Person>().Where(p => p.Salary == constants.SixtyThousandField).ToArray(); Assert.That(equality.Length, Is.EqualTo(1)); Assert.That(equality[0].FullName, Is.EqualTo("John Doe")); } [Test] public void SearchComparingInstanceProperties() { var constants = new InstanceConstants(); // Verify that instance properties in LINQ work var equality = _realm.All<Person>().Where(p => p.Salary == constants.SixtyThousandProperty).ToArray(); Assert.That(equality.Length, Is.EqualTo(1)); Assert.That(equality[0].FullName, Is.EqualTo("John Doe")); } [Test] public void SearchComparingNestedInstanceFields() { var constants = new NestedConstants(); // Verify that nested instance fields in LINQ work var equality = _realm.All<Person>().Where(p => p.Salary == constants.InstanceConstants.SixtyThousandField).ToArray(); Assert.That(equality.Length, Is.EqualTo(1)); Assert.That(equality[0].FullName, Is.EqualTo("John Doe")); } [Test] public void SearchComparingNestedInstanceProperties() { var constants = new NestedConstants(); // Verify that nested instance properties in LINQ work var equality = _realm.All<Person>().Where(p => p.Salary == constants.InstanceConstants.SixtyThousandProperty).ToArray(); Assert.That(equality.Length, Is.EqualTo(1)); Assert.That(equality[0].FullName, Is.EqualTo("John Doe")); } [Test] public void SearchComparingObjects() { var rex = new Dog { Name = "Rex" }; var peter = new Owner { Name = "Peter", TopDog = rex }; var george = new Owner { Name = "George", TopDog = rex }; var sharo = new Dog { Name = "Sharo" }; var ivan = new Owner { Name = "Ivan", TopDog = sharo }; _realm.Write(() => { _realm.Add(peter); _realm.Add(george); _realm.Add(ivan); }); var rexOwners = _realm.All<Owner>().Where(o => o.TopDog == rex); Assert.That(rexOwners.Count(), Is.EqualTo(2)); var sharoOwners = _realm.All<Owner>().Where(o => o.TopDog != rex); Assert.That(sharoOwners.Count(), Is.EqualTo(1)); Assert.That(sharoOwners.Single().Name, Is.EqualTo("Ivan")); } [Test] public void StringSearch_Equals_CaseSensitivityTests() { MakeThreePatricks(); // case sensitive var equalequal_patrick = _realm.All<Person>().Where(p => p.FirstName == "patrick").Count(); Assert.That(equalequal_patrick, Is.EqualTo(2)); // case sensitive var notequal_patrick = _realm.All<Person>().Where(p => p.FirstName != "patrick").Count(); Assert.That(notequal_patrick, Is.EqualTo(1)); // case sensitive var equals_patrick = _realm.All<Person>().Where(p => p.FirstName.Equals("patrick")).Count(); Assert.That(equals_patrick, Is.EqualTo(2)); // case sensitive var notequals_patrick = _realm.All<Person>().Where(p => !p.FirstName.Equals("patrick")).Count(); Assert.That(notequals_patrick, Is.EqualTo(1)); // ignore case var equals_ignorecase_patrick = _realm.All<Person>().Where(p => p.FirstName.Equals("patrick", StringComparison.OrdinalIgnoreCase)).Count(); Assert.That(equals_ignorecase_patrick, Is.EqualTo(3)); // ignore case var notequals_ignorecase_patrick = _realm.All<Person>().Where(p => !p.FirstName.Equals("patrick", StringComparison.OrdinalIgnoreCase)).Count(); Assert.That(notequals_ignorecase_patrick, Is.EqualTo(0)); // case sensitive var equals_ordinal_patrick = _realm.All<Person>().Where(p => p.FirstName.Equals("patrick", StringComparison.Ordinal)).Count(); Assert.That(equals_ordinal_patrick, Is.EqualTo(2)); // case sensitive var equals_ordinal_Patrick = _realm.All<Person>().Where(p => p.FirstName.Equals("Patrick", StringComparison.Ordinal)).Count(); Assert.That(equals_ordinal_Patrick, Is.EqualTo(0)); // case sensitive var equals_ordinal_patRick = _realm.All<Person>().Where(p => p.FirstName.Equals("patRick", StringComparison.Ordinal)).Count(); Assert.That(equals_ordinal_patRick, Is.EqualTo(1)); // case sensitive var notequals_ordinal_patrick = _realm.All<Person>().Where(p => !p.FirstName.Equals("patrick", StringComparison.Ordinal)).Count(); Assert.That(notequals_ordinal_patrick, Is.EqualTo(1)); } [Test] public void StringSearch_StartsWith_CaseSensitivityTests() { MakeThreePatricks(); // case sensitive var startswith_patr = _realm.All<Person>().Where(p => p.FirstName.StartsWith("patr")).Count(); Assert.That(startswith_patr, Is.EqualTo(2)); // case sensitive var startswith_ordinal_patr = _realm.All<Person>().Where(p => p.FirstName.StartsWith("patr", StringComparison.Ordinal)).Count(); Assert.That(startswith_ordinal_patr, Is.EqualTo(2)); // ignore case var startswith_ignorecase_patr = _realm.All<Person>().Where(p => p.FirstName.StartsWith("patr", StringComparison.OrdinalIgnoreCase)).Count(); Assert.That(startswith_ignorecase_patr, Is.EqualTo(3)); } [Test] public void StringSearch_EndsWith_CaseSensitivityTests() { MakeThreePatricks(); // case sensitive var endswith_rick = _realm.All<Person>().Where(p => p.FirstName.EndsWith("rick")).Count(); Assert.That(endswith_rick, Is.EqualTo(2)); // case sensitive var endswith_ordinal_rick = _realm.All<Person>().Where(p => p.FirstName.EndsWith("rick", StringComparison.Ordinal)).Count(); Assert.That(endswith_ordinal_rick, Is.EqualTo(2)); // ignore case var endswith_ignorecase_rick = _realm.All<Person>().Where(p => p.FirstName.EndsWith("rick", StringComparison.OrdinalIgnoreCase)).Count(); Assert.That(endswith_ignorecase_rick, Is.EqualTo(3)); } [Test] public void StringSearch_Contains_CaseSensitivityTests() { MakeThreePatricks(); // case sensitive var contains_atri = _realm.All<Person>().Where(p => p.FirstName.Contains("atri")).Count(); Assert.That(contains_atri, Is.EqualTo(2)); // case sensitive var contains_ordinal_atri = _realm.All<Person>().Where(p => p.FirstName.Contains("atri", StringComparison.Ordinal)).Count(); Assert.That(contains_ordinal_atri, Is.EqualTo(2)); // ignore case var contains_ignorecase_atri = _realm.All<Person>().Where(p => p.FirstName.Contains("atri", StringComparison.OrdinalIgnoreCase)).Count(); Assert.That(contains_ignorecase_atri, Is.EqualTo(3)); } [Test] public void StringSearch_InvalidStringComparisonTests() { MakeThreePatricks(); Assert.That(() => { _realm.All<Person>().Where(p => p.FirstName.Equals("patrick", StringComparison.CurrentCulture)).Count(); }, Throws.TypeOf<NotSupportedException>()); Assert.That(() => { _realm.All<Person>().Where(p => p.FirstName.Equals("patrick", StringComparison.CurrentCultureIgnoreCase)).Count(); }, Throws.TypeOf<NotSupportedException>()); #if !WINDOWS_UWP Assert.That(() => { _realm.All<Person>().Where(p => p.FirstName.Equals("patrick", StringComparison.InvariantCulture)).Count(); }, Throws.TypeOf<NotSupportedException>()); Assert.That(() => { _realm.All<Person>().Where(p => p.FirstName.Equals("patrick", StringComparison.InvariantCultureIgnoreCase)).Count(); }, Throws.TypeOf<NotSupportedException>()); #endif Assert.That(() => { _realm.All<Person>().Where(p => p.FirstName.StartsWith("pat", StringComparison.CurrentCulture)).Count(); }, Throws.TypeOf<NotSupportedException>()); Assert.That(() => { _realm.All<Person>().Where(p => p.FirstName.EndsWith("rick", StringComparison.CurrentCulture)).Count(); }, Throws.TypeOf<NotSupportedException>()); Assert.That(() => { _realm.All<Person>().Where(p => p.FirstName.Contains("atri", StringComparison.CurrentCulture)).Count(); }, Throws.TypeOf<NotSupportedException>()); } [TestCaseSource(nameof(LikeTestValues))] public void StringSearch_LikeTests(string str, string pattern, bool caseSensitive, bool expected) { _realm.Write(() => _realm.Add(new IntPrimaryKeyWithValueObject { Id = 1, StringValue = str })); var regularQuery = _realm.All<IntPrimaryKeyWithValueObject>().Where(o => o.StringValue.Like(pattern, caseSensitive)); var negatedQuery = _realm.All<IntPrimaryKeyWithValueObject>().Where(o => !o.StringValue.Like(pattern, caseSensitive)); if (expected) { Assert.That(regularQuery.Count(), Is.EqualTo(1)); Assert.That(regularQuery.Single().Id, Is.EqualTo(1)); Assert.That(negatedQuery.Count(), Is.EqualTo(0)); } else { Assert.That(regularQuery.Count(), Is.EqualTo(0)); Assert.That(negatedQuery.Count(), Is.EqualTo(1)); Assert.That(negatedQuery.Single().Id, Is.EqualTo(1)); } } public static object[] LikeTestValues = { new object[] { "abc", "ab", false, false }, new object[] { "abc", string.Empty, false, false }, new object[] { string.Empty, string.Empty, true, true }, new object[] { string.Empty, string.Empty, false, true }, new object[] { null, string.Empty, true, false }, new object[] { null, string.Empty, false, false }, new object[] { string.Empty, null, true, false }, new object[] { string.Empty, null, false, false }, new object[] { null, null, true, true }, new object[] { null, null, false, true }, new object[] { null, "*", true, false }, new object[] { null, "*", false, false }, new object[] { string.Empty, "*", true, true }, new object[] { string.Empty, "*", false, true }, new object[] { string.Empty, "?", true, false }, new object[] { string.Empty, "?", false, false }, new object[] { "abc", "*a*", true, true }, new object[] { "abc", "*b*", true, true }, new object[] { "abc", "*c", true, true }, new object[] { "abc", "ab*", true, true }, new object[] { "abc", "*bc", true, true }, new object[] { "abc", "a*bc", true, true }, new object[] { "abc", "*abc*", true, true }, new object[] { "abc", "*d*", true, false }, new object[] { "abc", "aabc", true, false }, new object[] { "abc", "b*bc", true, false }, new object[] { "abc", "a??", true, true }, new object[] { "abc", "?b?", true, true }, new object[] { "abc", "*?c", true, true }, new object[] { "abc", "ab?", true, true }, new object[] { "abc", "?bc", true, true }, new object[] { "abc", "?d?", true, false }, new object[] { "abc", "?abc", true, false }, new object[] { "abc", "b?bc", true, false }, new object[] { "abc", "*C*", true, false }, new object[] { "abc", "*c*", false, true }, new object[] { "abc", "*C*", false, true }, }; [Test] public void AnySucceeds() { Assert.That(_realm.All<Person>().Where(p => p.Latitude > 50).Any()); Assert.That(_realm.All<Person>().Where(p => p.Score > 0).Any()); Assert.That(_realm.All<Person>().Where(p => p.IsInteresting == false).Any()); Assert.That(_realm.All<Person>().Where(p => p.FirstName == "John").Any()); } [Test] public void AnyFails() { Assert.False(_realm.All<Person>().Where(p => p.Latitude > 100).Any()); Assert.False(_realm.All<Person>().Where(p => p.Score > 50000).Any()); Assert.False(_realm.All<Person>().Where(p => p.FirstName == "Samantha").Any()); } [Test] public void SingleFailsToFind() { Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Single(p => p.Latitude > 100)); Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Where(p => p.Latitude > 100).Single()); Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Single(p => p.Score > 50000)); Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Single(p => p.FirstName == "Samantha")); } [Test] public void SingleFindsTooMany() { Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Where(p => p.Latitude == 50).Single()); Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Single(p => p.Score != 100.0f)); Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Single(p => p.FirstName == "John")); } [Test] public void SingleWorks() { var s0 = _realm.All<Person>().Single(p => p.Longitude < -70.0 && p.Longitude > -90.0); Assert.That(s0.Email, Is.EqualTo("john@doe.com")); var s1 = _realm.All<Person>().Where(p => p.Score == 100.0f).Single(); Assert.That(s1.Email, Is.EqualTo("john@doe.com")); var s2 = _realm.All<Person>().Single(p => p.FirstName == "Peter"); Assert.That(s2.FirstName, Is.EqualTo("Peter")); } [Test] public void SingleOrDefaultWorks() { var s0 = _realm.All<Person>().SingleOrDefault(p => p.Longitude < -70.0 && p.Longitude > -90.0); Assert.That(s0.Email, Is.EqualTo("john@doe.com")); var s1 = _realm.All<Person>().Where(p => p.Score == 100.0f).SingleOrDefault(); Assert.That(s1.Email, Is.EqualTo("john@doe.com")); var s2 = _realm.All<Person>().SingleOrDefault(p => p.FirstName == "Peter"); Assert.That(s2.FirstName, Is.EqualTo("Peter")); } [Test] public void SingleOrDefaultReturnsDefault() { var expectedDef = _realm.All<Person>().SingleOrDefault(p => p.FirstName == "Zaphod"); Assert.That(expectedDef, Is.Null); expectedDef = _realm.All<Person>().Where(p => p.FirstName == "Just Some Guy").SingleOrDefault(); Assert.That(expectedDef, Is.Null); } [Test] public void FirstFailsToFind() { Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().First(p => p.Latitude > 100)); Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Where(p => p.Latitude > 100).First()); Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().First(p => p.FirstName == "Samantha")); } [Test] public void FirstWorks() { var s0 = _realm.All<Person>().First(p => p.Longitude < -70.0 && p.Longitude > -90.0); Assert.That(s0.Email, Is.EqualTo("john@doe.com")); var s1 = _realm.All<Person>().Where(p => p.Score == 100.0f).First(); Assert.That(s1.Email, Is.EqualTo("john@doe.com")); var s2 = _realm.All<Person>().First(p => p.FirstName == "John"); Assert.That(s2.FirstName, Is.EqualTo("John")); } [Test] public void FirstOrDefaultWorks() { var s0 = _realm.All<Person>().FirstOrDefault(p => p.Longitude < -70.0 && p.Longitude > -90.0); Assert.That(s0.Email, Is.EqualTo("john@doe.com")); var s1 = _realm.All<Person>().Where(p => p.Score == 100.0f).FirstOrDefault(); Assert.That(s1.Email, Is.EqualTo("john@doe.com")); var s2 = _realm.All<Person>().FirstOrDefault(p => p.FirstName == "John"); Assert.That(s2.FirstName, Is.EqualTo("John")); } [Test] public void FirstOrDefaultReturnsDefault() { var expectedDef = _realm.All<Person>().FirstOrDefault(p => p.FirstName == "Zaphod"); Assert.That(expectedDef, Is.Null); expectedDef = _realm.All<Person>().Where(p => p.FirstName == "Just Some Guy").FirstOrDefault(); Assert.That(expectedDef, Is.Null); expectedDef = _realm.All<Person>() .Where(p => p.FirstName == "Just Some Guy") .OrderByDescending(p => p.FirstName) .FirstOrDefault(); Assert.That(expectedDef, Is.Null); } [Test] public void LastFailsToFind() { Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Last(p => p.Latitude > 100)); Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Where(p => p.Latitude > 100).Last()); Assert.Throws<InvalidOperationException>(() => _realm.All<Person>().Last(p => p.LastName == "Samantha")); } [Test] public void LastWorks() { var s0 = _realm.All<Person>().Last(p => p.Longitude < -70.0 && p.Longitude > -90.0); Assert.That(s0.Email, Is.EqualTo("john@doe.com")); // Last same as First when one match var s1 = _realm.All<Person>().Where(p => p.Score == 100.0f).Last(); Assert.That(s1.Email, Is.EqualTo("john@doe.com")); var s2 = _realm.All<Person>().Last(p => p.FirstName == "John"); Assert.That(s2.FirstName, Is.EqualTo("John")); // order not guaranteed in two items but know they match this } [Test] public void LastOrDefaultWorks() { var s0 = _realm.All<Person>().LastOrDefault(p => p.Longitude < -70.0 && p.Longitude > -90.0); Assert.That(s0.Email, Is.EqualTo("john@doe.com")); // Last same as First when one match var s1 = _realm.All<Person>().Where(p => p.Score == 100.0f).LastOrDefault(); Assert.That(s1.Email, Is.EqualTo("john@doe.com")); var s2 = _realm.All<Person>().LastOrDefault(p => p.FirstName == "John"); Assert.That(s2.FirstName, Is.EqualTo("John")); // order not guaranteed in two items but know they match this } [Test] public void LastOrDefaultReturnsDefault() { var expectedDef = _realm.All<Person>().LastOrDefault(p => p.FirstName == "Zaphod"); Assert.That(expectedDef, Is.Null); expectedDef = _realm.All<Person>().Where(p => p.FirstName == "Just Some Guy").LastOrDefault(); Assert.That(expectedDef, Is.Null); } [Test] public void ElementAtOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => _realm.All<Person>().Where(p => p.Latitude > 140).ElementAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => _realm.All<Person>().Where(p => p.FirstName == "Samantha").ElementAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => _realm.All<Person>().Where(p => p.FirstName == "Peter").ElementAt(10)); Assert.Throws<ArgumentOutOfRangeException>(() => _realm.All<Person>().ElementAt(10)); Assert.Throws<ArgumentOutOfRangeException>(() => _realm.All<Person>().ElementAt(-1)); } [Test] public void ElementAtInRange() { var s0 = _realm.All<Person>().Where(p => p.Longitude < -70.0 && p.Longitude > -90.0).ElementAt(0); Assert.That(s0.Email, Is.EqualTo("john@doe.com")); var s1 = _realm.All<Person>().Where(p => p.Score == 100.0f).ElementAt(0); Assert.That(s1.Email, Is.EqualTo("john@doe.com")); var s2 = _realm.All<Person>().Where(p => p.FirstName == "John").ElementAt(1); Assert.That(s2.FirstName, Is.EqualTo("John")); var s3 = _realm.All<Person>().ElementAt(2); Assert.That(s3.FirstName, Is.EqualTo("Peter")); } [Test] public void ElementAtOrDefaultInRange() { var s0 = _realm.All<Person>().Where(p => p.Longitude < -70.0 && p.Longitude > -90.0).ElementAtOrDefault(0); Assert.That(s0.Email, Is.EqualTo("john@doe.com")); var s1 = _realm.All<Person>().Where(p => p.Score == 100.0f).ElementAtOrDefault(0); Assert.That(s1.Email, Is.EqualTo("john@doe.com")); var s2 = _realm.All<Person>().Where(p => p.FirstName == "John").ElementAtOrDefault(1); Assert.That(s2.FirstName, Is.EqualTo("John")); var s3 = _realm.All<Person>().ElementAtOrDefault(2); Assert.That(s3.FirstName, Is.EqualTo("Peter")); } [Test] public void ElementAtOrDefaultReturnsDefault() { var expectedDef = _realm.All<Person>().Where(p => p.FirstName == "Just Some Guy").ElementAtOrDefault(0); Assert.That(expectedDef, Is.Null); } // note that DefaultIfEmpty returns a collection of one item [Test, Explicit("Currently broken and hard to implement")] public void DefaultIfEmptyReturnsDefault() { /* * This is comprehensively broken and awkward to fix in our current architecture. * Looking at the test code below, the Count is invoked on a RealmResults and directly * invokes its query handle, which of course has zero elements. * One posible approach is to toggle the RealmResults into a special state where * it acts as a generator for a single null pointer.* */ var expectCollectionOfOne = _realm.All<Person>().Where(p => p.FirstName == "Just Some Guy").DefaultIfEmpty(); Assert.That(expectCollectionOfOne.Count(), Is.EqualTo(1)); var expectedDef = expectCollectionOfOne.Single(); Assert.That(expectedDef, Is.Null); } [Test] public void ChainedWhereFirst() { var moderateScorers = _realm.All<Person>().Where(p => p.Score >= 20.0f && p.Score <= 100.0f); var johnScorer = moderateScorers.Where(p => p.FirstName == "John").First(); Assert.That(johnScorer, Is.Not.Null); Assert.That(johnScorer.Score, Is.EqualTo(100.0f)); Assert.That(johnScorer.FullName, Is.EqualTo("John Doe")); } [Test] public void ChainedWhereFirstWithPredicate() { var moderateScorers = _realm.All<Person>().Where(p => p.Score >= 20.0f && p.Score <= 100.0f); var johnScorer = moderateScorers.First(p => p.FirstName == "John"); Assert.That(johnScorer, Is.Not.Null); Assert.That(johnScorer.Score, Is.EqualTo(100.0f)); Assert.That(johnScorer.FullName, Is.EqualTo("John Doe")); } [Test] public void ChainedWhereAnyTrue() { var moderateScorers = _realm.All<Person>().Where(p => p.Score >= 20.0f && p.Score <= 100.0f); var hasJohn = moderateScorers.Where(p => p.FirstName == "John").Any(); Assert.That(hasJohn, Is.True); } [Test] public void ChainedWhereAnyFalse() { var moderateScorers = _realm.All<Person>().Where(p => p.Score >= 20.0f && p.Score <= 100.0f); var hasJohnSmith = moderateScorers.Where(p => p.LastName == "Smith").Any(); Assert.That(hasJohnSmith, Is.False); } [Test] public void ChainedWhereAnyWithPredicateTrue() { var moderateScorers = _realm.All<Person>().Where(p => p.Score >= 20.0f && p.Score <= 100.0f); var hasJohn = moderateScorers.Any(p => p.FirstName == "John"); Assert.That(hasJohn, Is.True); } [Test] public void ChainedWhereAnyWithPredicateFalse() { var moderateScorers = _realm.All<Person>().Where(p => p.Score >= 20.0f && p.Score <= 100.0f); var hasJohnSmith = moderateScorers.Any(p => p.LastName == "Smith"); Assert.That(hasJohnSmith, Is.False); } private void MakeThreePatricks() { _realm.Write(() => { _realm.RemoveAll<Person>(); _realm.Add(new Person { FirstName = "patRick" }); _realm.Add(new Person { FirstName = "patrick" }); _realm.Add(new Person { FirstName = "patrick" }); }); } private static class Constants { public const long SixtyThousandConstant = 60000; public static readonly long SixtyThousandField = 60000; public static long SixtyThousandProperty { get; } = 60000; } private class NestedConstants { public InstanceConstants InstanceConstants { get; } = new InstanceConstants(); } private class InstanceConstants { public readonly long SixtyThousandField = 60000; public long SixtyThousandProperty { get; } = 60000; } } }
namespace MathNet.Spatial.Units { using System; using System.Globalization; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using System.Xml.Serialization; /// <summary> /// An angle /// </summary> [Serializable] public struct Angle : IComparable<Angle>, IEquatable<Angle>, IFormattable, IXmlSerializable { /// <summary> /// The value in radians /// </summary> public readonly double Radians; private Angle(double radians) { Radians = radians; } /// <summary> /// Initializes a new instance of the Angle. /// </summary> /// <param name="radians"></param> /// <param name="unit"></param> public Angle(double radians, Radians unit) { Radians = radians; } /// <summary> /// Initializes a new instance of the Angle. /// </summary> /// <param name="value"></param> /// <param name="unit"></param> public Angle(double value, Degrees unit) { Radians = UnitConverter.ConvertFrom(value, unit); } /// <summary> /// The value in degrees /// </summary> public double Degrees { get { return UnitConverter.ConvertTo(Radians, AngleUnit.Degrees); } } /// <summary> /// Creates an Angle from its string representation /// </summary> /// <param name="s">The string representation of the angle</param> /// <returns></returns> public static Angle Parse(string s) { return UnitParser.Parse(s, From); } /// <summary> /// Creates a new instance of Angle. /// </summary> /// <param name="value"></param> /// <param name="unit"></param> public static Angle From<T>(double value, T unit) where T : IAngleUnit { return new Angle(UnitConverter.ConvertFrom(value, unit)); } /// <summary> /// Creates a new instance of Angle. /// </summary> /// <param name="value"></param> public static Angle FromDegrees(double value) { return new Angle(UnitConverter.ConvertFrom(value, AngleUnit.Degrees)); } /// <summary> /// Creates a new instance of Angle. /// </summary> /// <param name="value"></param> public static Angle FromRadians(double value) { return new Angle(value); } /// <summary> /// Indicates whether two <see cref="T:MathNet.Spatial.Units.Angle"/> instances are equal. /// </summary> /// <returns> /// true if the values of <paramref name="left"/> and <paramref name="right"/> are equal; otherwise, false. /// </returns> /// <param name="left">A <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> /// <param name="right">A <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> public static bool operator ==(Angle left, Angle right) { return left.Equals(right); } /// <summary> /// Indicates whether two <see cref="T:MathNet.Spatial.Units.Angle"/> instances are not equal. /// </summary> /// <returns> /// true if the values of <paramref name="left"/> and <paramref name="right"/> are not equal; otherwise, false. /// </returns> /// <param name="left">A <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> /// <param name="right">A <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> public static bool operator !=(Angle left, Angle right) { return !left.Equals(right); } /// <summary> /// Indicates whether a specified <see cref="T:MathNet.Spatial.Units.Angle"/> is less than another specified <see cref="T:MathNet.Spatial.Units.Angle"/>. /// </summary> /// <returns> /// true if the value of <paramref name="left"/> is less than the value of <paramref name="right"/>; otherwise, false. /// </returns> /// <param name="left">An <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> /// <param name="right">An <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> public static bool operator <(Angle left, Angle right) { return left.Radians < right.Radians; } /// <summary> /// Indicates whether a specified <see cref="T:MathNet.Spatial.Units.Angle"/> is greater than another specified <see cref="T:MathNet.Spatial.Units.Angle"/>. /// </summary> /// <returns> /// true if the value of <paramref name="left"/> is greater than the value of <paramref name="right"/>; otherwise, false. /// </returns> /// <param name="left">An <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> /// <param name="right">An <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> public static bool operator >(Angle left, Angle right) { return left.Radians > right.Radians; } /// <summary> /// Indicates whether a specified <see cref="T:MathNet.Spatial.Units.Angle"/> is less than or equal to another specified <see cref="T:MathNet.Spatial.Units.Angle"/>. /// </summary> /// <returns> /// true if the value of <paramref name="left"/> is less than or equal to the value of <paramref name="right"/>; otherwise, false. /// </returns> /// <param name="left">An <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> /// <param name="right">An <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> public static bool operator <=(Angle left, Angle right) { return left.Radians <= right.Radians; } /// <summary> /// Indicates whether a specified <see cref="T:MathNet.Spatial.Units.Angle"/> is greater than or equal to another specified <see cref="T:MathNet.Spatial.Units.Angle"/>. /// </summary> /// <returns> /// true if the value of <paramref name="left"/> is greater than or equal to the value of <paramref name="right"/>; otherwise, false. /// </returns> /// <param name="left">An <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> /// <param name="right">An <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> public static bool operator >=(Angle left, Angle right) { return left.Radians >= right.Radians; } /// <summary> /// Multiplies an instance of <see cref="T:MathNet.Spatial.Units.Angle"/> with <paramref name="left"/> and returns the result. /// </summary> /// <param name="right">An instance of <see cref="T:MathNet.Spatial.Units.Angle"/></param> /// <param name="left">An instance of <seealso cref="T:System.Double"/></param> /// <returns>Multiplies an instance of <see cref="T:MathNet.Spatial.Units.Angle"/> with <paramref name="left"/> and returns the result.</returns> public static Angle operator *(double left, Angle right) { return new Angle(left * right.Radians); } /// <summary> /// Multiplies an instance of <see cref="T:MathNet.Spatial.Units.Angle"/> with <paramref name="right"/> and returns the result. /// </summary> /// <param name="left">An instance of <see cref="T:MathNet.Spatial.Units.Angle"/></param> /// <param name="right">An instance of <seealso cref="T:System.Double"/></param> /// <returns>Multiplies an instance of <see cref="T:MathNet.Spatial.Units.Angle"/> with <paramref name="right"/> and returns the result.</returns> public static Angle operator *(Angle left, double right) { return new Angle(left.Radians * right); } /// <summary> /// Divides an instance of <see cref="T:MathNet.Spatial.Units.Angle"/> with <paramref name="right"/> and returns the result. /// </summary> /// <param name="left">An instance of <see cref="T:MathNet.Spatial.Units.Angle"/></param> /// <param name="right">An instance of <seealso cref="T:System.Double"/></param> /// <returns>Divides an instance of <see cref="T:MathNet.Spatial.Units.Angle"/> with <paramref name="right"/> and returns the result.</returns> public static Angle operator /(Angle left, double right) { return new Angle(left.Radians / right); } /// <summary> /// Adds two specified <see cref="T:MathNet.Spatial.Units.Angle"/> instances. /// </summary> /// <returns> /// An <see cref="T:MathNet.Spatial.Units.Angle"/> whose value is the sum of the values of <paramref name="left"/> and <paramref name="right"/>. /// </returns> /// <param name="left">A <see cref="T:MathNet.Spatial.Units.Angle"/>.</param> /// <param name="right">A TimeSpan.</param> public static Angle operator +(Angle left, Angle right) { return new Angle(left.Radians + right.Radians); } /// <summary> /// Subtracts an angle from another angle and returns the difference. /// </summary> /// <returns> /// An <see cref="T:MathNet.Spatial.Units.Angle"/> that is the difference /// </returns> /// <param name="left">A <see cref="T:MathNet.Spatial.Units.Angle"/> (the minuend).</param> /// <param name="right">A <see cref="T:MathNet.Spatial.Units.Angle"/> (the subtrahend).</param> public static Angle operator -(Angle left, Angle right) { return new Angle(left.Radians - right.Radians); } /// <summary> /// Returns an <see cref="T:MathNet.Spatial.Units.Angle"/> whose value is the negated value of the specified instance. /// </summary> /// <returns> /// An <see cref="T:MathNet.Spatial.Units.Angle"/> with the same numeric value as this instance, but the opposite sign. /// </returns> /// <param name="angle">A <see cref="T:MathNet.Spatial.Units.Angle"/></param> public static Angle operator -(Angle angle) { return new Angle(-1*angle.Radians); } /// <summary> /// Returns the specified instance of <see cref="T:MathNet.Spatial.Units.Angle"/>. /// </summary> /// <returns> /// Returns <paramref name="angle"/>. /// </returns> /// <param name="angle">A <see cref="T:MathNet.Spatial.Units.Angle"/></param> public static Angle operator +(Angle angle) { return angle; } public override string ToString() { return this.ToString((string)null, (IFormatProvider)NumberFormatInfo.CurrentInfo); } public string ToString(string format) { return this.ToString(format, (IFormatProvider)NumberFormatInfo.CurrentInfo); } public string ToString(IFormatProvider provider) { return this.ToString((string)null, (IFormatProvider)NumberFormatInfo.GetInstance(provider)); } public string ToString(string format, IFormatProvider formatProvider) { return this.ToString(format, formatProvider, AngleUnit.Radians); } public string ToString<T>(string format, IFormatProvider formatProvider, T unit) where T : IAngleUnit { var value = UnitConverter.ConvertTo(this.Radians, unit); return string.Format("{0}{1}", value.ToString(format, formatProvider), unit.ShortName); } /// <summary> /// Compares this instance to a specified <see cref="T:MathNet.Spatial.Units.Angle"/> object and returns an integer that indicates whether this <see cref="instance"/> is shorter than, equal to, or longer than the <see cref="T:MathNet.Spatial.Units.Angle"/> object. /// </summary> /// <returns> /// A signed number indicating the relative values of this instance and <paramref name="value"/>. /// /// Value /// /// Description /// /// A negative integer /// /// This instance is smaller than <paramref name="value"/>. /// /// Zero /// /// This instance is equal to <paramref name="value"/>. /// /// A positive integer /// /// This instance is larger than <paramref name="value"/>. /// /// </returns> /// <param name="value">A <see cref="T:MathNet.Spatial.Units.Angle"/> object to compare to this instance.</param> public int CompareTo(Angle value) { return this.Radians.CompareTo(value.Radians); } /// <summary> /// Returns a value indicating whether this instance is equal to a specified <see cref="T:MathNet.Spatial.Units.Angle"/> object. /// </summary> /// <returns> /// true if <paramref name="other"/> represents the same angle as this instance; otherwise, false. /// </returns> /// <param name="other">An <see cref="T:MathNet.Spatial.Units.Angle"/> object to compare with this instance.</param> public bool Equals(Angle other) { return this.Radians.Equals(other.Radians); } /// <summary> /// Returns a value indicating whether this instance is equal to a specified <see cref="T:MathNet.Spatial.Units.Angle"/> object within the given tolerance. /// </summary> /// <returns> /// true if <paramref name="other"/> represents the same angle as this instance; otherwise, false. /// </returns> /// <param name="other">An <see cref="T:MathNet.Spatial.Units.Angle"/> object to compare with this instance.</param> /// <param name="tolerance">The maximum difference for being considered equal</param> public bool Equals(Angle other, double tolerance) { return Math.Abs(this.Radians - other.Radians) < tolerance; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } return obj is Angle && this.Equals((Angle)obj); } public override int GetHashCode() { return this.Radians.GetHashCode(); } /// <summary> /// This method is reserved and should not be used. When implementing the IXmlSerializable interface, /// you should return null (Nothing in Visual Basic) from this method, and instead, /// if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class. /// </summary> /// <returns> /// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the /// <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> /// method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method. /// </returns> public XmlSchema GetSchema() { return null; } /// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized. </param> public void ReadXml(XmlReader reader) { reader.MoveToContent(); var e = (XElement)XNode.ReadFrom(reader); // Hacking set readonly fields here, can't think of a cleaner workaround XmlExt.SetReadonlyField(ref this, x => x.Radians, XmlConvert.ToDouble(e.ReadAttributeOrElementOrDefault("Value"))); } /// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized. </param> public void WriteXml(XmlWriter writer) { writer.WriteAttribute("Value", this.Radians); } /// <summary> /// Reads an instance of <see cref="T:MathNet.Spatial.Units.Angle"/> from the <paramref name="reader"/> /// </summary> /// <param name="reader"></param> /// <returns>An instance of <see cref="T:MathNet.Spatial.Units.Angle"/></returns> public static Angle ReadFrom(XmlReader reader) { var v = new Angle(); v.ReadXml(reader); return v; } } }
using XPT.Games.Generic.Constants; using XPT.Games.Generic.Maps; using XPT.Games.Twinion.Entities; namespace XPT.Games.Twinion.Maps { class TwMap12 : TwMap { public override int MapIndex => 12; public override int MapID => 0x0502; protected override int RandomEncounterChance => 15; protected override int RandomEncounterExtraCount => 1; protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 240, Direction.North); } protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "You enter a room where golems await you."); if (HasItem(player, type, doMsgs, MANARESTORE) || HasItem(player, type, doMsgs, GAUNTLETSOFMERCY)) { SetTreasure(player, type, doMsgs, MANDRAKESTAFF, SCROLLOFPROTECTION, 0, 0, 0, 1500); } else { SetTreasure(player, type, doMsgs, MANARESTORE, GAUNTLETSOFMERCY, 0, 0, 0, 3000); } if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 7); AddEncounter(player, type, doMsgs, 02, 8); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 7); AddEncounter(player, type, doMsgs, 02, 9); AddEncounter(player, type, doMsgs, 06, 9); } else { AddEncounter(player, type, doMsgs, 01, 7); AddEncounter(player, type, doMsgs, 02, 7); AddEncounter(player, type, doMsgs, 03, 8); AddEncounter(player, type, doMsgs, 05, 9); AddEncounter(player, type, doMsgs, 06, 9); } } protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "A bard sings his tale in the Cloister."); ShowText(player, type, doMsgs, "If true, continue south. If false, walk west."); } protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 93, Direction.South); } protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 165, Direction.North); } protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 69, Direction.West); } protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int race = 0; race = GetRace(player, type, doMsgs); switch (race) { case HUMAN: itemA = CORAL; break; default: itemA = OPAL; break; } if (HasItem(player, type, doMsgs, itemA) || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 1) { ShowText(player, type, doMsgs, "Tyndil is not in his office."); } else { GiveItem(player, type, doMsgs, itemA); ShowPortrait(player, type, doMsgs, GNOMEWIZARD); ShowText(player, type, doMsgs, "The crafty Tyndil invites you into his office."); ShowText(player, type, doMsgs, "'I offer a precious token in exchange for a mere glance at your map pieces. Thank you!'"); } } protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int race = 0; race = GetRace(player, type, doMsgs); switch (race) { case GREMLIN: case GNOME: itemA = CORAL; break; default: itemA = TOPAZ; break; } if (HasItem(player, type, doMsgs, itemA) || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 1) { ShowText(player, type, doMsgs, "Kalydor is not in his office."); } else { ShowPortrait(player, type, doMsgs, ORCKNIGHT); GiveItem(player, type, doMsgs, itemA); ShowText(player, type, doMsgs, "Kalydor's excitement is obvious."); ShowText(player, type, doMsgs, "'Take this precious bauble in exchange for one look at your map pieces. Ah, yes, very good!'"); } } protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "This portal will send you to the Main Entrance."); TeleportParty(player, type, doMsgs, 1, 1, 204, Direction.North); } protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int itemB = SHORTSWORD; int itemC = 0; int itemD = 0; int itemE = UNITYRING; int tile = 0; if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 0)) { if (GetPartyCount(player, type, doMsgs) == 1 && GetRace(player, type, doMsgs) == GNOME) { tile = GetTile(player, type, doMsgs); switch (tile) { case 116: itemA = EBONY; itemC = PEARL; itemD = OPAL; break; case 115: itemA = CORAL; itemC = LIFEJACKET; itemD = TOPAZ; break; case 114: itemA = OPAL; itemC = EBONY; itemD = SPIRITBOTTLE; break; case 113: itemA = PEARL; itemC = TOPAZ; itemD = EBONY; break; } if (UsedItem(player, type, ref doMsgs, itemB, itemC) || UsedItem(player, type, ref doMsgs, itemD, itemE)) { DamXit(player, type, doMsgs); } else if (UsedItem(player, type, ref doMsgs, itemA, itemA)) { ClearWallBlock(player, type, doMsgs, tile, Direction.West); SetWallItem(player, type, doMsgs, DOOR, tile, Direction.West); ShowText(player, type, doMsgs, "You've unlocked this door!"); ShowText(player, type, doMsgs, "Now proceed to the next lock."); } else { ShowText(player, type, doMsgs, "Use the correct token to unlock this door."); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "'Intrepid Gnome, if you have read the secret clues, use your tokens as the keys.'"); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "The doors remain open for you."); WallClear(player, type, doMsgs); } } protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int itemB = SHORTSWORD; int itemC = 0; int itemD = 0; int itemE = UNITYRING; int tile = 0; if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 0)) { if (GetPartyCount(player, type, doMsgs) == 1 && GetRace(player, type, doMsgs) == HALFLING) { tile = GetTile(player, type, doMsgs); switch (tile) { case 68: itemA = TOPAZ; itemC = CORAL; itemD = PEARL; break; case 67: itemA = PEARL; itemC = TOPAZ; itemD = EBONY; break; case 66: itemA = EBONY; itemC = PEARL; itemD = OPAL; break; case 65: itemA = OPAL; itemC = EBONY; itemD = SPIRITBOTTLE; break; } if (UsedItem(player, type, ref doMsgs, itemB, itemC) || UsedItem(player, type, ref doMsgs, itemD, itemE)) { DamXit(player, type, doMsgs); } else if (UsedItem(player, type, ref doMsgs, itemA, itemA)) { ClearWallBlock(player, type, doMsgs, tile, Direction.West); SetWallItem(player, type, doMsgs, DOOR, tile, Direction.West); ShowText(player, type, doMsgs, "You've unlocked this door!"); ShowText(player, type, doMsgs, "Now proceed to the next lock."); } else { ShowText(player, type, doMsgs, "Use the correct token to unlock this door."); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "'Worthy Halfling, if you have read the secret clues, use your tokens as the keys.'"); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "The doors remain open for you."); WallClear(player, type, doMsgs); } } protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int itemB = SHORTSWORD; int itemC = 0; int itemD = 0; int itemE = UNITYRING; int tile = 0; if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 0)) { if (GetPartyCount(player, type, doMsgs) == 1 && GetRace(player, type, doMsgs) == ORC) { tile = GetTile(player, type, doMsgs); switch (tile) { case 84: itemA = PEARL; itemC = TOPAZ; itemD = EBONY; break; case 83: itemA = OPAL; itemC = EBONY; itemD = SPIRITBOTTLE; break; case 82: itemA = CORAL; itemC = LIFEJACKET; itemD = TOPAZ; break; case 81: itemA = TOPAZ; itemC = CORAL; itemD = PEARL; break; } if (UsedItem(player, type, ref doMsgs, itemB, itemC) || UsedItem(player, type, ref doMsgs, itemD, itemE)) { DamXit(player, type, doMsgs); } else if (UsedItem(player, type, ref doMsgs, itemA, itemA)) { ClearWallBlock(player, type, doMsgs, tile, Direction.West); SetWallItem(player, type, doMsgs, DOOR, tile, Direction.West); ShowText(player, type, doMsgs, "You've unlocked this door!"); ShowText(player, type, doMsgs, "Now proceed to the next lock."); } else { ShowText(player, type, doMsgs, "Use the correct token to unlock this door."); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "'Brave Orc, if you have read the secret clues, use your tokens as the keys.'"); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "The doors remain open for you."); WallClear(player, type, doMsgs); } } protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int itemB = SHORTSWORD; int itemC = 0; int itemD = 0; int itemE = UNITYRING; int tile = 0; if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 0)) { if (GetPartyCount(player, type, doMsgs) == 1 && GetRace(player, type, doMsgs) == TROLL) { tile = GetTile(player, type, doMsgs); switch (tile) { case 100: itemA = OPAL; itemC = EBONY; itemD = SPIRITBOTTLE; break; case 99: itemA = CORAL; itemC = LIFEJACKET; itemD = TOPAZ; break; case 98: itemA = TOPAZ; itemC = CORAL; itemD = PEARL; break; case 97: itemA = PEARL; itemC = TOPAZ; itemD = EBONY; break; } if (UsedItem(player, type, ref doMsgs, itemB, itemC) || UsedItem(player, type, ref doMsgs, itemD, itemE)) { DamXit(player, type, doMsgs); } else if (UsedItem(player, type, ref doMsgs, itemA, itemA)) { ClearWallBlock(player, type, doMsgs, tile, Direction.West); SetWallItem(player, type, doMsgs, DOOR, tile, Direction.West); ShowText(player, type, doMsgs, "You've unlocked this door!"); ShowText(player, type, doMsgs, "Now proceed to the next lock."); } else { ShowText(player, type, doMsgs, "Use the correct token to unlock this door."); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "'Courageous Troll, if you have read the secret clues, use the tokens as the keys.'"); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "The doors remain open for you."); WallClear(player, type, doMsgs); } } protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, DWARFWIZARD); ShowText(player, type, doMsgs, "Xanith smiles as you draw near."); ShowText(player, type, doMsgs, "'I see you have mastered my riddles. To the west are some doors. Proceed alone through the door designated for your race.'"); ShowText(player, type, doMsgs, "'You must use your tokens in the order you were told, lest dire consequences befall you!'"); } protected override void FnEvent10(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Angel Fountain is in Cliffhanger. If true, continue south. If false, walk north."); } protected override void FnEvent11(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 3, 47, Direction.North); ShowText(player, type, doMsgs, "To the Graveyard."); } protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The Emerald Lockpick is exchanged for the Diamond Lockpick. If true, take the door to the south. If false, take the door to the east."); } protected override void FnEvent13(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 0)) { ShowPortrait(player, type, doMsgs, QUEENAEOWYN); ShowText(player, type, doMsgs, "Queen Aeowyn materializes in the room."); ShowText(player, type, doMsgs, "'Greetings, my Champion. Now we may bond these fragments together in this magical space.'"); ShowText(player, type, doMsgs, "Aeowyn examines the pieces closely and then arranges them on the floor in a peculiar order."); ShowText(player, type, doMsgs, "'Ahh...look!' You watch as the tokens release their magical properties and fuse together the map pieces."); ShowText(player, type, doMsgs, "'Now, take this map and use it as the key through the northern gateway opposite the Night Elves' portal in the Main Entrance."); ShowText(player, type, doMsgs, "Fare thee well.' The Queen then vanishes."); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE, 1); RemoveItem(player, type, doMsgs, LEATHERMAP); RemoveItem(player, type, doMsgs, PARCHMENTMAP); RemoveItem(player, type, doMsgs, SLATEMAP); RemoveItem(player, type, doMsgs, SNAKESKINMAP); RemoveItem(player, type, doMsgs, CORAL); RemoveItem(player, type, doMsgs, EBONY); RemoveItem(player, type, doMsgs, OPAL); RemoveItem(player, type, doMsgs, PEARL); RemoveItem(player, type, doMsgs, TOPAZ); GiveItem(player, type, doMsgs, WHOLEMAP); ModifyExperience(player, type, doMsgs, 2500000); } else { ShowText(player, type, doMsgs, "A quiet breezes wafts through this area."); } } protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) { DisableSpells(player, type, doMsgs); if (GetPartyCount(player, type, doMsgs) > 1) { int racecheck = 0; int tile = 0; racecheck = GetRace(player, type, doMsgs); switch (racecheck) { case HALFLING: tile = 68; break; case ORC: tile = 84; break; case TROLL: tile = 100; break; case GNOME: tile = 116; break; case ELF: tile = 132; break; case DWARF: tile = 148; break; case GREMLIN: tile = 164; break; case HUMAN: tile = 180; break; } ShowText(player, type, doMsgs, "You must enter here alone!"); TeleportParty(player, type, doMsgs, 5, 2, tile, Direction.East); } } protected override void FnEvent15(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int itemB = SHORTSWORD; int itemC = 0; int itemD = 0; int itemE = UNITYRING; int tile = 0; if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 0)) { if (GetPartyCount(player, type, doMsgs) == 1 && GetRace(player, type, doMsgs) == ELF) { tile = GetTile(player, type, doMsgs); switch (tile) { case 132: itemA = EBONY; itemC = PEARL; itemD = OPAL; break; case 131: itemA = OPAL; itemC = EBONY; itemD = SPIRITBOTTLE; break; case 130: itemA = CORAL; itemC = LIFEJACKET; itemD = TOPAZ; break; case 129: itemA = TOPAZ; itemC = CORAL; itemD = PEARL; break; } if (UsedItem(player, type, ref doMsgs, itemB, itemC) || UsedItem(player, type, ref doMsgs, itemD, itemE)) { DamXit(player, type, doMsgs); } else if (UsedItem(player, type, ref doMsgs, itemA, itemA)) { ClearWallBlock(player, type, doMsgs, tile, Direction.West); SetWallItem(player, type, doMsgs, DOOR, tile, Direction.West); ShowText(player, type, doMsgs, "You've unlocked this door!"); ShowText(player, type, doMsgs, "Proceed."); } else { ShowText(player, type, doMsgs, "Use the correct token to unlock this door."); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "'Fearless Elf, if you have read the secret clues, use your tokens as the keys.'"); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "The doors remain open for you."); WallClear(player, type, doMsgs); } } protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int itemB = SHORTSWORD; int itemC = 0; int itemD = 0; int itemE = UNITYRING; int tile = 0; if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 0)) { if (GetPartyCount(player, type, doMsgs) == 1 && GetRace(player, type, doMsgs) == DWARF) { tile = GetTile(player, type, doMsgs); switch (tile) { case 148: itemA = OPAL; itemC = EBONY; itemD = SPIRITBOTTLE; break; case 147: itemA = TOPAZ; itemC = CORAL; itemD = PEARL; break; case 146: itemA = EBONY; itemC = PEARL; itemD = OPAL; break; case 145: itemA = CORAL; itemC = LIFEJACKET; itemD = TOPAZ; break; } if (UsedItem(player, type, ref doMsgs, itemB, itemC) || UsedItem(player, type, ref doMsgs, itemD, itemE)) { DamXit(player, type, doMsgs); } else if (UsedItem(player, type, ref doMsgs, itemA, itemA)) { ClearWallBlock(player, type, doMsgs, tile, Direction.West); SetWallItem(player, type, doMsgs, DOOR, tile, Direction.West); ShowText(player, type, doMsgs, "You've unlocked this door!"); ShowText(player, type, doMsgs, "Proceed."); } else { ShowText(player, type, doMsgs, "Use the correct token to unlock this door."); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "'Valiant Dwarf, if you have read the secret clues, use your tokens as the keys.'"); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "The doors remain open for you."); WallClear(player, type, doMsgs); } } protected override void FnEvent17(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 3, 233, Direction.South); ShowText(player, type, doMsgs, "To the Graveyard."); } protected override void FnEvent18(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The Vault is found in Twinion Keep. If true, continue east. If false, walk west."); } protected override void FnEvent19(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 151, Direction.North); } protected override void FnEvent1A(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int itemB = SHORTSWORD; int itemC = 0; int itemD = 0; int itemE = UNITYRING; int tile = 0; if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 0)) { if (GetPartyCount(player, type, doMsgs) == 1 && GetRace(player, type, doMsgs) == GREMLIN) { tile = GetTile(player, type, doMsgs); switch (tile) { case 164: itemA = PEARL; itemC = TOPAZ; itemD = EBONY; break; case 163: itemA = EBONY; itemC = PEARL; itemD = OPAL; break; case 162: itemA = OPAL; itemC = EBONY; itemD = SPIRITBOTTLE; break; case 161: itemA = CORAL; itemC = LIFEJACKET; itemD = TOPAZ; break; } if (UsedItem(player, type, ref doMsgs, itemB, itemC) || UsedItem(player, type, ref doMsgs, itemD, itemE)) { DamXit(player, type, doMsgs); } else if (UsedItem(player, type, ref doMsgs, itemA, itemA)) { ClearWallBlock(player, type, doMsgs, tile, Direction.West); SetWallItem(player, type, doMsgs, DOOR, tile, Direction.West); ShowText(player, type, doMsgs, "You've unlocked this door!"); ShowText(player, type, doMsgs, "Proceed."); } else { ShowText(player, type, doMsgs, "Use the correct token to unlock this door."); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "'Hardy Gremlin, if you have read the secret clues, use your tokens as the keys.'"); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "The doors remain open for you."); WallClear(player, type, doMsgs); } } protected override void FnEvent1B(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int itemB = SHORTSWORD; int itemC = 0; int itemD = 0; int itemE = UNITYRING; int tile = 0; if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 0)) { if (GetPartyCount(player, type, doMsgs) == 1 && GetRace(player, type, doMsgs) == HUMAN) { tile = GetTile(player, type, doMsgs); switch (tile) { case 180: itemA = CORAL; itemC = LIFEJACKET; itemD = TOPAZ; break; case 179: itemA = TOPAZ; itemC = CORAL; itemD = PEARL; break; case 178: itemA = PEARL; itemC = TOPAZ; itemD = EBONY; break; case 177: itemA = EBONY; itemC = PEARL; itemD = OPAL; break; } if (UsedItem(player, type, ref doMsgs, itemB, itemC) || UsedItem(player, type, ref doMsgs, itemD, itemE)) { DamXit(player, type, doMsgs); } else if (UsedItem(player, type, ref doMsgs, itemA, itemA)) { ClearWallBlock(player, type, doMsgs, tile, Direction.West); SetWallItem(player, type, doMsgs, DOOR, tile, Direction.West); ShowText(player, type, doMsgs, "You've unlocked this door!"); ShowText(player, type, doMsgs, "Proceed."); } else { ShowText(player, type, doMsgs, "Use the correct token to unlock this door."); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "'Adventurous Human, if you have read the secret clues, use the tokens as the keys.'"); WallBlock(player, type, doMsgs); } } else { ShowText(player, type, doMsgs, "The doors remain open for you."); WallClear(player, type, doMsgs); } } protected override void FnEvent1C(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "To go back and search for your clues, exit here."); } protected override void FnEvent1E(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 33, Direction.North); } protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The musty smell of old maps is overpowering. You sense your mana being leeched away."); ModifyMana(player, type, doMsgs, - 200); } protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The only way to Race Track is from Rat Race. If true, continue north. If false, walk east."); } protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 194, Direction.East); } protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 59, Direction.South); } protected override void FnEvent2F(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Harmonics should visit the Tool Shed for a reward. If true, continue west. If false, walk east."); } protected override void FnEvent34(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Smug owns a Pawn Shop. If true, continue west. If false, walk south."); } protected override void FnEvent39(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "A book on the table reads, 'Futility is the price you pay for returning to the Cartography Shop ere you know the riddles' answers.'"); } protected override void FnEvent3A(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "A path of correct answers will lead you directly to the Cartographer."); } protected override void FnEvent3C(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 45, Direction.South); } protected override void FnEvent3D(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 8 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) { ShowText(player, type, doMsgs, "A secret door is revealed."); SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); WallClear(player, type, doMsgs); } else { WallBlock(player, type, doMsgs); } } protected override void FnEvent3E(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 35, Direction.West); } protected override void FnEvent3F(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int race = 0; race = GetRace(player, type, doMsgs); switch (race) { case ORC: case TROLL: itemA = CORAL; break; default: itemA = EBONY; break; } if (HasItem(player, type, doMsgs, itemA) || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 1) { ShowText(player, type, doMsgs, "Dabelais is not in his office."); } else { GiveItem(player, type, doMsgs, itemA); ShowPortrait(player, type, doMsgs, ELFCLERIC); ShowText(player, type, doMsgs, "Dabelais looks up and says, 'Accept this token as payment for showing me your map pieces.'"); } } protected override void FnEvent41(TwPlayerServer player, MapEventType type, bool doMsgs) { int itemA = 0; int race = 0; race = GetRace(player, type, doMsgs); switch (race) { case DWARF: case ELF: itemA = CORAL; break; default: itemA = PEARL; break; } if (HasItem(player, type, doMsgs, itemA) || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 1) { ShowText(player, type, doMsgs, "Syrene is not in her office."); } else { ShowPortrait(player, type, doMsgs, ORCRANGER); GiveItem(player, type, doMsgs, itemA); ShowText(player, type, doMsgs, "Syrene greets you. 'Adventurers, I offer a token for a glance at your map pieces.'"); } } protected override void FnEvent42(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Unity Fountain is found in Rat Race. If true, continue east. If false, walk west."); } protected override void FnEvent43(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Fellowship Fountain is found in the Armory. If true, continue south. If false, walk north."); } protected override void FnEvent44(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 15, Direction.South); } protected override void FnEvent45(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 5, 2, 88, Direction.South); } protected override void FnEvent46(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "To the Graveyard."); TeleportParty(player, type, doMsgs, 5, 3, 225, Direction.West); } protected override void FnEvent47(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, FOUNTAIN); if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.NSTAR) == 1) { ShowText(player, type, doMsgs, "The twinkling waters of NorthStar Fountain restore your mana."); ModifyMana(player, type, doMsgs, 10000); } else { ModifyMana(player, type, doMsgs, 10000); ModAttribute(player, type, doMsgs, INITIATIVE, 2); ModAttribute(player, type, doMsgs, STRENGTH, 1); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.NSTAR, 1); ShowText(player, type, doMsgs, "The twinkling waters of NorthStar Fountain restore your mana and increase your Strength and Initiative."); } } protected override void FnEvent4B(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 26); AddEncounter(player, type, doMsgs, 02, 31); } else { AddEncounter(player, type, doMsgs, 01, 27); AddEncounter(player, type, doMsgs, 02, 27); AddEncounter(player, type, doMsgs, 03, 31); AddEncounter(player, type, doMsgs, 06, 30); } } protected override void FnEvent4D(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 6); AddEncounter(player, type, doMsgs, 02, 7); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 6); AddEncounter(player, type, doMsgs, 02, 6); AddEncounter(player, type, doMsgs, 03, 7); AddEncounter(player, type, doMsgs, 04, 40); } else { AddEncounter(player, type, doMsgs, 01, 9); AddEncounter(player, type, doMsgs, 02, 9); AddEncounter(player, type, doMsgs, 03, 25); AddEncounter(player, type, doMsgs, 04, 25); AddEncounter(player, type, doMsgs, 05, 11); } } protected override void FnEvent4F(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 35); AddEncounter(player, type, doMsgs, 02, 27); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 35); AddEncounter(player, type, doMsgs, 02, 36); AddEncounter(player, type, doMsgs, 03, 28); } else { AddEncounter(player, type, doMsgs, 01, 35); AddEncounter(player, type, doMsgs, 02, 36); AddEncounter(player, type, doMsgs, 03, 29); AddEncounter(player, type, doMsgs, 04, 30); } } protected override void FnEvent50(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 6); AddEncounter(player, type, doMsgs, 02, 36); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 6); AddEncounter(player, type, doMsgs, 02, 5); AddEncounter(player, type, doMsgs, 03, 14); AddEncounter(player, type, doMsgs, 05, 32); } else { AddEncounter(player, type, doMsgs, 01, 8); AddEncounter(player, type, doMsgs, 02, 8); AddEncounter(player, type, doMsgs, 03, 25); AddEncounter(player, type, doMsgs, 04, 25); AddEncounter(player, type, doMsgs, 05, 32); AddEncounter(player, type, doMsgs, 06, 32); } } private void DamXit(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "You failed to use the correct item."); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs)); } private void WallBlock(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } private void WallClear(TwPlayerServer player, MapEventType type, bool doMsgs) { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations for operating on Azure SQL Server Active /// Directory Administrators. Contains operations to: Create, Retrieve, /// Update, and Delete Azure SQL Server Active Directory Administrators. /// </summary> internal partial class ServerAdministratorOperations : IServiceOperations<SqlManagementClient>, IServerAdministratorOperations { /// <summary> /// Initializes a new instance of the ServerAdministratorOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServerAdministratorOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Begins creating a new Azure SQL Server Active Directory /// Administrator or updating an existing Azure SQL Server Active /// Directory Administrator. To determine the status of the operation /// call GetServerAdministratorOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server to which the Azure SQL /// Server Active Directory administrator belongs /// </param> /// <param name='administratorName'> /// Required. The name of the Azure SQL Server Active Directory /// Administrator. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating an /// Active Directory Administrator. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure SQL Server Active Directory /// Administrator operations. /// </returns> public async Task<ServerAdministratorCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string administratorName, ServerAdministratorCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (administratorName == null) { throw new ArgumentNullException("administratorName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.AdministratorType == null) { throw new ArgumentNullException("parameters.Properties.AdministratorType"); } if (parameters.Properties.Login == null) { throw new ArgumentNullException("parameters.Properties.Login"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("administratorName", administratorName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/administrators/"; url = url + Uri.EscapeDataString(administratorName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject serverAdministratorCreateOrUpdateParametersValue = new JObject(); requestDoc = serverAdministratorCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); serverAdministratorCreateOrUpdateParametersValue["properties"] = propertiesValue; propertiesValue["login"] = parameters.Properties.Login; propertiesValue["sid"] = parameters.Properties.Sid.ToString(); propertiesValue["administratorType"] = parameters.Properties.AdministratorType; propertiesValue["tenantId"] = parameters.Properties.TenantId.ToString(); requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerAdministratorCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerAdministratorCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } ServerAdministrator serverAdministratorInstance = new ServerAdministrator(); result.ServerAdministrator = serverAdministratorInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ServerAdministratorProperties propertiesInstance = new ServerAdministratorProperties(); serverAdministratorInstance.Properties = propertiesInstance; JToken administratorTypeValue = propertiesValue2["administratorType"]; if (administratorTypeValue != null && administratorTypeValue.Type != JTokenType.Null) { string administratorTypeInstance = ((string)administratorTypeValue); propertiesInstance.AdministratorType = administratorTypeInstance; } JToken loginValue = propertiesValue2["login"]; if (loginValue != null && loginValue.Type != JTokenType.Null) { string loginInstance = ((string)loginValue); propertiesInstance.Login = loginInstance; } JToken sidValue = propertiesValue2["sid"]; if (sidValue != null && sidValue.Type != JTokenType.Null) { Guid sidInstance = Guid.Parse(((string)sidValue)); propertiesInstance.Sid = sidInstance; } JToken tenantIdValue = propertiesValue2["tenantId"]; if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null) { Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue)); propertiesInstance.TenantId = tenantIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverAdministratorInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverAdministratorInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverAdministratorInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverAdministratorInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverAdministratorInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Begins deleting an existing Azure SQL Server Active Directory /// Administrator.To determine the status of the operation call /// GetServerAdministratorDeleteOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server to which the Azure SQL /// Server Active Directory administrator belongs /// </param> /// <param name='administratorName'> /// Required. The name of the Azure SQL Server Active Directory /// Administrator. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure SQL Server Active Directory /// administrator delete operations. /// </returns> public async Task<ServerAdministratorDeleteResponse> BeginDeleteAsync(string resourceGroupName, string serverName, string administratorName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (administratorName == null) { throw new ArgumentNullException("administratorName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("administratorName", administratorName); TracingAdapter.Enter(invocationId, this, "BeginDeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/administrators/"; url = url + Uri.EscapeDataString(administratorName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerAdministratorDeleteResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerAdministratorDeleteResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Creates a new Azure SQL Server Active Directory Administrator or /// updates an existing Azure SQL Server Active Directory /// Administrator. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server on which the Azure SQL /// Server Active Directory Administrator is hosted. /// </param> /// <param name='administratorName'> /// Required. The name of the Azure SQL Server Active Directory /// Administrator to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Server /// Administrator. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure SQL Server Active Directory /// Administrator operations. /// </returns> public async Task<ServerAdministratorCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string administratorName, ServerAdministratorCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { SqlManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("administratorName", administratorName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ServerAdministratorCreateOrUpdateResponse response = await client.ServerAdministrators.BeginCreateOrUpdateAsync(resourceGroupName, serverName, administratorName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); ServerAdministratorCreateOrUpdateResponse result = await client.ServerAdministrators.GetServerAdministratorOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.ServerAdministrators.GetServerAdministratorOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Deletes an existing Azure SQL Server Active Directory Administrator. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server to which the Azure SQL /// Server Active Directory administrator belongs /// </param> /// <param name='administratorName'> /// Required. The name of the Azure SQL Server Active Directory /// Administrator to be operated on (Updated or created). /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure SQL Server Active Directory /// administrator delete operations. /// </returns> public async Task<ServerAdministratorDeleteResponse> DeleteAsync(string resourceGroupName, string serverName, string administratorName, CancellationToken cancellationToken) { SqlManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("administratorName", administratorName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ServerAdministratorDeleteResponse response = await client.ServerAdministrators.BeginDeleteAsync(resourceGroupName, serverName, administratorName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); ServerAdministratorDeleteResponse result = await client.ServerAdministrators.GetServerAdministratorDeleteOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.ServerAdministrators.GetServerAdministratorDeleteOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Returns an Azure SQL Server Administrator. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server to which the Azure SQL /// Server Active Directory administrator belongs. /// </param> /// <param name='administratorName'> /// Required. The name of the Azure SQL Server Active Directory /// Administrator. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a Get Azure SQL Server Active Directory /// Administrators request. /// </returns> public async Task<ServerAdministratorGetResponse> GetAsync(string resourceGroupName, string serverName, string administratorName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (administratorName == null) { throw new ArgumentNullException("administratorName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("administratorName", administratorName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/administrators/"; url = url + Uri.EscapeDataString(administratorName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerAdministratorGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerAdministratorGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ServerAdministrator administratorInstance = new ServerAdministrator(); result.Administrator = administratorInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerAdministratorProperties propertiesInstance = new ServerAdministratorProperties(); administratorInstance.Properties = propertiesInstance; JToken administratorTypeValue = propertiesValue["administratorType"]; if (administratorTypeValue != null && administratorTypeValue.Type != JTokenType.Null) { string administratorTypeInstance = ((string)administratorTypeValue); propertiesInstance.AdministratorType = administratorTypeInstance; } JToken loginValue = propertiesValue["login"]; if (loginValue != null && loginValue.Type != JTokenType.Null) { string loginInstance = ((string)loginValue); propertiesInstance.Login = loginInstance; } JToken sidValue = propertiesValue["sid"]; if (sidValue != null && sidValue.Type != JTokenType.Null) { Guid sidInstance = Guid.Parse(((string)sidValue)); propertiesInstance.Sid = sidInstance; } JToken tenantIdValue = propertiesValue["tenantId"]; if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null) { Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue)); propertiesInstance.TenantId = tenantIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); administratorInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); administratorInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); administratorInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); administratorInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); administratorInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the status of an Azure SQL Server Active Directory /// Administrator delete operation. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure SQL Server Active Directory /// administrator delete operations. /// </returns> public async Task<ServerAdministratorDeleteResponse> GetServerAdministratorDeleteOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetServerAdministratorDeleteOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerAdministratorDeleteResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerAdministratorDeleteResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the status of an Azure SQL Server Active Directory /// Administrator create or update operation. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure SQL Server Active Directory /// Administrator operations. /// </returns> public async Task<ServerAdministratorCreateOrUpdateResponse> GetServerAdministratorOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetServerAdministratorOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerAdministratorCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerAdministratorCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } ServerAdministrator serverAdministratorInstance = new ServerAdministrator(); result.ServerAdministrator = serverAdministratorInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerAdministratorProperties propertiesInstance = new ServerAdministratorProperties(); serverAdministratorInstance.Properties = propertiesInstance; JToken administratorTypeValue = propertiesValue["administratorType"]; if (administratorTypeValue != null && administratorTypeValue.Type != JTokenType.Null) { string administratorTypeInstance = ((string)administratorTypeValue); propertiesInstance.AdministratorType = administratorTypeInstance; } JToken loginValue = propertiesValue["login"]; if (loginValue != null && loginValue.Type != JTokenType.Null) { string loginInstance = ((string)loginValue); propertiesInstance.Login = loginInstance; } JToken sidValue = propertiesValue["sid"]; if (sidValue != null && sidValue.Type != JTokenType.Null) { Guid sidInstance = Guid.Parse(((string)sidValue)); propertiesInstance.Sid = sidInstance; } JToken tenantIdValue = propertiesValue["tenantId"]; if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null) { Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue)); propertiesInstance.TenantId = tenantIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverAdministratorInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverAdministratorInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverAdministratorInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverAdministratorInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverAdministratorInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns a list of Azure SQL Server Administrators. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server to which the Azure SQL /// Server Active Directory administrators belongs. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a List Azure SQL Active Directory /// Administrators request. /// </returns> public async Task<ServerAdministratorListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/administrators"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerAdministratorListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerAdministratorListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ServerAdministrator serverAdministratorInstance = new ServerAdministrator(); result.Administrators.Add(serverAdministratorInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerAdministratorProperties propertiesInstance = new ServerAdministratorProperties(); serverAdministratorInstance.Properties = propertiesInstance; JToken administratorTypeValue = propertiesValue["administratorType"]; if (administratorTypeValue != null && administratorTypeValue.Type != JTokenType.Null) { string administratorTypeInstance = ((string)administratorTypeValue); propertiesInstance.AdministratorType = administratorTypeInstance; } JToken loginValue = propertiesValue["login"]; if (loginValue != null && loginValue.Type != JTokenType.Null) { string loginInstance = ((string)loginValue); propertiesInstance.Login = loginInstance; } JToken sidValue = propertiesValue["sid"]; if (sidValue != null && sidValue.Type != JTokenType.Null) { Guid sidInstance = Guid.Parse(((string)sidValue)); propertiesInstance.Sid = sidInstance; } JToken tenantIdValue = propertiesValue["tenantId"]; if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null) { Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue)); propertiesInstance.TenantId = tenantIdInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverAdministratorInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverAdministratorInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverAdministratorInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverAdministratorInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverAdministratorInstance.Tags.Add(tagsKey, tagsValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record.Chart { using System; using System.Text; using NPOI.Util; /** * Describes a chart sheet properties record. * NOTE: This source is automatically generated please do not modify this file. Either subclass or * Remove the record in src/records/definitions. * @author Glen Stampoultzis (glens at apache.org) */ /// <summary> /// specifies properties of a chart as defined by the Chart Sheet Substream ABNF /// </summary> public class ShtPropsRecord : StandardRecord { public const short sid = 0x1044; private short field_1_flags; private BitField manSerAlloc = BitFieldFactory.GetInstance(0x1); private BitField plotVisibleOnly = BitFieldFactory.GetInstance(0x2); private BitField doNotSizeWithWindow = BitFieldFactory.GetInstance(0x4); private BitField manPlotArea = BitFieldFactory.GetInstance(0x8); private BitField alwaysAutoPlotArea = BitFieldFactory.GetInstance(0x10); private byte field_2_mdBlank; private byte field_3_reserved; public const byte EMPTY_NOT_PLOTTED = 0; public const byte EMPTY_ZERO = 1; public const byte EMPTY_INTERPOLATED = 2; public ShtPropsRecord() { } /** * Constructs a SheetProperties record and Sets its fields appropriately. * * @param in the RecordInputstream to Read the record from */ public ShtPropsRecord(RecordInputStream in1) { field_1_flags = in1.ReadShort(); field_2_mdBlank = (byte)in1.ReadByte(); field_3_reserved = (byte)in1.ReadByte(); } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[SHTPROPS]\n"); buffer.Append(" .flags = ") .Append("0x").Append(HexDump.ToHex(Flags)) .Append(" (").Append(Flags).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .chartTypeManuallyFormatted = ").Append(IsManSerAlloc).Append('\n'); buffer.Append(" .plotVisibleOnly = ").Append(IsPlotVisibleOnly).Append('\n'); buffer.Append(" .doNotSizeWithWindow = ").Append(IsNotSizeWithWindow).Append('\n'); buffer.Append(" .defaultPlotDimensions = ").Append(IsManPlotArea).Append('\n'); buffer.Append(" .autoPlotArea = ").Append(IsAlwaysAutoPlotArea).Append('\n'); buffer.Append(" .empty = ") .Append("0x").Append(HexDump.ToHex(Blank)) .Append(" (").Append(Blank).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append("[/SHTPROPS]\n"); return buffer.ToString(); } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(field_1_flags); out1.WriteByte(field_2_mdBlank); out1.WriteByte(0); //reserved field } /** * Size of record (exluding 4 byte header) */ protected override int DataSize { get { return 2 + 2; } } public override short Sid { get { return sid; } } public override Object Clone() { ShtPropsRecord rec = new ShtPropsRecord(); rec.field_1_flags = field_1_flags; rec.field_2_mdBlank = field_2_mdBlank; rec.field_3_reserved = field_3_reserved; return rec; } /** * Get the flags field for the SheetProperties record. */ public short Flags { get { return field_1_flags; } set { this.field_1_flags = value; } } /** * Get the empty field for the SheetProperties record. * * @return One of * EMPTY_NOT_PLOTTED * EMPTY_ZERO * EMPTY_INTERPOLATED */ /// <summary> /// specifies how the empty cells are plotted be a value from the following table: /// 0x00 Empty cells are not plotted. /// 0x01 Empty cells are plotted as zero. /// 0x02 Empty cells are plotted as interpolated. /// </summary> public byte Blank { get { return field_2_mdBlank; } set { this.field_2_mdBlank = value; } } /// <summary> /// whether series are automatically allocated for the chart. /// </summary> public bool IsManSerAlloc { get { return manSerAlloc.IsSet(field_1_flags); } set { field_1_flags = manSerAlloc.SetShortBoolean(field_1_flags, value); } } /// <summary> /// whether to plot visible cells only. /// </summary> public bool IsPlotVisibleOnly { get { return plotVisibleOnly.IsSet(field_1_flags); } set { field_1_flags = plotVisibleOnly.SetShortBoolean(field_1_flags, value); } } /// <summary> /// whether to size the chart with the window. /// </summary> public bool IsNotSizeWithWindow { get { return doNotSizeWithWindow.IsSet(field_1_flags); } set { field_1_flags = doNotSizeWithWindow.SetShortBoolean(field_1_flags, value); } } /// <summary> /// If fAlwaysAutoPlotArea is 1, then this field MUST be 1. /// If fAlwaysAutoPlotArea is 0, then this field MUST be ignored. /// </summary> public bool IsManPlotArea { get { return manPlotArea.IsSet(field_1_flags); } set { field_1_flags = manPlotArea.SetShortBoolean(field_1_flags, value); } } /// <summary> /// specifies whether the default plot area dimension (2) is used. /// 0 Use the default plot area dimension (2) regardless of the Pos record information. /// 1 Use the plot area dimension (2) of the Pos record; and fManPlotArea MUST be 1. /// </summary> public bool IsAlwaysAutoPlotArea { get { return alwaysAutoPlotArea.IsSet(field_1_flags); } set { field_1_flags = alwaysAutoPlotArea.SetShortBoolean(field_1_flags, value); if (value) IsManPlotArea = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // // /*============================================================ ** ** Class: ExecutionContext ** ** ** Purpose: Capture execution context for a thread ** ** ===========================================================*/ using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Security; namespace System.Threading { public delegate void ContextCallback(Object state); internal struct ExecutionContextSwitcher { internal ExecutionContext m_ec; internal SynchronizationContext m_sc; internal void Undo() { SynchronizationContext.SetSynchronizationContext(m_sc); ExecutionContext.Restore(m_ec); } } public sealed class ExecutionContext { public static readonly ExecutionContext Default = new ExecutionContext(); [ThreadStatic] static ExecutionContext t_currentMaybeNull; private readonly Dictionary<IAsyncLocal, object> m_localValues; private readonly List<IAsyncLocal> m_localChangeNotifications; private ExecutionContext() { m_localValues = new Dictionary<IAsyncLocal, object>(); m_localChangeNotifications = new List<IAsyncLocal>(); } private ExecutionContext(ExecutionContext other) { m_localValues = new Dictionary<IAsyncLocal, object>(other.m_localValues); m_localChangeNotifications = new List<IAsyncLocal>(other.m_localChangeNotifications); } public static ExecutionContext Capture() { return t_currentMaybeNull ?? ExecutionContext.Default; } public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state) { ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher); try { EstablishCopyOnWriteScope(ref ecsw); ExecutionContext.Restore(executionContext); callback(state); } catch { // Note: we have a "catch" rather than a "finally" because we want // to stop the first pass of EH here. That way we can restore the previous // context before any of our callers' EH filters run. That means we need to // end the scope separately in the non-exceptional case below. ecsw.Undo(); throw; } ecsw.Undo(); } internal static void Restore(ExecutionContext executionContext) { if (executionContext == null) throw new InvalidOperationException(SR.InvalidOperation_NullContext); ExecutionContext previous = t_currentMaybeNull ?? Default; t_currentMaybeNull = executionContext; if (previous != executionContext) OnContextChanged(previous, executionContext); } static internal void EstablishCopyOnWriteScope(ref ExecutionContextSwitcher ecsw) { ecsw.m_ec = Capture(); ecsw.m_sc = SynchronizationContext.CurrentExplicit; } private static void OnContextChanged(ExecutionContext previous, ExecutionContext current) { previous = previous ?? Default; foreach (IAsyncLocal local in previous.m_localChangeNotifications) { object previousValue; object currentValue; previous.m_localValues.TryGetValue(local, out previousValue); current.m_localValues.TryGetValue(local, out currentValue); if (previousValue != currentValue) local.OnValueChanged(previousValue, currentValue, true); } if (current.m_localChangeNotifications != previous.m_localChangeNotifications) { try { foreach (IAsyncLocal local in current.m_localChangeNotifications) { // If the local has a value in the previous context, we already fired the event for that local // in the code above. object previousValue; if (!previous.m_localValues.TryGetValue(local, out previousValue)) { object currentValue; current.m_localValues.TryGetValue(local, out currentValue); if (previousValue != currentValue) local.OnValueChanged(previousValue, currentValue, true); } } } catch (Exception ex) { Environment.FailFast(SR.ExecutionContext_ExceptionInAsyncLocalNotification, ex); } } } internal static object GetLocalValue(IAsyncLocal local) { ExecutionContext current = t_currentMaybeNull; if (current == null) return null; object value; current.m_localValues.TryGetValue(local, out value); return value; } internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications) { ExecutionContext current = t_currentMaybeNull ?? ExecutionContext.Default; object previousValue; bool hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue); if (previousValue == newValue) return; current = new ExecutionContext(current); current.m_localValues[local] = newValue; t_currentMaybeNull = current; if (needChangeNotifications) { if (hadPreviousValue) Contract.Assert(current.m_localChangeNotifications.Contains(local)); else current.m_localChangeNotifications.Add(local); local.OnValueChanged(previousValue, newValue, false); } } [Flags] internal enum CaptureOptions { None = 0x00, IgnoreSyncCtx = 0x01, OptimizeDefaultCase = 0x02, } internal static ExecutionContext PreAllocatedDefault { get { return ExecutionContext.Default; } } internal bool IsPreAllocatedDefault { get { return this == ExecutionContext.Default; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/groups/group_booking.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Booking.Groups { /// <summary>Holder for reflection information generated from booking/groups/group_booking.proto</summary> public static partial class GroupBookingReflection { #region Descriptor /// <summary>File descriptor for booking/groups/group_booking.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GroupBookingReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiJib29raW5nL2dyb3Vwcy9ncm91cF9ib29raW5nLnByb3RvEhpob2xtcy50", "eXBlcy5ib29raW5nLmdyb3VwcxoqcHJpbWl0aXZlL3BiX2luY2x1c2l2ZV9v", "cHNkYXRlX3JhbmdlLnByb3RvGhRwcmltaXRpdmUvdXVpZC5wcm90bxo2Ym9v", "a2luZy9pbmRpY2F0b3JzL2NhbmNlbGxhdGlvbl9wb2xpY3lfaW5kaWNhdG9y", "LnByb3RvGi9ib29raW5nL2luZGljYXRvcnMvdHJhdmVsX2FnZW50X2luZGlj", "YXRvci5wcm90bxowYm9va2luZy9pbmRpY2F0b3JzL2dyb3VwX2Jvb2tpbmdf", "aW5kaWNhdG9yLnByb3RvGilib29raW5nL2dyb3Vwcy9ncm91cF9ib29raW5n", "X3N0YXR1cy5wcm90bxogY3JtL2dyb3Vwcy9ncm91cF9pbmRpY2F0b3IucHJv", "dG8aJHN1cHBseS9yYXRlX3NjaGVkdWxlX2luZGljYXRvci5wcm90bxo+dGVu", "YW5jeV9jb25maWcvaW5kaWNhdG9ycy9ncm91cF9ib29raW5nX21ldGhvZF9p", "bmRpY2F0b3IucHJvdG8aMnRlbmFuY3lfY29uZmlnL2luZGljYXRvcnMvcHJv", "cGVydHlfaW5kaWNhdG9yLnByb3RvIr0ICgxHcm91cEJvb2tpbmcSSAoJZW50", "aXR5X2lkGAEgASgLMjUuaG9sbXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3Jz", "Lkdyb3VwQm9va2luZ0luZGljYXRvchI+CgZzdGF0dXMYAiABKA4yLi5ob2xt", "cy50eXBlcy5ib29raW5nLmdyb3Vwcy5Hcm91cEJvb2tpbmdTdGF0dXMSEgoK", "dGF4X2V4ZW1wdBgDIAEoCBIOCgZ0YXhfaWQYBCABKAkSGgoSZ3JvdXBfcGF5", "c19sb2RnaW5nGAUgASgIEh4KFmdyb3VwX3BheXNfaW5jaWRlbnRhbHMYBiAB", "KAgSGAoQYWRkaXRpb25hbF9ub3RlcxgHIAEoCRIbChNjdXN0b21lcl9ib29r", "aW5nX2lkGAggASgJEkIKCmRhdGVfcmFuZ2UYCSABKAsyLi5ob2xtcy50eXBl", "cy5wcmltaXRpdmUuUGJJbmNsdXNpdmVPcHNkYXRlUmFuZ2USQAoNcmF0ZV9z", "Y2hlZHVsZRgLIAEoCzIpLmhvbG1zLnR5cGVzLnN1cHBseS5SYXRlU2NoZWR1", "bGVJbmRpY2F0b3ISNQoFZ3JvdXAYDCABKAsyJi5ob2xtcy50eXBlcy5jcm0u", "Z3JvdXBzLkdyb3VwSW5kaWNhdG9yEj0KGGNvbmZpcm1hdGlvbl90ZW1wbGF0", "ZV9pZBgNIAEoCzIbLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5VdWlkEloKDmJv", "b2tpbmdfbWV0aG9kGA4gASgLMkIuaG9sbXMudHlwZXMudGVuYW5jeV9jb25m", "aWcuaW5kaWNhdG9ycy5Hcm91cEJvb2tpbmdNZXRob2RJbmRpY2F0b3ISOAoT", "YXJyaXZhbF90ZW1wbGF0ZV9pZBgPIAEoCzIbLmhvbG1zLnR5cGVzLnByaW1p", "dGl2ZS5VdWlkEjoKFXJlc2VydmF0aW9uX3NvdXJjZV9pZBgQIAEoCzIbLmhv", "bG1zLnR5cGVzLnByaW1pdGl2ZS5VdWlkEkoKDHRyYXZlbF9hZ2VudBgRIAEo", "CzI0LmhvbG1zLnR5cGVzLmJvb2tpbmcuaW5kaWNhdG9ycy5UcmF2ZWxBZ2Vu", "dEluZGljYXRvchJYChNjYW5jZWxsYXRpb25fcG9saWN5GBIgASgLMjsuaG9s", "bXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLkNhbmNlbGxhdGlvblBvbGlj", "eUluZGljYXRvchISCgpncm91cF9uYW1lGBMgASgJEhoKEnN1cnByZXNzX3Jh", "dGVfaW5mbxgUIAEoCBIUCgx0YXhfY2F0ZWdvcnkYFSABKAkSUgoQYm9va2lu", "Z19wcm9wZXJ0eRgWIAEoCzI4LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmln", "LmluZGljYXRvcnMuUHJvcGVydHlJbmRpY2F0b3JCLVoOYm9va2luZy9ncm91", "cHOqAhpIT0xNUy5UeXBlcy5Cb29raW5nLkdyb3Vwc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbInclusiveOpsdateRangeReflection.Descriptor, global::HOLMS.Types.Primitive.UuidReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.TravelAgentIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.GroupBookingIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Groups.GroupBookingStatusReflection.Descriptor, global::HOLMS.Types.CRM.Groups.GroupIndicatorReflection.Descriptor, global::HOLMS.Types.Supply.RateScheduleIndicatorReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.GroupBookingMethodIndicatorReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Groups.GroupBooking), global::HOLMS.Types.Booking.Groups.GroupBooking.Parser, new[]{ "EntityId", "Status", "TaxExempt", "TaxId", "GroupPaysLodging", "GroupPaysIncidentals", "AdditionalNotes", "CustomerBookingId", "DateRange", "RateSchedule", "Group", "ConfirmationTemplateId", "BookingMethod", "ArrivalTemplateId", "ReservationSourceId", "TravelAgent", "CancellationPolicy", "GroupName", "SurpressRateInfo", "TaxCategory", "BookingProperty" }, null, null, null) })); } #endregion } #region Messages public sealed partial class GroupBooking : pb::IMessage<GroupBooking> { private static readonly pb::MessageParser<GroupBooking> _parser = new pb::MessageParser<GroupBooking>(() => new GroupBooking()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GroupBooking> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.Groups.GroupBookingReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBooking() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBooking(GroupBooking other) : this() { EntityId = other.entityId_ != null ? other.EntityId.Clone() : null; status_ = other.status_; taxExempt_ = other.taxExempt_; taxId_ = other.taxId_; groupPaysLodging_ = other.groupPaysLodging_; groupPaysIncidentals_ = other.groupPaysIncidentals_; additionalNotes_ = other.additionalNotes_; customerBookingId_ = other.customerBookingId_; DateRange = other.dateRange_ != null ? other.DateRange.Clone() : null; RateSchedule = other.rateSchedule_ != null ? other.RateSchedule.Clone() : null; Group = other.group_ != null ? other.Group.Clone() : null; ConfirmationTemplateId = other.confirmationTemplateId_ != null ? other.ConfirmationTemplateId.Clone() : null; BookingMethod = other.bookingMethod_ != null ? other.BookingMethod.Clone() : null; ArrivalTemplateId = other.arrivalTemplateId_ != null ? other.ArrivalTemplateId.Clone() : null; ReservationSourceId = other.reservationSourceId_ != null ? other.ReservationSourceId.Clone() : null; TravelAgent = other.travelAgent_ != null ? other.TravelAgent.Clone() : null; CancellationPolicy = other.cancellationPolicy_ != null ? other.CancellationPolicy.Clone() : null; groupName_ = other.groupName_; surpressRateInfo_ = other.surpressRateInfo_; taxCategory_ = other.taxCategory_; BookingProperty = other.bookingProperty_ != null ? other.BookingProperty.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBooking Clone() { return new GroupBooking(this); } /// <summary>Field number for the "entity_id" field.</summary> public const int EntityIdFieldNumber = 1; private global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "status" field.</summary> public const int StatusFieldNumber = 2; private global::HOLMS.Types.Booking.Groups.GroupBookingStatus status_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Groups.GroupBookingStatus Status { get { return status_; } set { status_ = value; } } /// <summary>Field number for the "tax_exempt" field.</summary> public const int TaxExemptFieldNumber = 3; private bool taxExempt_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool TaxExempt { get { return taxExempt_; } set { taxExempt_ = value; } } /// <summary>Field number for the "tax_id" field.</summary> public const int TaxIdFieldNumber = 4; private string taxId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TaxId { get { return taxId_; } set { taxId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "group_pays_lodging" field.</summary> public const int GroupPaysLodgingFieldNumber = 5; private bool groupPaysLodging_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool GroupPaysLodging { get { return groupPaysLodging_; } set { groupPaysLodging_ = value; } } /// <summary>Field number for the "group_pays_incidentals" field.</summary> public const int GroupPaysIncidentalsFieldNumber = 6; private bool groupPaysIncidentals_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool GroupPaysIncidentals { get { return groupPaysIncidentals_; } set { groupPaysIncidentals_ = value; } } /// <summary>Field number for the "additional_notes" field.</summary> public const int AdditionalNotesFieldNumber = 7; private string additionalNotes_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string AdditionalNotes { get { return additionalNotes_; } set { additionalNotes_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "customer_booking_id" field.</summary> public const int CustomerBookingIdFieldNumber = 8; private string customerBookingId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CustomerBookingId { get { return customerBookingId_; } set { customerBookingId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "date_range" field.</summary> public const int DateRangeFieldNumber = 9; private global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange dateRange_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange DateRange { get { return dateRange_; } set { dateRange_ = value; } } /// <summary>Field number for the "rate_schedule" field.</summary> public const int RateScheduleFieldNumber = 11; private global::HOLMS.Types.Supply.RateScheduleIndicator rateSchedule_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.RateScheduleIndicator RateSchedule { get { return rateSchedule_; } set { rateSchedule_ = value; } } /// <summary>Field number for the "group" field.</summary> public const int GroupFieldNumber = 12; private global::HOLMS.Types.CRM.Groups.GroupIndicator group_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.CRM.Groups.GroupIndicator Group { get { return group_; } set { group_ = value; } } /// <summary>Field number for the "confirmation_template_id" field.</summary> public const int ConfirmationTemplateIdFieldNumber = 13; private global::HOLMS.Types.Primitive.Uuid confirmationTemplateId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.Uuid ConfirmationTemplateId { get { return confirmationTemplateId_; } set { confirmationTemplateId_ = value; } } /// <summary>Field number for the "booking_method" field.</summary> public const int BookingMethodFieldNumber = 14; private global::HOLMS.Types.TenancyConfig.Indicators.GroupBookingMethodIndicator bookingMethod_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.TenancyConfig.Indicators.GroupBookingMethodIndicator BookingMethod { get { return bookingMethod_; } set { bookingMethod_ = value; } } /// <summary>Field number for the "arrival_template_id" field.</summary> public const int ArrivalTemplateIdFieldNumber = 15; private global::HOLMS.Types.Primitive.Uuid arrivalTemplateId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.Uuid ArrivalTemplateId { get { return arrivalTemplateId_; } set { arrivalTemplateId_ = value; } } /// <summary>Field number for the "reservation_source_id" field.</summary> public const int ReservationSourceIdFieldNumber = 16; private global::HOLMS.Types.Primitive.Uuid reservationSourceId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.Uuid ReservationSourceId { get { return reservationSourceId_; } set { reservationSourceId_ = value; } } /// <summary>Field number for the "travel_agent" field.</summary> public const int TravelAgentFieldNumber = 17; private global::HOLMS.Types.Booking.Indicators.TravelAgentIndicator travelAgent_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.TravelAgentIndicator TravelAgent { get { return travelAgent_; } set { travelAgent_ = value; } } /// <summary>Field number for the "cancellation_policy" field.</summary> public const int CancellationPolicyFieldNumber = 18; private global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator cancellationPolicy_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator CancellationPolicy { get { return cancellationPolicy_; } set { cancellationPolicy_ = value; } } /// <summary>Field number for the "group_name" field.</summary> public const int GroupNameFieldNumber = 19; private string groupName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string GroupName { get { return groupName_; } set { groupName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "surpress_rate_info" field.</summary> public const int SurpressRateInfoFieldNumber = 20; private bool surpressRateInfo_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool SurpressRateInfo { get { return surpressRateInfo_; } set { surpressRateInfo_ = value; } } /// <summary>Field number for the "tax_category" field.</summary> public const int TaxCategoryFieldNumber = 21; private string taxCategory_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TaxCategory { get { return taxCategory_; } set { taxCategory_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "booking_property" field.</summary> public const int BookingPropertyFieldNumber = 22; private global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator bookingProperty_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator BookingProperty { get { return bookingProperty_; } set { bookingProperty_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GroupBooking); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GroupBooking other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EntityId, other.EntityId)) return false; if (Status != other.Status) return false; if (TaxExempt != other.TaxExempt) return false; if (TaxId != other.TaxId) return false; if (GroupPaysLodging != other.GroupPaysLodging) return false; if (GroupPaysIncidentals != other.GroupPaysIncidentals) return false; if (AdditionalNotes != other.AdditionalNotes) return false; if (CustomerBookingId != other.CustomerBookingId) return false; if (!object.Equals(DateRange, other.DateRange)) return false; if (!object.Equals(RateSchedule, other.RateSchedule)) return false; if (!object.Equals(Group, other.Group)) return false; if (!object.Equals(ConfirmationTemplateId, other.ConfirmationTemplateId)) return false; if (!object.Equals(BookingMethod, other.BookingMethod)) return false; if (!object.Equals(ArrivalTemplateId, other.ArrivalTemplateId)) return false; if (!object.Equals(ReservationSourceId, other.ReservationSourceId)) return false; if (!object.Equals(TravelAgent, other.TravelAgent)) return false; if (!object.Equals(CancellationPolicy, other.CancellationPolicy)) return false; if (GroupName != other.GroupName) return false; if (SurpressRateInfo != other.SurpressRateInfo) return false; if (TaxCategory != other.TaxCategory) return false; if (!object.Equals(BookingProperty, other.BookingProperty)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (entityId_ != null) hash ^= EntityId.GetHashCode(); if (Status != 0) hash ^= Status.GetHashCode(); if (TaxExempt != false) hash ^= TaxExempt.GetHashCode(); if (TaxId.Length != 0) hash ^= TaxId.GetHashCode(); if (GroupPaysLodging != false) hash ^= GroupPaysLodging.GetHashCode(); if (GroupPaysIncidentals != false) hash ^= GroupPaysIncidentals.GetHashCode(); if (AdditionalNotes.Length != 0) hash ^= AdditionalNotes.GetHashCode(); if (CustomerBookingId.Length != 0) hash ^= CustomerBookingId.GetHashCode(); if (dateRange_ != null) hash ^= DateRange.GetHashCode(); if (rateSchedule_ != null) hash ^= RateSchedule.GetHashCode(); if (group_ != null) hash ^= Group.GetHashCode(); if (confirmationTemplateId_ != null) hash ^= ConfirmationTemplateId.GetHashCode(); if (bookingMethod_ != null) hash ^= BookingMethod.GetHashCode(); if (arrivalTemplateId_ != null) hash ^= ArrivalTemplateId.GetHashCode(); if (reservationSourceId_ != null) hash ^= ReservationSourceId.GetHashCode(); if (travelAgent_ != null) hash ^= TravelAgent.GetHashCode(); if (cancellationPolicy_ != null) hash ^= CancellationPolicy.GetHashCode(); if (GroupName.Length != 0) hash ^= GroupName.GetHashCode(); if (SurpressRateInfo != false) hash ^= SurpressRateInfo.GetHashCode(); if (TaxCategory.Length != 0) hash ^= TaxCategory.GetHashCode(); if (bookingProperty_ != null) hash ^= BookingProperty.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (entityId_ != null) { output.WriteRawTag(10); output.WriteMessage(EntityId); } if (Status != 0) { output.WriteRawTag(16); output.WriteEnum((int) Status); } if (TaxExempt != false) { output.WriteRawTag(24); output.WriteBool(TaxExempt); } if (TaxId.Length != 0) { output.WriteRawTag(34); output.WriteString(TaxId); } if (GroupPaysLodging != false) { output.WriteRawTag(40); output.WriteBool(GroupPaysLodging); } if (GroupPaysIncidentals != false) { output.WriteRawTag(48); output.WriteBool(GroupPaysIncidentals); } if (AdditionalNotes.Length != 0) { output.WriteRawTag(58); output.WriteString(AdditionalNotes); } if (CustomerBookingId.Length != 0) { output.WriteRawTag(66); output.WriteString(CustomerBookingId); } if (dateRange_ != null) { output.WriteRawTag(74); output.WriteMessage(DateRange); } if (rateSchedule_ != null) { output.WriteRawTag(90); output.WriteMessage(RateSchedule); } if (group_ != null) { output.WriteRawTag(98); output.WriteMessage(Group); } if (confirmationTemplateId_ != null) { output.WriteRawTag(106); output.WriteMessage(ConfirmationTemplateId); } if (bookingMethod_ != null) { output.WriteRawTag(114); output.WriteMessage(BookingMethod); } if (arrivalTemplateId_ != null) { output.WriteRawTag(122); output.WriteMessage(ArrivalTemplateId); } if (reservationSourceId_ != null) { output.WriteRawTag(130, 1); output.WriteMessage(ReservationSourceId); } if (travelAgent_ != null) { output.WriteRawTag(138, 1); output.WriteMessage(TravelAgent); } if (cancellationPolicy_ != null) { output.WriteRawTag(146, 1); output.WriteMessage(CancellationPolicy); } if (GroupName.Length != 0) { output.WriteRawTag(154, 1); output.WriteString(GroupName); } if (SurpressRateInfo != false) { output.WriteRawTag(160, 1); output.WriteBool(SurpressRateInfo); } if (TaxCategory.Length != 0) { output.WriteRawTag(170, 1); output.WriteString(TaxCategory); } if (bookingProperty_ != null) { output.WriteRawTag(178, 1); output.WriteMessage(BookingProperty); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (entityId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId); } if (Status != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status); } if (TaxExempt != false) { size += 1 + 1; } if (TaxId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TaxId); } if (GroupPaysLodging != false) { size += 1 + 1; } if (GroupPaysIncidentals != false) { size += 1 + 1; } if (AdditionalNotes.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(AdditionalNotes); } if (CustomerBookingId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CustomerBookingId); } if (dateRange_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(DateRange); } if (rateSchedule_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(RateSchedule); } if (group_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Group); } if (confirmationTemplateId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ConfirmationTemplateId); } if (bookingMethod_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(BookingMethod); } if (arrivalTemplateId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ArrivalTemplateId); } if (reservationSourceId_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(ReservationSourceId); } if (travelAgent_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(TravelAgent); } if (cancellationPolicy_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(CancellationPolicy); } if (GroupName.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(GroupName); } if (SurpressRateInfo != false) { size += 2 + 1; } if (TaxCategory.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(TaxCategory); } if (bookingProperty_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(BookingProperty); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GroupBooking other) { if (other == null) { return; } if (other.entityId_ != null) { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator(); } EntityId.MergeFrom(other.EntityId); } if (other.Status != 0) { Status = other.Status; } if (other.TaxExempt != false) { TaxExempt = other.TaxExempt; } if (other.TaxId.Length != 0) { TaxId = other.TaxId; } if (other.GroupPaysLodging != false) { GroupPaysLodging = other.GroupPaysLodging; } if (other.GroupPaysIncidentals != false) { GroupPaysIncidentals = other.GroupPaysIncidentals; } if (other.AdditionalNotes.Length != 0) { AdditionalNotes = other.AdditionalNotes; } if (other.CustomerBookingId.Length != 0) { CustomerBookingId = other.CustomerBookingId; } if (other.dateRange_ != null) { if (dateRange_ == null) { dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange(); } DateRange.MergeFrom(other.DateRange); } if (other.rateSchedule_ != null) { if (rateSchedule_ == null) { rateSchedule_ = new global::HOLMS.Types.Supply.RateScheduleIndicator(); } RateSchedule.MergeFrom(other.RateSchedule); } if (other.group_ != null) { if (group_ == null) { group_ = new global::HOLMS.Types.CRM.Groups.GroupIndicator(); } Group.MergeFrom(other.Group); } if (other.confirmationTemplateId_ != null) { if (confirmationTemplateId_ == null) { confirmationTemplateId_ = new global::HOLMS.Types.Primitive.Uuid(); } ConfirmationTemplateId.MergeFrom(other.ConfirmationTemplateId); } if (other.bookingMethod_ != null) { if (bookingMethod_ == null) { bookingMethod_ = new global::HOLMS.Types.TenancyConfig.Indicators.GroupBookingMethodIndicator(); } BookingMethod.MergeFrom(other.BookingMethod); } if (other.arrivalTemplateId_ != null) { if (arrivalTemplateId_ == null) { arrivalTemplateId_ = new global::HOLMS.Types.Primitive.Uuid(); } ArrivalTemplateId.MergeFrom(other.ArrivalTemplateId); } if (other.reservationSourceId_ != null) { if (reservationSourceId_ == null) { reservationSourceId_ = new global::HOLMS.Types.Primitive.Uuid(); } ReservationSourceId.MergeFrom(other.ReservationSourceId); } if (other.travelAgent_ != null) { if (travelAgent_ == null) { travelAgent_ = new global::HOLMS.Types.Booking.Indicators.TravelAgentIndicator(); } TravelAgent.MergeFrom(other.TravelAgent); } if (other.cancellationPolicy_ != null) { if (cancellationPolicy_ == null) { cancellationPolicy_ = new global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator(); } CancellationPolicy.MergeFrom(other.CancellationPolicy); } if (other.GroupName.Length != 0) { GroupName = other.GroupName; } if (other.SurpressRateInfo != false) { SurpressRateInfo = other.SurpressRateInfo; } if (other.TaxCategory.Length != 0) { TaxCategory = other.TaxCategory; } if (other.bookingProperty_ != null) { if (bookingProperty_ == null) { bookingProperty_ = new global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator(); } BookingProperty.MergeFrom(other.BookingProperty); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator(); } input.ReadMessage(entityId_); break; } case 16: { status_ = (global::HOLMS.Types.Booking.Groups.GroupBookingStatus) input.ReadEnum(); break; } case 24: { TaxExempt = input.ReadBool(); break; } case 34: { TaxId = input.ReadString(); break; } case 40: { GroupPaysLodging = input.ReadBool(); break; } case 48: { GroupPaysIncidentals = input.ReadBool(); break; } case 58: { AdditionalNotes = input.ReadString(); break; } case 66: { CustomerBookingId = input.ReadString(); break; } case 74: { if (dateRange_ == null) { dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange(); } input.ReadMessage(dateRange_); break; } case 90: { if (rateSchedule_ == null) { rateSchedule_ = new global::HOLMS.Types.Supply.RateScheduleIndicator(); } input.ReadMessage(rateSchedule_); break; } case 98: { if (group_ == null) { group_ = new global::HOLMS.Types.CRM.Groups.GroupIndicator(); } input.ReadMessage(group_); break; } case 106: { if (confirmationTemplateId_ == null) { confirmationTemplateId_ = new global::HOLMS.Types.Primitive.Uuid(); } input.ReadMessage(confirmationTemplateId_); break; } case 114: { if (bookingMethod_ == null) { bookingMethod_ = new global::HOLMS.Types.TenancyConfig.Indicators.GroupBookingMethodIndicator(); } input.ReadMessage(bookingMethod_); break; } case 122: { if (arrivalTemplateId_ == null) { arrivalTemplateId_ = new global::HOLMS.Types.Primitive.Uuid(); } input.ReadMessage(arrivalTemplateId_); break; } case 130: { if (reservationSourceId_ == null) { reservationSourceId_ = new global::HOLMS.Types.Primitive.Uuid(); } input.ReadMessage(reservationSourceId_); break; } case 138: { if (travelAgent_ == null) { travelAgent_ = new global::HOLMS.Types.Booking.Indicators.TravelAgentIndicator(); } input.ReadMessage(travelAgent_); break; } case 146: { if (cancellationPolicy_ == null) { cancellationPolicy_ = new global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator(); } input.ReadMessage(cancellationPolicy_); break; } case 154: { GroupName = input.ReadString(); break; } case 160: { SurpressRateInfo = input.ReadBool(); break; } case 170: { TaxCategory = input.ReadString(); break; } case 178: { if (bookingProperty_ == null) { bookingProperty_ = new global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator(); } input.ReadMessage(bookingProperty_); break; } } } } } #endregion } #endregion Designer generated code
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// AccountOperations operations. /// </summary> internal partial class AccountOperations : Microsoft.Rest.IServiceOperations<BatchServiceClient>, IAccountOperations { /// <summary> /// Initializes a new instance of the AccountOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal AccountOperations(BatchServiceClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the BatchServiceClient /// </summary> public BatchServiceClient Client { get; private set; } /// <summary> /// Lists all node agent SKUs supported by the Azure Batch service. /// </summary> /// <param name='accountListNodeAgentSkusOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>> ListNodeAgentSkusWithHttpMessagesAsync(AccountListNodeAgentSkusOptions accountListNodeAgentSkusOptions = default(AccountListNodeAgentSkusOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } string filter = default(string); if (accountListNodeAgentSkusOptions != null) { filter = accountListNodeAgentSkusOptions.Filter; } int? maxResults = default(int?); if (accountListNodeAgentSkusOptions != null) { maxResults = accountListNodeAgentSkusOptions.MaxResults; } int? timeout = default(int?); if (accountListNodeAgentSkusOptions != null) { timeout = accountListNodeAgentSkusOptions.Timeout; } System.Guid? clientRequestId = default(System.Guid?); if (accountListNodeAgentSkusOptions != null) { clientRequestId = accountListNodeAgentSkusOptions.ClientRequestId; } bool? returnClientRequestId = default(bool?); if (accountListNodeAgentSkusOptions != null) { returnClientRequestId = accountListNodeAgentSkusOptions.ReturnClientRequestId; } System.DateTime? ocpDate = default(System.DateTime?); if (accountListNodeAgentSkusOptions != null) { ocpDate = accountListNodeAgentSkusOptions.OcpDate; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("filter", filter); tracingParameters.Add("maxResults", maxResults); tracingParameters.Add("timeout", timeout); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("returnClientRequestId", returnClientRequestId); tracingParameters.Add("ocpDate", ocpDate); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNodeAgentSkus", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "nodeagentskus").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (maxResults != null) { _queryParameters.Add(string.Format("maxresults={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(maxResults, this.Client.SerializationSettings).Trim('"')))); } if (timeout != null) { _queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (returnClientRequestId != null) { if (_httpRequest.Headers.Contains("return-client-request-id")) { _httpRequest.Headers.Remove("return-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"')); } if (ocpDate != null) { if (_httpRequest.Headers.Contains("ocp-date")) { _httpRequest.Headers.Remove("ocp-date"); } _httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NodeAgentSku>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<AccountListNodeAgentSkusHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all node agent SKUs supported by the Azure Batch service. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='accountListNodeAgentSkusNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>> ListNodeAgentSkusNextWithHttpMessagesAsync(string nextPageLink, AccountListNodeAgentSkusNextOptions accountListNodeAgentSkusNextOptions = default(AccountListNodeAgentSkusNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } System.Guid? clientRequestId = default(System.Guid?); if (accountListNodeAgentSkusNextOptions != null) { clientRequestId = accountListNodeAgentSkusNextOptions.ClientRequestId; } bool? returnClientRequestId = default(bool?); if (accountListNodeAgentSkusNextOptions != null) { returnClientRequestId = accountListNodeAgentSkusNextOptions.ReturnClientRequestId; } System.DateTime? ocpDate = default(System.DateTime?); if (accountListNodeAgentSkusNextOptions != null) { ocpDate = accountListNodeAgentSkusNextOptions.OcpDate; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("returnClientRequestId", returnClientRequestId); tracingParameters.Add("ocpDate", ocpDate); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNodeAgentSkusNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (returnClientRequestId != null) { if (_httpRequest.Headers.Contains("return-client-request-id")) { _httpRequest.Headers.Remove("return-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"')); } if (ocpDate != null) { if (_httpRequest.Headers.Contains("ocp-date")) { _httpRequest.Headers.Remove("ocp-date"); } _httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NodeAgentSku>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<AccountListNodeAgentSkusHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } 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.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System { // DateTimeOffset is a value type that consists of a DateTime and a time zone offset, // ie. how far away the time is from GMT. The DateTime is stored whole, and the offset // is stored as an Int16 internally to save space, but presented as a TimeSpan. // // The range is constrained so that both the represented clock time and the represented // UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime // for actual UTC times, and a slightly constrained range on one end when an offset is // present. // // This class should be substitutable for date time in most cases; so most operations // effectively work on the clock time. However, the underlying UTC time is what counts // for the purposes of identity, sorting and subtracting two instances. // // // There are theoretically two date times stored, the UTC and the relative local representation // or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable // for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this // out and for internal readability. [StructLayout(LayoutKind.Auto)] [Serializable] public struct DateTimeOffset : IComparable, IFormattable, IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>, ISerializable, IDeserializationCallback { // Constants internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14; internal const Int64 MinOffset = -MaxOffset; private const long UnixEpochTicks = TimeSpan.TicksPerDay * DateTime.DaysTo1970; // 621,355,968,000,000,000 private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800 private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 internal const long UnixMinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; internal const long UnixMaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; // Static Fields public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero); public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero); // Instance Fields private DateTime _dateTime; private Int16 _offsetMinutes; // Constructors // Constructs a DateTimeOffset from a tick count and offset public DateTimeOffset(long ticks, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); // Let the DateTime constructor do the range checks DateTime dateTime = new DateTime(ticks); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds, // extracts the local offset. For UTC, creates a UTC instance with a zero offset. public DateTimeOffset(DateTime dateTime) { TimeSpan offset; if (dateTime.Kind != DateTimeKind.Utc) { // Local and Unspecified are both treated as Local offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else { offset = new TimeSpan(0); } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time // consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that // the offset corresponds to the local. public DateTimeOffset(DateTime dateTime, TimeSpan offset) { if (dateTime.Kind == DateTimeKind.Local) { if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) { throw new ArgumentException(SR.Argument_OffsetLocalMismatch, nameof(offset)); } } else if (dateTime.Kind == DateTimeKind.Utc) { if (offset != TimeSpan.Zero) { throw new ArgumentException(SR.Argument_OffsetUtcMismatch, nameof(offset)); } } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond and offset public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond, Calendar and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset); } // Returns a DateTimeOffset representing the current date and time. The // resolution of the returned value depends on the system timer. For // Windows NT 3.5 and later the timer resolution is approximately 10ms, // for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98 // it is approximately 55ms. // public static DateTimeOffset Now { get { return new DateTimeOffset(DateTime.Now); } } public static DateTimeOffset UtcNow { get { return new DateTimeOffset(DateTime.UtcNow); } } public DateTime DateTime { get { return ClockDateTime; } } public DateTime UtcDateTime { get { return DateTime.SpecifyKind(_dateTime, DateTimeKind.Utc); } } public DateTime LocalDateTime { get { return UtcDateTime.ToLocalTime(); } } // Adjust to a given offset with the same UTC time. Can throw ArgumentException // public DateTimeOffset ToOffset(TimeSpan offset) { return new DateTimeOffset((_dateTime + offset).Ticks, offset); } // Instance Properties // The clock or visible time represented. This is just a wrapper around the internal date because this is // the chosen storage mechanism. Going through this helper is good for readability and maintainability. // This should be used for display but not identity. private DateTime ClockDateTime { get { return new DateTime((_dateTime + Offset).Ticks, DateTimeKind.Unspecified); } } // Returns the date part of this DateTimeOffset. The resulting value // corresponds to this DateTimeOffset with the time-of-day part set to // zero (midnight). // public DateTime Date { get { return ClockDateTime.Date; } } // Returns the day-of-month part of this DateTimeOffset. The returned // value is an integer between 1 and 31. // public int Day { get { return ClockDateTime.Day; } } // Returns the day-of-week part of this DateTimeOffset. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek DayOfWeek { get { return ClockDateTime.DayOfWeek; } } // Returns the day-of-year part of this DateTimeOffset. The returned value // is an integer between 1 and 366. // public int DayOfYear { get { return ClockDateTime.DayOfYear; } } // Returns the hour part of this DateTimeOffset. The returned value is an // integer between 0 and 23. // public int Hour { get { return ClockDateTime.Hour; } } // Returns the millisecond part of this DateTimeOffset. The returned value // is an integer between 0 and 999. // public int Millisecond { get { return ClockDateTime.Millisecond; } } // Returns the minute part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Minute { get { return ClockDateTime.Minute; } } // Returns the month part of this DateTimeOffset. The returned value is an // integer between 1 and 12. // public int Month { get { return ClockDateTime.Month; } } public TimeSpan Offset { get { return new TimeSpan(0, _offsetMinutes, 0); } } // Returns the second part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Second { get { return ClockDateTime.Second; } } // Returns the tick count for this DateTimeOffset. The returned value is // the number of 100-nanosecond intervals that have elapsed since 1/1/0001 // 12:00am. // public long Ticks { get { return ClockDateTime.Ticks; } } public long UtcTicks { get { return UtcDateTime.Ticks; } } // Returns the time-of-day part of this DateTimeOffset. The returned value // is a TimeSpan that indicates the time elapsed since midnight. // public TimeSpan TimeOfDay { get { return ClockDateTime.TimeOfDay; } } // Returns the year part of this DateTimeOffset. The returned value is an // integer between 1 and 9999. // public int Year { get { return ClockDateTime.Year; } } // Returns the DateTimeOffset resulting from adding the given // TimeSpan to this DateTimeOffset. // public DateTimeOffset Add(TimeSpan timeSpan) { return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // days to this DateTimeOffset. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddDays(double days) { return new DateTimeOffset(ClockDateTime.AddDays(days), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // hours to this DateTimeOffset. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddHours(double hours) { return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset); } // Returns the DateTimeOffset resulting from the given number of // milliseconds to this DateTimeOffset. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to this DateTimeOffset. The value // argument is permitted to be negative. // public DateTimeOffset AddMilliseconds(double milliseconds) { return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // minutes to this DateTimeOffset. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddMinutes(double minutes) { return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset); } public DateTimeOffset AddMonths(int months) { return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // seconds to this DateTimeOffset. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddSeconds(double seconds) { return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // 100-nanosecond ticks to this DateTimeOffset. The value argument // is permitted to be negative. // public DateTimeOffset AddTicks(long ticks) { return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // years to this DateTimeOffset. The result is computed by incrementing // (or decrementing) the year part of this DateTimeOffset by value // years. If the month and day of this DateTimeOffset is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of this DateTimeOffset. // public DateTimeOffset AddYears(int years) { return new DateTimeOffset(ClockDateTime.AddYears(years), Offset); } // Compares two DateTimeOffset values, returning an integer that indicates // their relationship. // public static int Compare(DateTimeOffset first, DateTimeOffset second) { return DateTime.Compare(first.UtcDateTime, second.UtcDateTime); } // Compares this DateTimeOffset to a given object. This method provides an // implementation of the IComparable interface. The object // argument must be another DateTimeOffset, or otherwise an exception // occurs. Null is considered less than any instance. // int IComparable.CompareTo(Object obj) { if (obj == null) return 1; if (!(obj is DateTimeOffset)) { throw new ArgumentException(SR.Arg_MustBeDateTimeOffset); } DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime; DateTime utc = UtcDateTime; if (utc > objUtc) return 1; if (utc < objUtc) return -1; return 0; } public int CompareTo(DateTimeOffset other) { DateTime otherUtc = other.UtcDateTime; DateTime utc = UtcDateTime; if (utc > otherUtc) return 1; if (utc < otherUtc) return -1; return 0; } // Checks if this DateTimeOffset is equal to a given object. Returns // true if the given object is a boxed DateTimeOffset and its value // is equal to the value of this DateTimeOffset. Returns false // otherwise. // public override bool Equals(Object obj) { if (obj is DateTimeOffset) { return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime); } return false; } public bool Equals(DateTimeOffset other) { return UtcDateTime.Equals(other.UtcDateTime); } public bool EqualsExact(DateTimeOffset other) { // // returns true when the ClockDateTime, Kind, and Offset match // // currently the Kind should always be Unspecified, but there is always the possibility that a future version // of DateTimeOffset overloads the Kind field // return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind); } // Compares two DateTimeOffset values for equality. Returns true if // the two DateTimeOffset values are equal, or false if they are // not equal. // public static bool Equals(DateTimeOffset first, DateTimeOffset second) { return DateTime.Equals(first.UtcDateTime, second.UtcDateTime); } // Creates a DateTimeOffset from a Windows filetime. A Windows filetime is // a long representing the date and time as the number of // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am. // public static DateTimeOffset FromFileTime(long fileTime) { return new DateTimeOffset(DateTime.FromFileTime(fileTime)); } public static DateTimeOffset FromUnixTimeSeconds(long seconds) { if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds) { throw new ArgumentOutOfRangeException(nameof(seconds), SR.Format(SR.ArgumentOutOfRange_Range, UnixMinSeconds, UnixMaxSeconds)); } long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) { const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) { throw new ArgumentOutOfRangeException(nameof(milliseconds), SR.Format(SR.ArgumentOutOfRange_Range, MinMilliseconds, MaxMilliseconds)); } long ticks = milliseconds * TimeSpan.TicksPerMillisecond + UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } // ----- SECTION: private serialization instance methods ----------------* void IDeserializationCallback.OnDeserialization(Object sender) { try { _offsetMinutes = ValidateOffset(Offset); _dateTime = ValidateDate(ClockDateTime, Offset); } catch (ArgumentException e) { throw new SerializationException(SR.Serialization_InvalidData, e); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } info.AddValue("DateTime", _dateTime); info.AddValue("OffsetMinutes", _offsetMinutes); } private DateTimeOffset(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } _dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime)); _offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16)); } // Returns the hash code for this DateTimeOffset. // public override int GetHashCode() { return UtcDateTime.GetHashCode(); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(String input) { TimeSpan offset; DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) { return Parse(input, formatProvider, DateTimeStyles.None); } public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) { return ParseExact(input, format, formatProvider, DateTimeStyles.None); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult = DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult = DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public TimeSpan Subtract(DateTimeOffset value) { return UtcDateTime.Subtract(value.UtcDateTime); } public DateTimeOffset Subtract(TimeSpan value) { return new DateTimeOffset(ClockDateTime.Subtract(value), Offset); } public long ToFileTime() { return UtcDateTime.ToFileTime(); } public long ToUnixTimeSeconds() { // Truncate sub-second precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times. // // For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0 // ticks = 621355967990010000 // ticksFromEpoch = ticks - UnixEpochTicks = -9990000 // secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0 // // Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division, // whereas we actually always want to round *down* when converting to Unix time. This happens // automatically for positive Unix time values. Now the example becomes: // seconds = ticks / TimeSpan.TicksPerSecond = 62135596799 // secondsFromEpoch = seconds - UnixEpochSeconds = -1 // // In other words, we want to consistently round toward the time 1/1/0001 00:00:00, // rather than toward the Unix Epoch (1/1/1970 00:00:00). long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond; return seconds - UnixEpochSeconds; } public long ToUnixTimeMilliseconds() { // Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond; return milliseconds - UnixEpochMilliseconds; } public DateTimeOffset ToLocalTime() { return ToLocalTime(false); } internal DateTimeOffset ToLocalTime(bool throwOnOverflow) { return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow)); } public override String ToString() { return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset); } public String ToString(String format) { return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset); } public String ToString(IFormatProvider formatProvider) { return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), Offset); } public String ToString(String format, IFormatProvider formatProvider) { return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset); } public DateTimeOffset ToUniversalTime() { return new DateTimeOffset(UtcDateTime); } public static Boolean TryParse(String input, out DateTimeOffset result) { TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } // Ensures the TimeSpan is valid to go in a DateTimeOffset. private static Int16 ValidateOffset(TimeSpan offset) { Int64 ticks = offset.Ticks; if (ticks % TimeSpan.TicksPerMinute != 0) { throw new ArgumentException(SR.Argument_OffsetPrecision, nameof(offset)); } if (ticks < MinOffset || ticks > MaxOffset) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_OffsetOutOfRange); } return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute); } // Ensures that the time and offset are in range. private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) { // The key validation is that both the UTC and clock times fit. The clock time is validated // by the DateTime constructor. Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated."); // This operation cannot overflow because offset should have already been validated to be within // 14 hours and the DateTime instance is more than that distance from the boundaries of Int64. Int64 utcTicks = dateTime.Ticks - offset.Ticks; if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_UTCOutOfRange); } // make sure the Kind is set to Unspecified // return new DateTime(utcTicks, DateTimeKind.Unspecified); } private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) { if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidDateTimeStyles, parameterName); } if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) { throw new ArgumentException(SR.Argument_ConflictingDateTimeStyles, parameterName); } if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) { throw new ArgumentException(SR.Argument_DateTimeOffsetInvalidDateTimeStyles, parameterName); } // RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatibility with DateTime style &= ~DateTimeStyles.RoundtripKind; // AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse style &= ~DateTimeStyles.AssumeLocal; return style; } // Operators public static implicit operator DateTimeOffset(DateTime dateTime) { return new DateTimeOffset(dateTime); } public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset); } public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset); } public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime - right.UtcDateTime; } public static bool operator ==(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime == right.UtcDateTime; } public static bool operator !=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime != right.UtcDateTime; } public static bool operator <(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime < right.UtcDateTime; } public static bool operator <=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime <= right.UtcDateTime; } public static bool operator >(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime > right.UtcDateTime; } public static bool operator >=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime >= right.UtcDateTime; } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CrystalDecisions.Shared; namespace WebApplication2 { /// <summary> /// Summary description for frmResourcesInfo. /// </summary> public partial class frmProfilesCon: System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here loadProfiles(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void loadProfiles() { if (!IsPostBack) { if (Session["CM"] != null) { lblOrg.Text = "Household Characteristics for: " + Session["OrgName"].ToString(); } lblFunction.Text="Please check all items that are true for you or your household"; loadData(); } } private void loadData() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveProfilesAll"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Type",SqlDbType.NVarChar); cmd.Parameters["@Type"].Value=Session["Type"].ToString(); cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"ProfilesAll"); Session["ds"] = ds; DataGrid1.DataSource=ds; DataGrid1.DataBind(); refreshGrid(); } protected void btnOK_Click(object sender, System.EventArgs e) { if (Session["CM"] != null) { prepareReport(); } else { deleteGrid(); updateGrid(); Exit(); } } private void deleteGrid() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_DeleteProfileOrg"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } private void updateGrid() { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[3].FindControl("cbxSel")); if (cb.Checked) { SqlCommand cmd1=new SqlCommand(); cmd1.CommandType=CommandType.StoredProcedure; cmd1.CommandText="eps_UpdateProfileOrg"; cmd1.Connection=this.epsDbConn; cmd1.Parameters.Add ("@OrgId",SqlDbType.Int); cmd1.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd1.Parameters.Add ("@ProfileId",SqlDbType.Int); cmd1.Parameters["@ProfileId"].Value=i.Cells[0].Text; cmd1.Connection.Open(); cmd1.ExecuteNonQuery(); cmd1.Connection.Close(); } } } private void refreshGrid() { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[3].FindControl("cbxSel")); SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.Text; cmd.CommandText="Select Id from ProfileOrg" + " Where OrgId = " + Session["OrgId"].ToString() + " and ProfileId = " + i.Cells[0].Text; cmd.Connection.Open(); if (cmd.ExecuteScalar() != null) cb.Checked = true; cmd.Connection.Close(); } } private void Exit() { Response.Redirect (strURL + Session["CSProfilesCon"].ToString() + ".aspx?"); } protected void btnCancel_Click(object sender, System.EventArgs e) { Response.Redirect (strURL + Session["CSProfilesCon"].ToString() + ".aspx?"); } private void rpts() { Session["cRG"] = "frmMainWP"; Response.Redirect(strURL + "frmReportGen.aspx?"); } private void prepareReport() { ParameterFields myParams = new ParameterFields(); ParameterField myParam = new ParameterField(); ParameterDiscreteValue myDiscreteValue = new ParameterDiscreteValue(); myParam.ParameterFieldName = "ProfileId"; //Reuse myDiscreteValue foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[3].FindControl("cbxSel")); if (cb.Checked) { myDiscreteValue = new ParameterDiscreteValue(); myDiscreteValue.Value = i.Cells[0].Text; myParam.CurrentValues.Add(myDiscreteValue); /* SqlCommand cmd1 = new SqlCommand(); cmd1.CommandType = CommandType.StoredProcedure; cmd1.CommandText = "eps_UpdateProfileOrg"; cmd1.Connection = this.epsDbConn; cmd1.Parameters.Add("@OrgId", SqlDbType.Int); cmd1.Parameters["@OrgId"].Value = Session["OrgId"].ToString(); cmd1.Parameters.Add("@ProfileId", SqlDbType.Int); cmd1.Parameters["@ProfileId"].Value = ; cmd1.Connection.Open(); cmd1.ExecuteNonQuery(); cmd1.Connection.Close();*/ } } // Add param object to params collection myParams.Add(myParam); // Assign the params collection to the report viewer Session["ReportParameters"] = myParams; Session["ReportName"] = "rptHouseholdPlan.rpt"; rpts(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; namespace System.IO { // Provides methods for processing file system strings in a cross-platform manner. // Most of the methods don't do a complete parsing (such as examining a UNC hostname), // but they will handle most string operations. public static partial class Path { // Public static readonly variant of the separators. The Path implementation itself is using // internal const variant of the separators for better performance. public static readonly char DirectorySeparatorChar = PathInternal.DirectorySeparatorChar; public static readonly char AltDirectorySeparatorChar = PathInternal.AltDirectorySeparatorChar; public static readonly char VolumeSeparatorChar = PathInternal.VolumeSeparatorChar; public static readonly char PathSeparator = PathInternal.PathSeparator; // For generating random file names // 8 random bytes provides 12 chars in our encoding for the 8.3 name. private const int KeyLength = 8; [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] public static readonly char[] InvalidPathChars = GetInvalidPathChars(); // Changes the extension of a file path. The path parameter // specifies a file path, and the extension parameter // specifies a file extension (with a leading period, such as // ".exe" or ".cs"). // // The function returns a file path with the same root, directory, and base // name parts as path, but with the file extension changed to // the specified extension. If path is null, the function // returns null. If path does not contain a file extension, // the new file extension is appended to the path. If extension // is null, any existing extension is removed from path. public static string ChangeExtension(string path, string extension) { if (path != null) { PathInternal.CheckInvalidPathChars(path); string s = path; for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { s = path.Substring(0, i); break; } if (PathInternal.IsDirectoryOrVolumeSeparator(ch)) break; } if (extension != null && path.Length != 0) { s = (extension.Length == 0 || extension[0] != '.') ? s + "." + extension : s + extension; } return s; } return null; } // Returns the directory path of a file path. This method effectively // removes the last element of the given file path, i.e. it returns a // string consisting of all characters up to but not including the last // backslash ("\") in the file path. The returned value is null if the file // path is null or if the file path denotes a root (such as "\", "C:", or // "\\server\share"). public static string GetDirectoryName(string path) { if (string.IsNullOrWhiteSpace(path)) { if (path == null) return null; throw new ArgumentException(SR.Arg_PathIllegal, nameof(path)); } PathInternal.CheckInvalidPathChars(path); path = PathInternal.NormalizeDirectorySeparators(path); int root = PathInternal.GetRootLength(path); int i = path.Length; if (i > root) { while (i > root && !PathInternal.IsDirectorySeparator(path[--i])) ; return path.Substring(0, i); } return null; } // Returns the extension of the given path. The returned value includes the // period (".") character of the extension except when you have a terminal period when you get string.Empty, such as ".exe" or // ".cpp". The returned value is null if the given path is // null or if the given path does not include an extension. [Pure] public static string GetExtension(string path) { if (path == null) return null; PathInternal.CheckInvalidPathChars(path); int length = path.Length; for (int i = length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { if (i != length - 1) return path.Substring(i, length - i); else return string.Empty; } if (PathInternal.IsDirectoryOrVolumeSeparator(ch)) break; } return string.Empty; } // Returns the name and extension parts of the given path. The resulting // string contains the characters of path that follow the last // separator in path. The resulting string is null if path is null. [Pure] public static string GetFileName(string path) { if (path == null) return null; int offset = PathInternal.FindFileNameIndex(path); int count = path.Length - offset; return path.Substring(offset, count); } [Pure] public static string GetFileNameWithoutExtension(string path) { if (path == null) return null; int length = path.Length; int offset = PathInternal.FindFileNameIndex(path); int end = path.LastIndexOf('.', length - 1, length - offset); return end == -1 ? path.Substring(offset) : // No extension was found path.Substring(offset, end - offset); } // Returns a cryptographically strong random 8.3 string that can be // used as either a folder name or a file name. public static unsafe string GetRandomFileName() { byte* pKey = stackalloc byte[KeyLength]; Interop.GetRandomBytes(pKey, KeyLength); const int RandomFileNameLength = 12; char* pRandomFileName = stackalloc char[RandomFileNameLength]; Populate83FileNameFromRandomBytes(pKey, KeyLength, pRandomFileName, RandomFileNameLength); return new string(pRandomFileName, 0, RandomFileNameLength); } // Tests if a path includes a file extension. The result is // true if the characters that follow the last directory // separator ('\\' or '/') or volume separator (':') in the path include // a period (".") other than a terminal period. The result is false otherwise. [Pure] public static bool HasExtension(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { return i != path.Length - 1; } if (PathInternal.IsDirectoryOrVolumeSeparator(ch)) break; } } return false; } public static string Combine(string path1, string path2) { if (path1 == null || path2 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1) : nameof(path2)); Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); return CombineNoChecks(path1, path2); } public static string Combine(string path1, string path2, string path3) { if (path1 == null || path2 == null || path3 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : nameof(path3)); Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); PathInternal.CheckInvalidPathChars(path3); return CombineNoChecks(path1, path2, path3); } public static string Combine(string path1, string path2, string path3, string path4) { if (path1 == null || path2 == null || path3 == null || path4 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : (path3 == null) ? nameof(path3) : nameof(path4)); Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); PathInternal.CheckInvalidPathChars(path3); PathInternal.CheckInvalidPathChars(path4); return CombineNoChecks(path1, path2, path3, path4); } public static string Combine(params string[] paths) { if (paths == null) { throw new ArgumentNullException(nameof(paths)); } Contract.EndContractBlock(); int finalSize = 0; int firstComponent = 0; // We have two passes, the first calculates how large a buffer to allocate and does some precondition // checks on the paths passed in. The second actually does the combination. for (int i = 0; i < paths.Length; i++) { if (paths[i] == null) { throw new ArgumentNullException(nameof(paths)); } if (paths[i].Length == 0) { continue; } PathInternal.CheckInvalidPathChars(paths[i]); if (IsPathRooted(paths[i])) { firstComponent = i; finalSize = paths[i].Length; } else { finalSize += paths[i].Length; } char ch = paths[i][paths[i].Length - 1]; if (!PathInternal.IsDirectoryOrVolumeSeparator(ch)) finalSize++; } StringBuilder finalPath = StringBuilderCache.Acquire(finalSize); for (int i = firstComponent; i < paths.Length; i++) { if (paths[i].Length == 0) { continue; } if (finalPath.Length == 0) { finalPath.Append(paths[i]); } else { char ch = finalPath[finalPath.Length - 1]; if (!PathInternal.IsDirectoryOrVolumeSeparator(ch)) { finalPath.Append(PathInternal.DirectorySeparatorChar); } finalPath.Append(paths[i]); } } return StringBuilderCache.GetStringAndRelease(finalPath); } private static string CombineNoChecks(string path1, string path2) { if (path2.Length == 0) return path1; if (path1.Length == 0) return path2; if (IsPathRooted(path2)) return path2; char ch = path1[path1.Length - 1]; return PathInternal.IsDirectoryOrVolumeSeparator(ch) ? path1 + path2 : path1 + PathInternal.DirectorySeparatorCharAsString + path2; } private static string CombineNoChecks(string path1, string path2, string path3) { if (path1.Length == 0) return CombineNoChecks(path2, path3); if (path2.Length == 0) return CombineNoChecks(path1, path3); if (path3.Length == 0) return CombineNoChecks(path1, path2); if (IsPathRooted(path3)) return path3; if (IsPathRooted(path2)) return CombineNoChecks(path2, path3); bool hasSep1 = PathInternal.IsDirectoryOrVolumeSeparator(path1[path1.Length - 1]); bool hasSep2 = PathInternal.IsDirectoryOrVolumeSeparator(path2[path2.Length - 1]); if (hasSep1 && hasSep2) { return path1 + path2 + path3; } else if (hasSep1) { return path1 + path2 + PathInternal.DirectorySeparatorCharAsString + path3; } else if (hasSep2) { return path1 + PathInternal.DirectorySeparatorCharAsString + path2 + path3; } else { // string.Concat only has string-based overloads up to four arguments; after that requires allocating // a params string[]. Instead, try to use a cached StringBuilder. StringBuilder sb = StringBuilderCache.Acquire(path1.Length + path2.Length + path3.Length + 2); sb.Append(path1) .Append(PathInternal.DirectorySeparatorChar) .Append(path2) .Append(PathInternal.DirectorySeparatorChar) .Append(path3); return StringBuilderCache.GetStringAndRelease(sb); } } private static string CombineNoChecks(string path1, string path2, string path3, string path4) { if (path1.Length == 0) return CombineNoChecks(path2, path3, path4); if (path2.Length == 0) return CombineNoChecks(path1, path3, path4); if (path3.Length == 0) return CombineNoChecks(path1, path2, path4); if (path4.Length == 0) return CombineNoChecks(path1, path2, path3); if (IsPathRooted(path4)) return path4; if (IsPathRooted(path3)) return CombineNoChecks(path3, path4); if (IsPathRooted(path2)) return CombineNoChecks(path2, path3, path4); bool hasSep1 = PathInternal.IsDirectoryOrVolumeSeparator(path1[path1.Length - 1]); bool hasSep2 = PathInternal.IsDirectoryOrVolumeSeparator(path2[path2.Length - 1]); bool hasSep3 = PathInternal.IsDirectoryOrVolumeSeparator(path3[path3.Length - 1]); if (hasSep1 && hasSep2 && hasSep3) { // Use string.Concat overload that takes four strings return path1 + path2 + path3 + path4; } else { // string.Concat only has string-based overloads up to four arguments; after that requires allocating // a params string[]. Instead, try to use a cached StringBuilder. StringBuilder sb = StringBuilderCache.Acquire(path1.Length + path2.Length + path3.Length + path4.Length + 3); sb.Append(path1); if (!hasSep1) { sb.Append(PathInternal.DirectorySeparatorChar); } sb.Append(path2); if (!hasSep2) { sb.Append(PathInternal.DirectorySeparatorChar); } sb.Append(path3); if (!hasSep3) { sb.Append(PathInternal.DirectorySeparatorChar); } sb.Append(path4); return StringBuilderCache.GetStringAndRelease(sb); } } private static readonly char[] s_base32Char = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5'}; private static unsafe void Populate83FileNameFromRandomBytes(byte* bytes, int byteCount, char* chars, int charCount) { Debug.Assert(bytes != null); Debug.Assert(chars != null); // This method requires bytes of length 8 and chars of length 12. Debug.Assert(byteCount == 8, $"Unexpected {nameof(byteCount)}"); Debug.Assert(charCount == 12, $"Unexpected {nameof(charCount)}"); byte b0 = bytes[0]; byte b1 = bytes[1]; byte b2 = bytes[2]; byte b3 = bytes[3]; byte b4 = bytes[4]; // Consume the 5 Least significant bits of the first 5 bytes chars[0] = s_base32Char[b0 & 0x1F]; chars[1] = s_base32Char[b1 & 0x1F]; chars[2] = s_base32Char[b2 & 0x1F]; chars[3] = s_base32Char[b3 & 0x1F]; chars[4] = s_base32Char[b4 & 0x1F]; // Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4 chars[5] = s_base32Char[( ((b0 & 0xE0) >> 5) | ((b3 & 0x60) >> 2))]; chars[6] = s_base32Char[( ((b1 & 0xE0) >> 5) | ((b4 & 0x60) >> 2))]; // Consume 3 MSB bits of b2, 1 MSB bit of b3, b4 b2 >>= 5; Debug.Assert(((b2 & 0xF8) == 0), "Unexpected set bits"); if ((b3 & 0x80) != 0) b2 |= 0x08; if ((b4 & 0x80) != 0) b2 |= 0x10; chars[7] = s_base32Char[b2]; // Set the file extension separator chars[8] = '.'; // Consume the 5 Least significant bits of the remaining 3 bytes chars[9] = s_base32Char[(bytes[5] & 0x1F)]; chars[10] = s_base32Char[(bytes[6] & 0x1F)]; chars[11] = s_base32Char[(bytes[7] & 0x1F)]; } /// <summary> /// Create a relative path from one path to another. Paths will be resolved before calculating the difference. /// Default path comparison for the active platform will be used (OrdinalIgnoreCase for Windows or Mac, Ordinal for Unix). /// </summary> /// <param name="relativeTo">The source path the output should be relative to. This path is always considered to be a directory.</param> /// <param name="path">The destination path.</param> /// <returns>The relative path or <paramref name="path"/> if the paths don't share the same root.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="relativeTo"/> or <paramref name="path"/> is <c>null</c> or an empty string.</exception> public static string GetRelativePath(string relativeTo, string path) { return GetRelativePath(relativeTo, path, StringComparison); } private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType) { if (string.IsNullOrEmpty(relativeTo)) throw new ArgumentNullException(nameof(relativeTo)); if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException(nameof(path)); Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase); relativeTo = GetFullPath(relativeTo); path = GetFullPath(path); // Need to check if the roots are different- if they are we need to return the "to" path. if (!PathInternal.AreRootsEqual(relativeTo, path, comparisonType)) return path; int commonLength = PathInternal.GetCommonPathLength(relativeTo, path, ignoreCase: comparisonType == StringComparison.OrdinalIgnoreCase); // If there is nothing in common they can't share the same root, return the "to" path as is. if (commonLength == 0) return path; // Trailing separators aren't significant for comparison int relativeToLength = relativeTo.Length; if (PathInternal.EndsInDirectorySeparator(relativeTo)) relativeToLength--; bool pathEndsInSeparator = PathInternal.EndsInDirectorySeparator(path); int pathLength = path.Length; if (pathEndsInSeparator) pathLength--; // If we have effectively the same path, return "." if (relativeToLength == pathLength && commonLength >= relativeToLength) return "."; // We have the same root, we need to calculate the difference now using the // common Length and Segment count past the length. // // Some examples: // // C:\Foo C:\Bar L3, S1 -> ..\Bar // C:\Foo C:\Foo\Bar L6, S0 -> Bar // C:\Foo\Bar C:\Bar\Bar L3, S2 -> ..\..\Bar\Bar // C:\Foo\Foo C:\Foo\Bar L7, S1 -> ..\Bar StringBuilder sb = StringBuilderCache.Acquire(Math.Max(relativeTo.Length, path.Length)); // Add parent segments for segments past the common on the "from" path if (commonLength < relativeToLength) { sb.Append(PathInternal.ParentDirectoryPrefix); for (int i = commonLength; i < relativeToLength; i++) { if (PathInternal.IsDirectorySeparator(relativeTo[i])) { sb.Append(PathInternal.ParentDirectoryPrefix); } } } else if (PathInternal.IsDirectorySeparator(path[commonLength])) { // No parent segments and we need to eat the initial separator // (C:\Foo C:\Foo\Bar case) commonLength++; } // Now add the rest of the "to" path, adding back the trailing separator int count = pathLength - commonLength; if (pathEndsInSeparator) count++; sb.Append(path, commonLength, count); return StringBuilderCache.GetStringAndRelease(sb); } // StringComparison and IsCaseSensitive are also available in PathInternal.CaseSensitivity but we are // too low in System.Runtime.Extensions to use it (no FileStream, etc.) /// <summary>Returns a comparison that can be used to compare file and directory names for equality.</summary> internal static StringComparison StringComparison { get { return IsCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; } } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using FluentAssertions; using Humanizer; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.Filtering { public sealed class FilterOperatorTests : IClassFixture<IntegrationTestContext<TestableStartup<FilterDbContext>, FilterDbContext>> { private readonly IntegrationTestContext<TestableStartup<FilterDbContext>, FilterDbContext> _testContext; public FilterOperatorTests(IntegrationTestContext<TestableStartup<FilterDbContext>, FilterDbContext> testContext) { _testContext = testContext; testContext.UseController<FilterableResourcesController>(); var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.EnableLegacyFilterNotation = false; } [Fact] public async Task Can_filter_equality_on_special_characters() { // Arrange var resource = new FilterableResource { SomeString = "This, that & more" }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, new FilterableResource()); await dbContext.SaveChangesAsync(); }); string route = $"/filterableResources?filter=equals(someString,'{HttpUtility.UrlEncode(resource.SomeString)}')"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someString"].Should().Be(resource.SomeString); } [Fact] public async Task Can_filter_equality_on_two_attributes_of_same_type() { // Arrange var resource = new FilterableResource { SomeInt32 = 5, OtherInt32 = 5 }; var otherResource = new FilterableResource { SomeInt32 = 5, OtherInt32 = 10 }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, otherResource); await dbContext.SaveChangesAsync(); }); const string route = "/filterableResources?filter=equals(someInt32,otherInt32)"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someInt32"].Should().Be(resource.SomeInt32); responseDocument.Data.ManyValue[0].Attributes["otherInt32"].Should().Be(resource.OtherInt32); } [Fact] public async Task Can_filter_equality_on_two_attributes_of_same_nullable_type() { // Arrange var resource = new FilterableResource { SomeNullableInt32 = 5, OtherNullableInt32 = 5 }; var otherResource = new FilterableResource { SomeNullableInt32 = 5, OtherNullableInt32 = 10 }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, otherResource); await dbContext.SaveChangesAsync(); }); const string route = "/filterableResources?filter=equals(someNullableInt32,otherNullableInt32)"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someNullableInt32"].Should().Be(resource.SomeNullableInt32); responseDocument.Data.ManyValue[0].Attributes["otherNullableInt32"].Should().Be(resource.OtherNullableInt32); } [Fact] public async Task Can_filter_equality_on_two_attributes_with_nullable_at_start() { // Arrange var resource = new FilterableResource { SomeInt32 = 5, SomeNullableInt32 = 5 }; var otherResource = new FilterableResource { SomeInt32 = 5, SomeNullableInt32 = 10 }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, otherResource); await dbContext.SaveChangesAsync(); }); const string route = "/filterableResources?filter=equals(someNullableInt32,someInt32)"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someInt32"].Should().Be(resource.SomeInt32); responseDocument.Data.ManyValue[0].Attributes["someNullableInt32"].Should().Be(resource.SomeNullableInt32); } [Fact] public async Task Can_filter_equality_on_two_attributes_with_nullable_at_end() { // Arrange var resource = new FilterableResource { SomeInt32 = 5, SomeNullableInt32 = 5 }; var otherResource = new FilterableResource { SomeInt32 = 5, SomeNullableInt32 = 10 }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, otherResource); await dbContext.SaveChangesAsync(); }); const string route = "/filterableResources?filter=equals(someInt32,someNullableInt32)"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someInt32"].Should().Be(resource.SomeInt32); responseDocument.Data.ManyValue[0].Attributes["someNullableInt32"].Should().Be(resource.SomeNullableInt32); } [Fact] public async Task Can_filter_equality_on_two_attributes_of_compatible_types() { // Arrange var resource = new FilterableResource { SomeInt32 = 5, SomeUnsignedInt64 = 5 }; var otherResource = new FilterableResource { SomeInt32 = 5, SomeUnsignedInt64 = 10 }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, otherResource); await dbContext.SaveChangesAsync(); }); const string route = "/filterableResources?filter=equals(someInt32,someUnsignedInt64)"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someInt32"].Should().Be(resource.SomeInt32); responseDocument.Data.ManyValue[0].Attributes["someUnsignedInt64"].Should().Be(resource.SomeUnsignedInt64); } [Fact] public async Task Cannot_filter_equality_on_two_attributes_of_incompatible_types() { // Arrange const string route = "/filterableResources?filter=equals(someDouble,someTimeSpan)"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Query creation failed due to incompatible types."); error.Detail.Should().Be("No coercion operator is defined between types 'System.TimeSpan' and 'System.Double'."); error.Source.Should().BeNull(); } [Theory] [InlineData(19, 21, ComparisonOperator.LessThan, 20)] [InlineData(19, 21, ComparisonOperator.LessThan, 21)] [InlineData(19, 21, ComparisonOperator.LessOrEqual, 20)] [InlineData(19, 21, ComparisonOperator.LessOrEqual, 19)] [InlineData(21, 19, ComparisonOperator.GreaterThan, 20)] [InlineData(21, 19, ComparisonOperator.GreaterThan, 19)] [InlineData(21, 19, ComparisonOperator.GreaterOrEqual, 20)] [InlineData(21, 19, ComparisonOperator.GreaterOrEqual, 21)] public async Task Can_filter_comparison_on_whole_number(int matchingValue, int nonMatchingValue, ComparisonOperator filterOperator, double filterValue) { // Arrange var resource = new FilterableResource { SomeInt32 = matchingValue }; var otherResource = new FilterableResource { SomeInt32 = nonMatchingValue }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, otherResource); await dbContext.SaveChangesAsync(); }); string route = $"/filterableResources?filter={filterOperator.ToString().Camelize()}(someInt32,'{filterValue}')"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someInt32"].Should().Be(resource.SomeInt32); } [Theory] [InlineData(1.9, 2.1, ComparisonOperator.LessThan, 2.0)] [InlineData(1.9, 2.1, ComparisonOperator.LessThan, 2.1)] [InlineData(1.9, 2.1, ComparisonOperator.LessOrEqual, 2.0)] [InlineData(1.9, 2.1, ComparisonOperator.LessOrEqual, 1.9)] [InlineData(2.1, 1.9, ComparisonOperator.GreaterThan, 2.0)] [InlineData(2.1, 1.9, ComparisonOperator.GreaterThan, 1.9)] [InlineData(2.1, 1.9, ComparisonOperator.GreaterOrEqual, 2.0)] [InlineData(2.1, 1.9, ComparisonOperator.GreaterOrEqual, 2.1)] public async Task Can_filter_comparison_on_fractional_number(double matchingValue, double nonMatchingValue, ComparisonOperator filterOperator, double filterValue) { // Arrange var resource = new FilterableResource { SomeDouble = matchingValue }; var otherResource = new FilterableResource { SomeDouble = nonMatchingValue }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, otherResource); await dbContext.SaveChangesAsync(); }); string route = $"/filterableResources?filter={filterOperator.ToString().Camelize()}(someDouble,'{filterValue}')"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someDouble"].Should().Be(resource.SomeDouble); } [Theory] [InlineData("2001-01-01", "2001-01-09", ComparisonOperator.LessThan, "2001-01-05")] [InlineData("2001-01-01", "2001-01-09", ComparisonOperator.LessThan, "2001-01-09")] [InlineData("2001-01-01", "2001-01-09", ComparisonOperator.LessOrEqual, "2001-01-05")] [InlineData("2001-01-01", "2001-01-09", ComparisonOperator.LessOrEqual, "2001-01-01")] [InlineData("2001-01-09", "2001-01-01", ComparisonOperator.GreaterThan, "2001-01-05")] [InlineData("2001-01-09", "2001-01-01", ComparisonOperator.GreaterThan, "2001-01-01")] [InlineData("2001-01-09", "2001-01-01", ComparisonOperator.GreaterOrEqual, "2001-01-05")] [InlineData("2001-01-09", "2001-01-01", ComparisonOperator.GreaterOrEqual, "2001-01-09")] public async Task Can_filter_comparison_on_DateTime(string matchingDateTime, string nonMatchingDateTime, ComparisonOperator filterOperator, string filterDateTime) { // Arrange var resource = new FilterableResource { SomeDateTime = DateTime.ParseExact(matchingDateTime, "yyyy-MM-dd", null) }; var otherResource = new FilterableResource { SomeDateTime = DateTime.ParseExact(nonMatchingDateTime, "yyyy-MM-dd", null) }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, otherResource); await dbContext.SaveChangesAsync(); }); string route = $"/filterableResources?filter={filterOperator.ToString().Camelize()}(someDateTime," + $"'{DateTime.ParseExact(filterDateTime, "yyyy-MM-dd", null)}')"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someDateTime"].As<DateTime>().Should().BeCloseTo(resource.SomeDateTime); } [Theory] [InlineData("The fox jumped over the lazy dog", "Other", TextMatchKind.Contains, "jumped")] [InlineData("The fox jumped over the lazy dog", "the fox...", TextMatchKind.Contains, "The")] [InlineData("The fox jumped over the lazy dog", "The fox jumped", TextMatchKind.Contains, "dog")] [InlineData("The fox jumped over the lazy dog", "Yesterday The fox...", TextMatchKind.StartsWith, "The")] [InlineData("The fox jumped over the lazy dog", "over the lazy dog earlier", TextMatchKind.EndsWith, "dog")] public async Task Can_filter_text_match(string matchingText, string nonMatchingText, TextMatchKind matchKind, string filterText) { // Arrange var resource = new FilterableResource { SomeString = matchingText }; var otherResource = new FilterableResource { SomeString = nonMatchingText }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, otherResource); await dbContext.SaveChangesAsync(); }); string route = $"/filterableResources?filter={matchKind.ToString().Camelize()}(someString,'{filterText}')"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someString"].Should().Be(resource.SomeString); } [Theory] [InlineData("two", "one two", "'one','two','three'")] [InlineData("two", "nine", "'one','two','three','four','five'")] public async Task Can_filter_in_set(string matchingText, string nonMatchingText, string filterText) { // Arrange var resource = new FilterableResource { SomeString = matchingText }; var otherResource = new FilterableResource { SomeString = nonMatchingText }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, otherResource); await dbContext.SaveChangesAsync(); }); string route = $"/filterableResources?filter=any(someString,{filterText})"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Attributes["someString"].Should().Be(resource.SomeString); } [Fact] public async Task Can_filter_on_has() { // Arrange var resource = new FilterableResource { Children = new List<FilterableResource> { new() } }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, new FilterableResource()); await dbContext.SaveChangesAsync(); }); const string route = "/filterableResources?filter=has(children)"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(resource.StringId); } [Fact] public async Task Can_filter_on_has_with_nested_condition() { // Arrange var resources = new List<FilterableResource> { new() { Children = new List<FilterableResource> { new() { SomeBoolean = false } } }, new() { Children = new List<FilterableResource> { new() { SomeBoolean = true } } } }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resources); await dbContext.SaveChangesAsync(); }); const string route = "/filterableResources?filter=has(children,equals(someBoolean,'true'))"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(resources[1].StringId); } [Fact] public async Task Can_filter_on_count() { // Arrange var resource = new FilterableResource { Children = new List<FilterableResource> { new(), new() } }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource, new FilterableResource()); await dbContext.SaveChangesAsync(); }); const string route = "/filterableResources?filter=equals(count(children),'2')"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(resource.StringId); } [Theory] [InlineData("and(equals(someString,'ABC'),equals(someInt32,'11'))")] [InlineData("and(equals(someString,'ABC'),equals(someInt32,'11'),equals(someEnum,'Tuesday'))")] [InlineData("or(equals(someString,'---'),lessThan(someInt32,'33'))")] [InlineData("not(equals(someEnum,'Saturday'))")] public async Task Can_filter_on_logical_functions(string filterExpression) { // Arrange var resource1 = new FilterableResource { SomeString = "ABC", SomeInt32 = 11, SomeEnum = DayOfWeek.Tuesday }; var resource2 = new FilterableResource { SomeString = "XYZ", SomeInt32 = 99, SomeEnum = DayOfWeek.Saturday }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<FilterableResource>(); dbContext.FilterableResources.AddRange(resource1, resource2); await dbContext.SaveChangesAsync(); }); string route = $"/filterableResources?filter={filterExpression}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(resource1.StringId); } } }
/// Credit glennpow, Zarlang /// Sourced from - http://forum.unity3d.com/threads/free-script-particle-systems-in-ui-screen-space-overlay.406862/ /// Updated by Zarlang with a more robust implementation, including TextureSheet annimation support namespace UnityEngine.UI.Extensions { #if UNITY_5_3_OR_NEWER [ExecuteInEditMode] [RequireComponent(typeof(CanvasRenderer), typeof(ParticleSystem))] [AddComponentMenu("UI/Effects/Extensions/UIParticleSystem")] public class UIParticleSystem : MaskableGraphic { [Tooltip("Having this enabled run the system in LateUpdate rather than in Update making it faster but less precise (more clunky)")] public bool fixedTime = true; private Transform _transform; private ParticleSystem pSystem; private ParticleSystem.Particle[] particles; private UIVertex[] _quad = new UIVertex[4]; private Vector4 imageUV = Vector4.zero; private ParticleSystem.TextureSheetAnimationModule textureSheetAnimation; private int textureSheetAnimationFrames; private Vector2 textureSheetAnimationFrameSize; private ParticleSystemRenderer pRenderer; private Material currentMaterial; private Texture currentTexture; #if UNITY_5_5_OR_NEWER private ParticleSystem.MainModule mainModule; #endif public override Texture mainTexture { get { return currentTexture; } } protected bool Initialize() { // initialize members if (_transform == null) { _transform = transform; } if (pSystem == null) { pSystem = GetComponent<ParticleSystem>(); if (pSystem == null) { return false; } #if UNITY_5_5_OR_NEWER mainModule = pSystem.main; if (pSystem.main.maxParticles > 14000) { mainModule.maxParticles = 14000; } #else if (pSystem.maxParticles > 14000) pSystem.maxParticles = 14000; #endif pRenderer = pSystem.GetComponent<ParticleSystemRenderer>(); if (pRenderer != null) pRenderer.enabled = false; Shader foundShader = Shader.Find("UI Extensions/Particles/Additive"); Material pMaterial = new Material(foundShader); if (material == null) material = pMaterial; currentMaterial = material; if (currentMaterial && currentMaterial.HasProperty("_MainTex")) { currentTexture = currentMaterial.mainTexture; if (currentTexture == null) currentTexture = Texture2D.whiteTexture; } material = currentMaterial; // automatically set scaling #if UNITY_5_5_OR_NEWER mainModule.scalingMode = ParticleSystemScalingMode.Hierarchy; #else pSystem.scalingMode = ParticleSystemScalingMode.Hierarchy; #endif particles = null; } #if UNITY_5_5_OR_NEWER if (particles == null) particles = new ParticleSystem.Particle[pSystem.main.maxParticles]; #else if (particles == null) particles = new ParticleSystem.Particle[pSystem.maxParticles]; #endif imageUV = new Vector4(0, 0, 1, 1); // prepare texture sheet animation textureSheetAnimation = pSystem.textureSheetAnimation; textureSheetAnimationFrames = 0; textureSheetAnimationFrameSize = Vector2.zero; if (textureSheetAnimation.enabled) { textureSheetAnimationFrames = textureSheetAnimation.numTilesX * textureSheetAnimation.numTilesY; textureSheetAnimationFrameSize = new Vector2(1f / textureSheetAnimation.numTilesX, 1f / textureSheetAnimation.numTilesY); } return true; } protected override void Awake() { base.Awake(); if (!Initialize()) enabled = false; } protected override void OnPopulateMesh(VertexHelper vh) { #if UNITY_EDITOR if (!Application.isPlaying) { if (!Initialize()) { return; } } #endif // prepare vertices vh.Clear(); if (!gameObject.activeInHierarchy) { return; } Vector2 temp = Vector2.zero; Vector2 corner1 = Vector2.zero; Vector2 corner2 = Vector2.zero; // iterate through current particles int count = pSystem.GetParticles(particles); for (int i = 0; i < count; ++i) { ParticleSystem.Particle particle = particles[i]; // get particle properties #if UNITY_5_5_OR_NEWER Vector2 position = (mainModule.simulationSpace == ParticleSystemSimulationSpace.Local ? particle.position : _transform.InverseTransformPoint(particle.position)); #else Vector2 position = (pSystem.simulationSpace == ParticleSystemSimulationSpace.Local ? particle.position : _transform.InverseTransformPoint(particle.position)); #endif float rotation = -particle.rotation * Mathf.Deg2Rad; float rotation90 = rotation + Mathf.PI / 2; Color32 color = particle.GetCurrentColor(pSystem); float size = particle.GetCurrentSize(pSystem) * 0.5f; // apply scale #if UNITY_5_5_OR_NEWER if (mainModule.scalingMode == ParticleSystemScalingMode.Shape) position /= canvas.scaleFactor; #else if (pSystem.scalingMode == ParticleSystemScalingMode.Shape) position /= canvas.scaleFactor; #endif // apply texture sheet animation Vector4 particleUV = imageUV; if (textureSheetAnimation.enabled) { #if UNITY_5_5_OR_NEWER float frameProgress = 1 - (particle.remainingLifetime / particle.startLifetime); if (textureSheetAnimation.frameOverTime.curveMin != null) { frameProgress = textureSheetAnimation.frameOverTime.curveMin.Evaluate(1 - (particle.remainingLifetime / particle.startLifetime)); } else if (textureSheetAnimation.frameOverTime.curve != null) { frameProgress = textureSheetAnimation.frameOverTime.curve.Evaluate(1 - (particle.remainingLifetime / particle.startLifetime)); } else if (textureSheetAnimation.frameOverTime.constant > 0) { frameProgress = textureSheetAnimation.frameOverTime.constant - (particle.remainingLifetime / particle.startLifetime); } #else float frameProgress = 1 - (particle.lifetime / particle.startLifetime); #endif frameProgress = Mathf.Repeat(frameProgress * textureSheetAnimation.cycleCount, 1); int frame = 0; switch (textureSheetAnimation.animation) { case ParticleSystemAnimationType.WholeSheet: frame = Mathf.FloorToInt(frameProgress * textureSheetAnimationFrames); break; case ParticleSystemAnimationType.SingleRow: frame = Mathf.FloorToInt(frameProgress * textureSheetAnimation.numTilesX); int row = textureSheetAnimation.rowIndex; // if (textureSheetAnimation.useRandomRow) { // FIXME - is this handled internally by rowIndex? // row = Random.Range(0, textureSheetAnimation.numTilesY, using: particle.randomSeed); // } frame += row * textureSheetAnimation.numTilesX; break; } frame %= textureSheetAnimationFrames; particleUV.x = (frame % textureSheetAnimation.numTilesX) * textureSheetAnimationFrameSize.x; particleUV.y = Mathf.FloorToInt(frame / textureSheetAnimation.numTilesX) * textureSheetAnimationFrameSize.y; particleUV.z = particleUV.x + textureSheetAnimationFrameSize.x; particleUV.w = particleUV.y + textureSheetAnimationFrameSize.y; } temp.x = particleUV.x; temp.y = particleUV.y; _quad[0] = UIVertex.simpleVert; _quad[0].color = color; _quad[0].uv0 = temp; temp.x = particleUV.x; temp.y = particleUV.w; _quad[1] = UIVertex.simpleVert; _quad[1].color = color; _quad[1].uv0 = temp; temp.x = particleUV.z; temp.y = particleUV.w; _quad[2] = UIVertex.simpleVert; _quad[2].color = color; _quad[2].uv0 = temp; temp.x = particleUV.z; temp.y = particleUV.y; _quad[3] = UIVertex.simpleVert; _quad[3].color = color; _quad[3].uv0 = temp; if (rotation == 0) { // no rotation corner1.x = position.x - size; corner1.y = position.y - size; corner2.x = position.x + size; corner2.y = position.y + size; temp.x = corner1.x; temp.y = corner1.y; _quad[0].position = temp; temp.x = corner1.x; temp.y = corner2.y; _quad[1].position = temp; temp.x = corner2.x; temp.y = corner2.y; _quad[2].position = temp; temp.x = corner2.x; temp.y = corner1.y; _quad[3].position = temp; } else { // apply rotation Vector2 right = new Vector2(Mathf.Cos(rotation), Mathf.Sin(rotation)) * size; Vector2 up = new Vector2(Mathf.Cos(rotation90), Mathf.Sin(rotation90)) * size; _quad[0].position = position - right - up; _quad[1].position = position - right + up; _quad[2].position = position + right + up; _quad[3].position = position + right - up; } vh.AddUIVertexQuad(_quad); } } void Update() { if (!fixedTime && Application.isPlaying) { pSystem.Simulate(Time.unscaledDeltaTime, false, false, true); SetAllDirty(); if ((currentMaterial != null && currentTexture != currentMaterial.mainTexture) || (material != null && currentMaterial != null && material.shader != currentMaterial.shader)) { pSystem = null; Initialize(); } } } void LateUpdate() { if (!Application.isPlaying) { SetAllDirty(); } else { if (fixedTime) { pSystem.Simulate(Time.unscaledDeltaTime, false, false, true); SetAllDirty(); if ((currentMaterial != null && currentTexture != currentMaterial.mainTexture) || (material != null && currentMaterial != null && material.shader != currentMaterial.shader)) { pSystem = null; Initialize(); } } } if (material == currentMaterial) return; pSystem = null; Initialize(); } } #endif }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using Xunit; namespace System.Runtime.Serialization.Xml.Tests { public static class XmlDictionaryReaderTests { [Fact] public static void ReadValueChunkReadEncodedDoubleWideChars() { // The test is to verify the fix made for the following issue: // When reading value chunk from XmlReader where Encoding.UTF8 is used, and where the // encoded bytes contains 4-byte UTF-8 encoded characters: if the 4 byte character is decoded // into 2 chars and the char[] only has one space left, an ArgumentException will be thrown // stating that there is not enough space to decode the bytes. string xmlPayloadHolder = @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/""><s:Body><Response xmlns=""http://tempuri.org/""><Result>{0}</Result></Response></s:Body></s:Envelope>"; int startWideChars = 0; int endWideChars = 128; int incrementWideChars = 1; for (int wideChars = startWideChars; wideChars < endWideChars; wideChars += incrementWideChars) { for (int singleByteChars = 0; singleByteChars < 4; singleByteChars++) { string testString = GenerateDoubleWideTestString(wideChars, singleByteChars); string returnedString; string xmlContent = string.Format(xmlPayloadHolder, testString); using (Stream stream = GenerateStreamFromString(xmlContent)) { var encoding = Encoding.UTF8; var quotas = new XmlDictionaryReaderQuotas(); XmlReader reader = XmlDictionaryReader.CreateTextReader(stream, encoding, quotas, null); reader.ReadStartElement(); // <s:Envelope> reader.ReadStartElement(); // <s:Body> reader.ReadStartElement(); // <Response> reader.ReadStartElement(); // <Result> Assert.True(reader.CanReadValueChunk, "reader.CanReadValueChunk is expected to be true, but it returned false."); var resultChars = new List<char>(); var buffer = new char[256]; int count = 0; while ((count = reader.ReadValueChunk(buffer, 0, buffer.Length)) > 0) { for (int i = 0; i < count; i++) { resultChars.Add(buffer[i]); } } returnedString = new string(resultChars.ToArray()); } Assert.StrictEqual(testString, returnedString); } } } [Fact] public static void ReadElementContentAsStringDataExceedsMaxBytesPerReadQuota() { XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas(); quotas.MaxBytesPerRead = 4096; int contentLength = 8176; string testString = new string('a', contentLength); string returnedString; XmlDictionary dict = new XmlDictionary(); XmlDictionaryString dictEntry = dict.Add("Value"); using (var ms = new MemoryStream()) { XmlDictionaryWriter xmlWriter = XmlDictionaryWriter.CreateBinaryWriter(ms, dict); xmlWriter.WriteElementString(dictEntry, XmlDictionaryString.Empty, testString); xmlWriter.Flush(); ms.Position = 0; XmlDictionaryReader xmlReader = XmlDictionaryReader.CreateBinaryReader(ms, dict, quotas); xmlReader.Read(); returnedString = xmlReader.ReadElementContentAsString(); } Assert.StrictEqual(testString, returnedString); } [Fact] public static void ReadElementContentAsDateTimeTest() { string xmlFileContent = @"<root><date>2013-01-02T03:04:05.006Z</date></root>"; Stream sm = GenerateStreamFromString(xmlFileContent); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(sm, XmlDictionaryReaderQuotas.Max); reader.ReadToFollowing("date"); DateTime dt = reader.ReadElementContentAsDateTime(); DateTime expected = new DateTime(2013, 1, 2, 3, 4, 5, 6, DateTimeKind.Utc); Assert.Equal(expected, dt); } [Fact] public static void ReadElementContentAsBinHexTest() { string xmlFileContent = @"<data>540068006500200071007500690063006B002000620072006F0077006E00200066006F00780020006A0075006D007000730020006F00760065007200200074006800650020006C0061007A007900200064006F0067002E00</data>"; Stream sm = GenerateStreamFromString(xmlFileContent); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(sm, XmlDictionaryReaderQuotas.Max); reader.ReadToFollowing("data"); byte[] bytes = reader.ReadElementContentAsBinHex(); byte[] expected = Encoding.Unicode.GetBytes("The quick brown fox jumps over the lazy dog."); Assert.Equal(expected, bytes); } [Fact] public static void GetNonAtomizedNamesTest() { string localNameTest = "localNameTest"; string namespaceUriTest = "http://www.msn.com/"; var encoding = Encoding.UTF8; var rndGen = new Random(); int byteArrayLength = rndGen.Next(100, 2000); byte[] byteArray = new byte[byteArrayLength]; rndGen.NextBytes(byteArray); MemoryStream ms = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms, encoding); writer.WriteElementString(localNameTest, namespaceUriTest, "value"); writer.Flush(); ms.Position = 0; XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(ms, encoding, XmlDictionaryReaderQuotas.Max, null); bool success = reader.ReadToDescendant(localNameTest); Assert.True(success); string localName; string namespaceUriStr; reader.GetNonAtomizedNames(out localName, out namespaceUriStr); Assert.Equal(localNameTest, localName); Assert.Equal(namespaceUriTest, namespaceUriStr); writer.Close(); } [Fact] public static void ReadStringTest() { MemoryStream stream = new MemoryStream(); XmlDictionary dictionary = new XmlDictionary(); List<XmlDictionaryString> stringList = new List<XmlDictionaryString>(); stringList.Add(dictionary.Add("Name")); stringList.Add(dictionary.Add("urn:Test")); using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream, dictionary, null)) { // write using the dictionary - element name, namespace, value string value = "value"; writer.WriteElementString(stringList[0], stringList[1], value); writer.Flush(); stream.Position = 0; XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, dictionary, new XmlDictionaryReaderQuotas()); reader.Read(); string s = reader.ReadString(); Assert.Equal(value, s); } } private static Stream GenerateStreamFromString(string s) { var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(s); writer.Flush(); stream.Position = 0; return stream; } private static string GenerateDoubleWideTestString(int charsToGenerate, int singleByteChars) { int count = 0; int startChar = 0x10000; var sb = new StringBuilder(); while (count < singleByteChars) { sb.Append((char)('a' + count % 26)); count++; } count = 0; while (count < charsToGenerate) { sb.Append(char.ConvertFromUtf32(startChar + count % 65535)); count++; } return sb.ToString(); } [Fact] public static void Close_DerivedReader_Success() { new NotImplementedXmlDictionaryReader().Close(); } private sealed class NotImplementedXmlDictionaryReader : XmlDictionaryReader { public override ReadState ReadState => ReadState.Initial; public override int AttributeCount => throw new NotImplementedException(); public override string BaseURI => throw new NotImplementedException(); public override int Depth => throw new NotImplementedException(); public override bool EOF => throw new NotImplementedException(); public override bool IsEmptyElement => throw new NotImplementedException(); public override string LocalName => throw new NotImplementedException(); public override string NamespaceURI => throw new NotImplementedException(); public override XmlNameTable NameTable => throw new NotImplementedException(); public override XmlNodeType NodeType => throw new NotImplementedException(); public override string Prefix => throw new NotImplementedException(); public override string Value => throw new NotImplementedException(); public override string GetAttribute(int i) => throw new NotImplementedException(); public override string GetAttribute(string name) => throw new NotImplementedException(); public override string GetAttribute(string name, string namespaceURI) => throw new NotImplementedException(); public override string LookupNamespace(string prefix) => throw new NotImplementedException(); public override bool MoveToAttribute(string name) => throw new NotImplementedException(); public override bool MoveToAttribute(string name, string ns) => throw new NotImplementedException(); public override bool MoveToElement() => throw new NotImplementedException(); public override bool MoveToFirstAttribute() => throw new NotImplementedException(); public override bool MoveToNextAttribute() => throw new NotImplementedException(); public override bool Read() => throw new NotImplementedException(); public override bool ReadAttributeValue() => throw new NotImplementedException(); public override void ResolveEntity() => throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Hosting; using Nop.Core.Data; using Nop.Core.Infrastructure; namespace Nop.Core { /// <summary> /// Represents a common helper /// </summary> public partial class WebHelper : IWebHelper { #region Fields private readonly HttpContextBase _httpContext; #endregion #region Utilities protected virtual Boolean IsRequestAvailable(HttpContextBase httpContext) { if (httpContext == null) return false; try { if (httpContext.Request == null) return false; } catch (HttpException ex) { return false; } return true; } protected virtual bool TryWriteWebConfig() { try { // In medium trust, "UnloadAppDomain" is not supported. Touch web.config // to force an AppDomain restart. File.SetLastWriteTimeUtc(MapPath("~/web.config"), DateTime.UtcNow); return true; } catch { return false; } } protected virtual bool TryWriteGlobalAsax() { try { //When a new plugin is dropped in the Plugins folder and is installed into nopCommerce, //even if the plugin has registered routes for its controllers, //these routes will not be working as the MVC framework couldn't //find the new controller types and couldn't instantiate the requested controller. //That's why you get these nasty errors //i.e "Controller does not implement IController". //The issue is described here: http://www.nopcommerce.com/boards/t/10969/nop-20-plugin.aspx?p=4#51318 //The solution is to touch global.asax file File.SetLastWriteTimeUtc(MapPath("~/global.asax"), DateTime.UtcNow); return true; } catch { return false; } } #endregion #region Methods /// <summary> /// Ctor /// </summary> /// <param name="httpContext">HTTP context</param> public WebHelper(HttpContextBase httpContext) { this._httpContext = httpContext; } /// <summary> /// Get URL referrer /// </summary> /// <returns>URL referrer</returns> public virtual string GetUrlReferrer() { string referrerUrl = string.Empty; //URL referrer is null in some case (for example, in IE 8) if (IsRequestAvailable(_httpContext) && _httpContext.Request.UrlReferrer != null) referrerUrl = _httpContext.Request.UrlReferrer.PathAndQuery; return referrerUrl; } /// <summary> /// Get context IP address /// </summary> /// <returns>URL referrer</returns> public virtual string GetCurrentIpAddress() { if (!IsRequestAvailable(_httpContext)) return string.Empty; var result = ""; if (_httpContext.Request.Headers != null) { //The X-Forwarded-For (XFF) HTTP header field is a de facto standard //for identifying the originating IP address of a client //connecting to a web server through an HTTP proxy or load balancer. var forwardedHttpHeader = "X-FORWARDED-FOR"; if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["ForwardedHTTPheader"])) { //but in some cases server use other HTTP header //in these cases an administrator can specify a custom Forwarded HTTP header forwardedHttpHeader = ConfigurationManager.AppSettings["ForwardedHTTPheader"]; } //it's used for identifying the originating IP address of a client connecting to a web server //through an HTTP proxy or load balancer. string xff = _httpContext.Request.Headers.AllKeys .Where(x => forwardedHttpHeader.Equals(x, StringComparison.InvariantCultureIgnoreCase)) .Select(k => _httpContext.Request.Headers[k]) .FirstOrDefault(); //if you want to exclude private IP addresses, then see http://stackoverflow.com/questions/2577496/how-can-i-get-the-clients-ip-address-in-asp-net-mvc if (!String.IsNullOrEmpty(xff)) { string lastIp = xff.Split(new char[] { ',' }).FirstOrDefault(); result = lastIp; } } if (String.IsNullOrEmpty(result) && _httpContext.Request.UserHostAddress != null) { result = _httpContext.Request.UserHostAddress; } //some validation if (result == "::1") result = "127.0.0.1"; //remove port if (!String.IsNullOrEmpty(result)) { int index = result.IndexOf(":", StringComparison.InvariantCultureIgnoreCase); if (index > 0) result = result.Substring(0, index); } return result; } /// <summary> /// Gets this page name /// </summary> /// <param name="includeQueryString">Value indicating whether to include query strings</param> /// <returns>Page name</returns> public virtual string GetThisPageUrl(bool includeQueryString) { bool useSsl = IsCurrentConnectionSecured(); return GetThisPageUrl(includeQueryString, useSsl); } /// <summary> /// Gets this page name /// </summary> /// <param name="includeQueryString">Value indicating whether to include query strings</param> /// <param name="useSsl">Value indicating whether to get SSL protected page</param> /// <returns>Page name</returns> public virtual string GetThisPageUrl(bool includeQueryString, bool useSsl) { string url = string.Empty; if (!IsRequestAvailable(_httpContext)) return url; if (includeQueryString) { string storeHost = GetStoreHost(useSsl); if (storeHost.EndsWith("/")) storeHost = storeHost.Substring(0, storeHost.Length - 1); url = storeHost + _httpContext.Request.RawUrl; } else { if (_httpContext.Request.Url != null) { url = _httpContext.Request.Url.GetLeftPart(UriPartial.Path); } } url = url.ToLowerInvariant(); return url; } /// <summary> /// Gets a value indicating whether current connection is secured /// </summary> /// <returns>true - secured, false - not secured</returns> public virtual bool IsCurrentConnectionSecured() { bool useSsl = false; if (IsRequestAvailable(_httpContext)) { useSsl = _httpContext.Request.IsSecureConnection; //when your hosting uses a load balancer on their server then the Request.IsSecureConnection is never got set to true, use the statement below //just uncomment it //useSSL = _httpContext.Request.ServerVariables["HTTP_CLUSTER_HTTPS"] == "on" ? true : false; } return useSsl; } /// <summary> /// Gets server variable by name /// </summary> /// <param name="name">Name</param> /// <returns>Server variable</returns> public virtual string ServerVariables(string name) { string result = string.Empty; try { if (!IsRequestAvailable(_httpContext)) return result; //put this method is try-catch //as described here http://www.nopcommerce.com/boards/t/21356/multi-store-roadmap-lets-discuss-update-done.aspx?p=6#90196 if (_httpContext.Request.ServerVariables[name] != null) { result = _httpContext.Request.ServerVariables[name]; } } catch { result = string.Empty; } return result; } /// <summary> /// Gets store host location /// </summary> /// <param name="useSsl">Use SSL</param> /// <returns>Store host location</returns> public virtual string GetStoreHost(bool useSsl) { var result = ""; var httpHost = ServerVariables("HTTP_HOST"); if (!String.IsNullOrEmpty(httpHost)) { result = "http://" + httpHost; if (!result.EndsWith("/")) result += "/"; } if (DataSettingsHelper.DatabaseIsInstalled()) { #region Database is installed //let's resolve IWorkContext here. //Do not inject it via contructor because it'll cause circular references var storeContext = EngineContext.Current.Resolve<IStoreContext>(); var currentStore = storeContext.CurrentStore; if (currentStore == null) throw new Exception("Current store cannot be loaded"); if (String.IsNullOrWhiteSpace(httpHost)) { //HTTP_HOST variable is not available. //This scenario is possible only when HttpContext is not available (for example, running in a schedule task) //in this case use URL of a store entity configured in admin area result = currentStore.Url; if (!result.EndsWith("/")) result += "/"; } if (useSsl) { if (!String.IsNullOrWhiteSpace(currentStore.SecureUrl)) { //Secure URL specified. //So a store owner don't want it to be detected automatically. //In this case let's use the specified secure URL result = currentStore.SecureUrl; } else { //Secure URL is not specified. //So a store owner wants it to be detected automatically. result = result.Replace("http:/", "https:/"); } } else { if (currentStore.SslEnabled && !String.IsNullOrWhiteSpace(currentStore.SecureUrl)) { //SSL is enabled in this store and secure URL is specified. //So a store owner don't want it to be detected automatically. //In this case let's use the specified non-secure URL result = currentStore.Url; } } #endregion } else { #region Database is not installed if (useSsl) { //Secure URL is not specified. //So a store owner wants it to be detected automatically. result = result.Replace("http:/", "https:/"); } #endregion } if (!result.EndsWith("/")) result += "/"; return result.ToLowerInvariant(); } /// <summary> /// Gets store location /// </summary> /// <returns>Store location</returns> public virtual string GetStoreLocation() { bool useSsl = IsCurrentConnectionSecured(); return GetStoreLocation(useSsl); } /// <summary> /// Gets store location /// </summary> /// <param name="useSsl">Use SSL</param> /// <returns>Store location</returns> public virtual string GetStoreLocation(bool useSsl) { //return HostingEnvironment.ApplicationVirtualPath; string result = GetStoreHost(useSsl); if (result.EndsWith("/")) result = result.Substring(0, result.Length - 1); if (IsRequestAvailable(_httpContext)) result = result + _httpContext.Request.ApplicationPath; if (!result.EndsWith("/")) result += "/"; return result.ToLowerInvariant(); } /// <summary> /// Returns true if the requested resource is one of the typical resources that needn't be processed by the cms engine. /// </summary> /// <param name="request">HTTP Request</param> /// <returns>True if the request targets a static resource file.</returns> /// <remarks> /// These are the file extensions considered to be static resources: /// .css /// .gif /// .png /// .jpg /// .jpeg /// .js /// .axd /// .ashx /// </remarks> public virtual bool IsStaticResource(HttpRequest request) { if (request == null) throw new ArgumentNullException("request"); string path = request.Path; string extension = VirtualPathUtility.GetExtension(path); if (extension == null) return false; switch (extension.ToLower()) { case ".axd": case ".ashx": case ".bmp": case ".css": case ".gif": case ".htm": case ".html": case ".ico": case ".jpeg": case ".jpg": case ".js": case ".png": case ".rar": case ".zip": return true; } return false; } /// <summary> /// Maps a virtual path to a physical disk path. /// </summary> /// <param name="path">The path to map. E.g. "~/bin"</param> /// <returns>The physical path. E.g. "c:\inetpub\wwwroot\bin"</returns> public virtual string MapPath(string path) { if (HostingEnvironment.IsHosted) { //hosted return HostingEnvironment.MapPath(path); } else { //not hosted. For example, run in unit tests string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\'); return Path.Combine(baseDirectory, path); } } /// <summary> /// Modifies query string /// </summary> /// <param name="url">Url to modify</param> /// <param name="queryStringModification">Query string modification</param> /// <param name="anchor">Anchor</param> /// <returns>New url</returns> public virtual string ModifyQueryString(string url, string queryStringModification, string anchor) { if (url == null) url = string.Empty; url = url.ToLowerInvariant(); if (queryStringModification == null) queryStringModification = string.Empty; queryStringModification = queryStringModification.ToLowerInvariant(); if (anchor == null) anchor = string.Empty; anchor = anchor.ToLowerInvariant(); string str = string.Empty; string str2 = string.Empty; if (url.Contains("#")) { str2 = url.Substring(url.IndexOf("#") + 1); url = url.Substring(0, url.IndexOf("#")); } if (url.Contains("?")) { str = url.Substring(url.IndexOf("?") + 1); url = url.Substring(0, url.IndexOf("?")); } if (!string.IsNullOrEmpty(queryStringModification)) { if (!string.IsNullOrEmpty(str)) { var dictionary = new Dictionary<string, string>(); foreach (string str3 in str.Split(new char[] { '&' })) { if (!string.IsNullOrEmpty(str3)) { string[] strArray = str3.Split(new char[] { '=' }); if (strArray.Length == 2) { if (!dictionary.ContainsKey(strArray[0])) { //do not add value if it already exists //two the same query parameters? theoretically it's not possible. //but MVC has some ugly implementation for checkboxes and we can have two values //find more info here: http://www.mindstorminteractive.com/topics/jquery-fix-asp-net-mvc-checkbox-truefalse-value/ //we do this validation just to ensure that the first one is not overriden dictionary[strArray[0]] = strArray[1]; } } else { dictionary[str3] = null; } } } foreach (string str4 in queryStringModification.Split(new char[] { '&' })) { if (!string.IsNullOrEmpty(str4)) { string[] strArray2 = str4.Split(new char[] { '=' }); if (strArray2.Length == 2) { dictionary[strArray2[0]] = strArray2[1]; } else { dictionary[str4] = null; } } } var builder = new StringBuilder(); foreach (string str5 in dictionary.Keys) { if (builder.Length > 0) { builder.Append("&"); } builder.Append(str5); if (dictionary[str5] != null) { builder.Append("="); builder.Append(dictionary[str5]); } } str = builder.ToString(); } else { str = queryStringModification; } } if (!string.IsNullOrEmpty(anchor)) { str2 = anchor; } return (url + (string.IsNullOrEmpty(str) ? "" : ("?" + str)) + (string.IsNullOrEmpty(str2) ? "" : ("#" + str2))).ToLowerInvariant(); } /// <summary> /// Remove query string from url /// </summary> /// <param name="url">Url to modify</param> /// <param name="queryString">Query string to remove</param> /// <returns>New url</returns> public virtual string RemoveQueryString(string url, string queryString) { if (url == null) url = string.Empty; url = url.ToLowerInvariant(); if (queryString == null) queryString = string.Empty; queryString = queryString.ToLowerInvariant(); string str = string.Empty; if (url.Contains("?")) { str = url.Substring(url.IndexOf("?") + 1); url = url.Substring(0, url.IndexOf("?")); } if (!string.IsNullOrEmpty(queryString)) { if (!string.IsNullOrEmpty(str)) { var dictionary = new Dictionary<string, string>(); foreach (string str3 in str.Split(new char[] { '&' })) { if (!string.IsNullOrEmpty(str3)) { string[] strArray = str3.Split(new char[] { '=' }); if (strArray.Length == 2) { dictionary[strArray[0]] = strArray[1]; } else { dictionary[str3] = null; } } } dictionary.Remove(queryString); var builder = new StringBuilder(); foreach (string str5 in dictionary.Keys) { if (builder.Length > 0) { builder.Append("&"); } builder.Append(str5); if (dictionary[str5] != null) { builder.Append("="); builder.Append(dictionary[str5]); } } str = builder.ToString(); } } return (url + (string.IsNullOrEmpty(str) ? "" : ("?" + str))); } /// <summary> /// Gets query string value by name /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name">Parameter name</param> /// <returns>Query string value</returns> public virtual T QueryString<T>(string name) { string queryParam = null; if (IsRequestAvailable(_httpContext) && _httpContext.Request.QueryString[name] != null) queryParam = _httpContext.Request.QueryString[name]; if (!String.IsNullOrEmpty(queryParam)) return CommonHelper.To<T>(queryParam); return default(T); } /// <summary> /// Restart application domain /// </summary> /// <param name="makeRedirect">A value indicating whether we should made redirection after restart</param> /// <param name="redirectUrl">Redirect URL; empty string if you want to redirect to the current page URL</param> public virtual void RestartAppDomain(bool makeRedirect = false, string redirectUrl = "") { if (CommonHelper.GetTrustLevel() > AspNetHostingPermissionLevel.Medium) { //full trust HttpRuntime.UnloadAppDomain(); TryWriteGlobalAsax(); } else { //medium trust bool success = TryWriteWebConfig(); if (!success) { throw new NopException("nopCommerce needs to be restarted due to a configuration change, but was unable to do so." + Environment.NewLine + "To prevent this issue in the future, a change to the web server configuration is required:" + Environment.NewLine + "- run the application in a full trust environment, or" + Environment.NewLine + "- give the application write access to the 'web.config' file."); } success = TryWriteGlobalAsax(); if (!success) { throw new NopException("nopCommerce needs to be restarted due to a configuration change, but was unable to do so." + Environment.NewLine + "To prevent this issue in the future, a change to the web server configuration is required:" + Environment.NewLine + "- run the application in a full trust environment, or" + Environment.NewLine + "- give the application write access to the 'Global.asax' file."); } } // If setting up extensions/modules requires an AppDomain restart, it's very unlikely the // current request can be processed correctly. So, we redirect to the same URL, so that the // new request will come to the newly started AppDomain. if (_httpContext != null && makeRedirect) { if (String.IsNullOrEmpty(redirectUrl)) redirectUrl = GetThisPageUrl(true); _httpContext.Response.Redirect(redirectUrl, true /*endResponse*/); } } /// <summary> /// Gets a value that indicates whether the client is being redirected to a new location /// </summary> public virtual bool IsRequestBeingRedirected { get { var response = _httpContext.Response; return response.IsRequestBeingRedirected; } } /// <summary> /// Gets or sets a value that indicates whether the client is being redirected to a new location using POST /// </summary> public virtual bool IsPostBeingDone { get { if (_httpContext.Items["nop.IsPOSTBeingDone"] == null) return false; return Convert.ToBoolean(_httpContext.Items["nop.IsPOSTBeingDone"]); } set { _httpContext.Items["nop.IsPOSTBeingDone"] = value; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Runtime.InteropServices; using System.Threading; using System.Linq; using Xunit; using System.Threading.Tasks; namespace System.Diagnostics.Tests { public class ProcessThreadTests : ProcessTestBase { [Fact] public void TestCommonPriorityAndTimeProperties() { CreateDefaultProcess(); ProcessThreadCollection threadCollection = _process.Threads; Assert.True(threadCollection.Count > 0); ProcessThread thread = threadCollection[0]; try { if (ThreadState.Terminated != thread.ThreadState) { // On OSX, thread id is a 64bit unsigned value. We truncate the ulong to int // due to .NET API surface area. Hence, on overflow id can be negative while // casting the ulong to int. Assert.True(thread.Id >= 0 || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)); Assert.Equal(_process.BasePriority, thread.BasePriority); Assert.True(thread.CurrentPriority >= 0); Assert.True(thread.PrivilegedProcessorTime.TotalSeconds >= 0); Assert.True(thread.UserProcessorTime.TotalSeconds >= 0); Assert.True(thread.TotalProcessorTime.TotalSeconds >= 0); } } catch (Exception e) when (e is Win32Exception || e is InvalidOperationException) { // Win32Exception is thrown when getting threadinfo fails, or // InvalidOperationException if it fails because the thread already exited. } } [Fact] public void TestThreadCount() { int numOfThreads = 10; CountdownEvent counter = new CountdownEvent(numOfThreads); ManualResetEventSlim mre = new ManualResetEventSlim(); for (int i = 0; i < numOfThreads; i++) { new Thread(() => { counter.Signal(); mre.Wait(); }) { IsBackground = true }.Start(); } counter.Wait(); try { Assert.True(Process.GetCurrentProcess().Threads.Count >= numOfThreads); } finally { mre.Set(); } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // OSX throws PNSE from StartTime public void TestStartTimeProperty_OSX() { using (Process p = Process.GetCurrentProcess()) { ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); ProcessThread thread = threads[0]; Assert.NotNull(thread); Assert.Throws<PlatformNotSupportedException>(() => thread.StartTime); } } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // OSX throws PNSE from StartTime public async Task TestStartTimeProperty() { TimeSpan allowedWindow = TimeSpan.FromSeconds(1); using (Process p = Process.GetCurrentProcess()) { // Get the process' start time DateTime startTime = p.StartTime.ToUniversalTime(); // Get the process' threads ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); // Get the current time DateTime curTime = DateTime.UtcNow; // Make sure each thread's start time is at least the process' // start time and not beyond the current time. int passed = 0; foreach (ProcessThread t in threads.Cast<ProcessThread>()) { try { Assert.InRange(t.StartTime.ToUniversalTime(), startTime - allowedWindow, curTime + allowedWindow); passed++; } catch (InvalidOperationException) { // The thread may have gone away between our getting its info and attempting to access its StartTime } } Assert.True(passed > 0, "Expected at least one thread to be valid for StartTime"); // Now add a thread, and from that thread, while it's still alive, verify // that there's at least one thread greater than the current time we previously grabbed. await Task.Factory.StartNew(() => { p.Refresh(); try { Assert.Contains(p.Threads.Cast<ProcessThread>(), t => t.StartTime.ToUniversalTime() >= curTime - allowedWindow); } catch (InvalidOperationException) { // A thread may have gone away between our getting its info and attempting to access its StartTime } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } } [Fact] public void TestStartAddressProperty() { using (Process p = Process.GetCurrentProcess()) { ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); IntPtr startAddress = threads[0].StartAddress; // There's nothing we can really validate about StartAddress, other than that we can get its value // without throwing. All values (even zero) are valid on all platforms. } } [Fact] public void TestPriorityLevelProperty() { CreateDefaultProcess(); ProcessThread thread = _process.Threads[0]; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel); Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal); return; } ThreadPriorityLevel originalPriority = thread.PriorityLevel; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal); return; } try { thread.PriorityLevel = ThreadPriorityLevel.AboveNormal; Assert.Equal(ThreadPriorityLevel.AboveNormal, thread.PriorityLevel); } finally { thread.PriorityLevel = originalPriority; Assert.Equal(originalPriority, thread.PriorityLevel); } } [Fact] public void TestThreadStateProperty() { CreateDefaultProcess(); ProcessThread thread = _process.Threads[0]; if (ThreadState.Wait != thread.ThreadState) { Assert.Throws<InvalidOperationException>(() => thread.WaitReason); } } [Fact] public void Threads_GetMultipleTimes_ReturnsSameInstance() { CreateDefaultProcess(); Assert.Same(_process.Threads, _process.Threads); } [Fact] public void Threads_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.Threads); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using DotSpatial.Data; using DotSpatial.Symbology; using NetTopologySuite.Geometries; namespace DotSpatial.Controls { /// <summary> /// This is a specialized FeatureLayer that specifically handles line drawing. /// </summary> public class MapLineLayer : LineLayer, IMapLineLayer { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MapLineLayer"/> class that is empty with a line feature set that has no members. /// </summary> public MapLineLayer() : base(new FeatureSet(FeatureType.Line)) { Configure(); } /// <summary> /// Initializes a new instance of the <see cref="MapLineLayer"/> class. /// </summary> /// <param name="inFeatureSet">The line feature set used as data source.</param> public MapLineLayer(IFeatureSet inFeatureSet) : base(inFeatureSet) { Configure(); OnFinishedLoading(); } /// <summary> /// Initializes a new instance of the <see cref="MapLineLayer"/> class. /// </summary> /// <param name="featureSet">A featureset that contains lines.</param> /// <param name="container">An IContainer that the line layer should be created in.</param> public MapLineLayer(IFeatureSet featureSet, ICollection<ILayer> container) : base(featureSet, container, null) { Configure(); OnFinishedLoading(); } /// <summary> /// Initializes a new instance of the <see cref="MapLineLayer"/> class, but passes the boolean /// notFinished variable to indicate whether or not this layer should fire the FinishedLoading event. /// </summary> /// <param name="featureSet">The line feature set used as data source.</param> /// <param name="container">An IContainer that the line layer should be created in.</param> /// <param name="notFinished">Indicates whether the OnFinishedLoading event should be suppressed after loading finished.</param> public MapLineLayer(IFeatureSet featureSet, ICollection<ILayer> container, bool notFinished) : base(featureSet, container, null) { Configure(); if (notFinished == false) OnFinishedLoading(); } #endregion #region Events /// <summary> /// Fires an event that indicates to the parent map-frame that it should first /// redraw the specified clip /// </summary> public event EventHandler<ClipArgs> BufferChanged; #endregion #region Properties /// <summary> /// Gets or sets the back buffer that will be drawn to as part of the initialization process. /// </summary> [ShallowCopy] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Image BackBuffer { get; set; } /// <summary> /// Gets or sets the current buffer. /// </summary> [ShallowCopy] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Image Buffer { get; set; } /// <summary> /// Gets or sets the geographic region represented by the buffer /// Calling Initialize will set this automatically. /// </summary> [ShallowCopy] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Envelope BufferEnvelope { get; set; } /// <summary> /// Gets or sets the rectangle in pixels to use as the back buffer. /// Calling Initialize will set this automatically. /// </summary> [ShallowCopy] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Rectangle BufferRectangle { get; set; } /// <summary> /// Gets or sets the label layer that is associated with this line layer. /// </summary> [ShallowCopy] public new IMapLabelLayer LabelLayer { get { return base.LabelLayer as IMapLabelLayer; } set { base.LabelLayer = value; } } /// <summary> /// Gets an integer number of chunks for this layer. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int NumChunks { get { if (DrawingFilter == null) return 0; return DrawingFilter.NumChunks; } } #endregion #region Methods /// <summary> /// Call StartDrawing before using this. /// </summary> /// <param name="rectangles">The rectangular region in pixels to clear.</param> /// <param name= "color">The color to use when clearing. Specifying transparent /// will replace content with transparent pixels.</param> public void Clear(List<Rectangle> rectangles, Color color) { if (BackBuffer == null) return; Graphics g = Graphics.FromImage(BackBuffer); foreach (Rectangle r in rectangles) { if (r.IsEmpty == false) { g.Clip = new Region(r); g.Clear(color); } } g.Dispose(); } /// <summary> /// This is testing the idea of using an input parameter type that is marked as out /// instead of a return type. /// </summary> /// <param name="result">The result of the creation.</param> /// <returns>Boolean, true if a layer can be created.</returns> public override bool CreateLayerFromSelectedFeatures(out IFeatureLayer result) { bool resultOk = CreateLayerFromSelectedFeatures(out MapLineLayer temp); result = temp; return resultOk; } /// <summary> /// This is the strong typed version of the same process that is specific to geo point layers. /// </summary> /// <param name="result">The new GeoPointLayer to be created.</param> /// <returns>Boolean, true if there were any values in the selection.</returns> public virtual bool CreateLayerFromSelectedFeatures(out MapLineLayer result) { result = null; if (Selection == null || Selection.Count == 0) return false; FeatureSet fs = Selection.ToFeatureSet(); result = new MapLineLayer(fs); return true; } /// <summary> /// If EditMode is true, then this method is used for feature drawing. /// </summary> /// <param name="args">The GeoArgs that control how these features should be drawn.</param> /// <param name="features">The features that should be drawn.</param> /// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param> /// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param> /// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param> public virtual void DrawFeatures(MapArgs args, List<IFeature> features, List<Rectangle> clipRectangles, bool useChunks, bool selected) { if (!useChunks) { DrawFeatures(args, features, selected); return; } int count = features.Count; int numChunks = (int)Math.Ceiling(count / (double)ChunkSize); for (int chunk = 0; chunk < numChunks; chunk++) { int numFeatures = ChunkSize; if (chunk == numChunks - 1) numFeatures = features.Count - (chunk * ChunkSize); DrawFeatures(args, features.GetRange(chunk * ChunkSize, numFeatures), selected); if (numChunks > 0 && chunk < numChunks - 1) { OnBufferChanged(clipRectangles); Application.DoEvents(); } } } /// <summary> /// If EditMode is false, then this method is used for feature drawing. /// </summary> /// <param name="args">The GeoArgs that control how these features should be drawn.</param> /// <param name="indices">The features that should be drawn.</param> /// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param> /// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param> /// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param> public virtual void DrawFeatures(MapArgs args, List<int> indices, List<Rectangle> clipRectangles, bool useChunks, bool selected) { if (!useChunks) { DrawFeatures(args, indices, selected); return; } int count = indices.Count; int numChunks = (int)Math.Ceiling(count / (double)ChunkSize); for (int chunk = 0; chunk < numChunks; chunk++) { int numFeatures = ChunkSize; if (chunk == numChunks - 1) numFeatures = indices.Count - (chunk * ChunkSize); DrawFeatures(args, indices.GetRange(chunk * ChunkSize, numFeatures), selected); if (numChunks > 0 && chunk < numChunks - 1) { OnBufferChanged(clipRectangles); Application.DoEvents(); } } } /// <summary> /// This will draw any features that intersect this region. To specify the features /// directly, use OnDrawFeatures. This will not clear existing buffer content. /// For that call Initialize instead. /// </summary> /// <param name="args">A GeoArgs clarifying the transformation from geographic to image space.</param> /// <param name="regions">The geographic regions to draw.</param> /// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param> public virtual void DrawRegions(MapArgs args, List<Extent> regions, bool selected) { // First determine the number of features we are talking about based on region. List<Rectangle> clipRects = args.ProjToPixel(regions); if (EditMode) { List<IFeature> drawList = new List<IFeature>(); foreach (Extent region in regions) { if (region != null) { // Use union to prevent duplicates. No sense in drawing more than we have to. drawList = drawList.Union(DataSet.Select(region)).ToList(); } } DrawFeatures(args, drawList, clipRects, true, selected); } else { List<int> drawList = new List<int>(); List<ShapeRange> shapes = DataSet.ShapeIndices; for (int shp = 0; shp < shapes.Count; shp++) { foreach (Extent region in regions) { if (!shapes[shp].Extent.Intersects(region)) continue; drawList.Add(shp); break; } } DrawFeatures(args, drawList, clipRects, true, selected); } } /// <summary> /// Builds a linestring into the graphics path, using minX, maxY, dx and dy for the transformations. /// </summary> /// <param name="path">Graphics path to add the line string to.</param> /// <param name="ls">LineString that gets added.</param> /// <param name="args">The map arguments.</param> /// <param name="clipRect">The clip rectangle.</param> internal static void BuildLineString(GraphicsPath path, LineString ls, MapArgs args, Rectangle clipRect) { double minX = args.MinX; double maxY = args.MaxY; double dx = args.Dx; double dy = args.Dy; var points = new List<double[]>(); double[] previousPoint = null; foreach (Coordinate c in ls.Coordinates) { var pt = new[] { (c.X - minX) * dx, (maxY - c.Y) * dy }; if (previousPoint == null || previousPoint.Length < 2 || pt[0] != previousPoint[0] || pt[1] != previousPoint[1]) { points.Add(pt); } previousPoint = pt; } AddLineStringToPath(path, args, ls.EnvelopeInternal.ToExtent(), points, clipRect); } /// <summary> /// Adds the line string to the path. /// </summary> /// <param name="path">Path to add the line string to.</param> /// <param name="vertices">Vertices of the line string.</param> /// <param name="shpx">Shape range of the line string.</param> /// <param name="args">The map arguments.</param> /// <param name="clipRect">The clip rectangle.</param> internal static void BuildLineString(GraphicsPath path, double[] vertices, ShapeRange shpx, MapArgs args, Rectangle clipRect) { double minX = args.MinX; double maxY = args.MaxY; double dx = args.Dx; double dy = args.Dy; for (int prt = 0; prt < shpx.Parts.Count; prt++) { PartRange prtx = shpx.Parts[prt]; int start = prtx.StartIndex; int end = prtx.EndIndex; var points = new List<double[]>(end - start + 1); for (int i = start; i <= end; i++) { var pt = new[] { (vertices[i * 2] - minX) * dx, (maxY - vertices[(i * 2) + 1]) * dy }; points.Add(pt); } AddLineStringToPath(path, args, shpx.Extent, points, clipRect); } } /// <summary> /// Fires the OnBufferChanged event. /// </summary> /// <param name="clipRectangles">The Rectangle in pixels.</param> protected virtual void OnBufferChanged(List<Rectangle> clipRectangles) { if (BufferChanged != null) { ClipArgs e = new ClipArgs(clipRectangles); BufferChanged(this, e); } } /// <summary> /// A default method to generate a label layer. /// </summary> protected override void OnCreateLabels() { LabelLayer = new MapLabelLayer(this); } /// <summary> /// Indiciates that whatever drawing is going to occur has finished and the contents /// are about to be flipped forward to the front buffer. /// </summary> protected virtual void OnFinishDrawing() { } /// <summary> /// Occurs when a new drawing is started, but after the BackBuffer has been established. /// </summary> protected virtual void OnStartDrawing() { } /// <summary> /// Adds the given points to the given path. /// </summary> /// <param name="path">Path the points get added to.</param> /// <param name="args">MapArgs used for clipping.</param> /// <param name="extent">Extent of the feature used for clipping.</param> /// <param name="points">Points that get added to the path.</param> /// <param name="clipRect">The clipping rectangle.</param> private static void AddLineStringToPath(GraphicsPath path, MapArgs args, Extent extent, List<double[]> points, Rectangle clipRect) { List<List<double[]>> multiLinestrings; if (!extent.Within(args.GeographicExtents)) { multiLinestrings = CohenSutherland.ClipLinestring(points, clipRect.Left, clipRect.Top, clipRect.Right, clipRect.Bottom); } else { multiLinestrings = new List<List<double[]>> { points }; } foreach (List<double[]> linestring in multiLinestrings) { var intPoints = DuplicationPreventer.Clean(linestring).ToArray(); if (intPoints.Length < 2) { continue; } path.StartFigure(); path.AddLines(intPoints); } } private static Rectangle ComputeClippingRectangle(MapArgs args, ILineSymbolizer ls) { // Compute a clipping rectangle that accounts for symbology int maxLineWidth = 2 * (int)Math.Ceiling(ls.GetWidth()); Rectangle clipRect = args.ProjToPixel(args.GeographicExtents); // use GeographicExtent for clipping because ImageRect clips to much clipRect.Inflate(maxLineWidth, maxLineWidth); return clipRect; } /// <summary> /// Gets the indices of the features that get drawn. /// </summary> /// <param name="indices">Indices of all the features that could be drawn.</param> /// <param name="states">FastDrawnStates of the features.</param> /// <param name="category">Category the features must have to get drawn.</param> /// <param name="selected">Indicates whether only the selected features get drawn.</param> /// <returns>List of the indices of the features that get drawn.</returns> private static List<int> GetFeatures(IList<int> indices, FastDrawnState[] states, ILineCategory category, bool selected) { List<int> drawnFeatures = new List<int>(); foreach (int index in indices) { if (index >= states.Length) break; FastDrawnState state = states[index]; if (selected) { if (state.Category == category && state.Visible && state.Selected) { drawnFeatures.Add(index); } } else { if (state.Category == category && state.Visible) { drawnFeatures.Add(index); } } } return drawnFeatures; } private void Configure() { BufferRectangle = new Rectangle(0, 0, 3000, 3000); ChunkSize = 50000; } private void DrawFeatures(MapArgs e, IEnumerable<int> indices, bool selected) { if (selected && !DrawnStatesNeeded) return; Graphics g = e.Device ?? Graphics.FromImage(BackBuffer); var indiceList = indices as IList<int> ?? indices.ToList(); Action<GraphicsPath, Rectangle, IEnumerable<int>> drawFeature = (graphPath, clipRect, features) => { foreach (int shp in features) { ShapeRange shape = DataSet.ShapeIndices[shp]; BuildLineString(graphPath, DataSet.Vertex, shape, e, clipRect); } }; if (DrawnStatesNeeded) { FastDrawnState[] states = DrawnStates; if (indiceList.Max() >= states.Length) { AssignFastDrawnStates(); states = DrawnStates; } if (selected && !states.Any(_ => _.Selected)) return; foreach (ILineCategory category in Symbology.Categories) { // Define the symbology based on the category and selection state ILineSymbolizer ls = selected ? category.SelectionSymbolizer : category.Symbolizer; var features = GetFeatures(indiceList, states, category, selected); DrawPath(g, ls, e, drawFeature, features); } } else { // Selection state is disabled and there is only one category ILineSymbolizer ls = Symbology.Categories[0].Symbolizer; DrawPath(g, ls, e, drawFeature, indiceList); } if (e.Device == null) g.Dispose(); } /// <summary> /// Draws the path that results from the given indices. /// </summary> /// <typeparam name="T">Type of the elements in the list.</typeparam> /// <param name="g">Graphics object used for drawing.</param> /// <param name="ls">LineSymbolizer used for drawing.</param> /// <param name="e">MapArgs needed for computation.</param> /// <param name="action">Action that is used to add the elements to the graphics path that gets drawn.</param> /// <param name="list">List that contains the elements that get drawn.</param> private void DrawPath<T>(Graphics g, ILineSymbolizer ls, MapArgs e, Action<GraphicsPath, Rectangle, IEnumerable<T>> action, IEnumerable<T> list) { g.SmoothingMode = ls.GetSmoothingMode(); Rectangle clipRect = ComputeClippingRectangle(e, ls); // Determine the subset of the specified features that are visible and match the category using (GraphicsPath graphPath = new GraphicsPath()) { action(graphPath, clipRect, list); double scale = ls.GetScale(e); foreach (IStroke stroke in ls.Strokes) { stroke.DrawPath(g, graphPath, scale); } } } // This draws the individual line features private void DrawFeatures(MapArgs e, IEnumerable<IFeature> features, bool selected) { if (selected && !DrawingFilter.DrawnStates.Any(_ => _.Value.IsSelected)) return; Graphics g = e.Device ?? Graphics.FromImage(BackBuffer); var featureList = features as IList<IFeature> ?? features.ToList(); Action<GraphicsPath, Rectangle, IEnumerable<IFeature>> drawFeature = (graphPath, clipRect, featList) => { foreach (IFeature f in featList) { var geo = f.Geometry as LineString; if (geo != null) { BuildLineString(graphPath, geo, e, clipRect); } else { var col = f.Geometry as GeometryCollection; if (col != null) { foreach (var c1 in col.Geometries.OfType<LineString>()) { BuildLineString(graphPath, c1, e, clipRect); } } } } }; foreach (ILineCategory category in Symbology.Categories) { // Define the symbology based on the category and selection state ILineSymbolizer ls = selected ? category.SelectionSymbolizer : category.Symbolizer; // Determine the subset of the specified features that are visible and match the category ILineCategory lineCategory = category; Func<IDrawnState, bool> isMember; if (selected) { // get only selected features isMember = state => state.SchemeCategory == lineCategory && state.IsVisible && state.IsSelected; } else { // get all features isMember = state => state.SchemeCategory == lineCategory && state.IsVisible; } var drawnFeatures = from feature in featureList where isMember(DrawingFilter[feature]) select feature; DrawPath(g, ls, e, drawFeature, drawnFeatures); } if (e.Device == null) g.Dispose(); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="ListItemCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.ComponentModel; using System.Drawing.Design; /// <devdoc> /// <para>Encapsulates the items within a <see cref='System.Web.UI.WebControls.ListControl'/> . /// This class cannot be inherited.</para> /// </devdoc> [ Editor("System.Web.UI.Design.WebControls.ListItemsCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)) ] public sealed class ListItemCollection : ICollection, IList, IStateManager { private ArrayList listItems; private bool marked; private bool saveAll; /// <devdoc> /// Initializes a new instance of the /// <see cref='System.Web.UI.WebControls.ListItemCollection'/> class. /// </devdoc> public ListItemCollection() { listItems = new ArrayList(); marked = false; saveAll = false; } /// <devdoc> /// <para>Gets a <see cref='System.Web.UI.WebControls.ListItem'/> referenced by the specified ordinal /// index value.</para> /// </devdoc> public ListItem this[int index] { get { return (ListItem)listItems[index]; } } /// <internalonly/> object IList.this[int index] { get { return listItems[index]; } set { listItems[index] = (ListItem)value; } } public int Capacity { get { return listItems.Capacity; } set { listItems.Capacity = value; } } /// <devdoc> /// <para>Gets the item count of the collection.</para> /// </devdoc> public int Count { get { return listItems.Count; } } /// <devdoc> /// <para>Adds the specified item to the end of the collection.</para> /// </devdoc> public void Add(string item) { Add(new ListItem(item)); } /// <devdoc> /// <para>Adds the specified <see cref='System.Web.UI.WebControls.ListItem'/> to the end of the collection.</para> /// </devdoc> public void Add(ListItem item) { listItems.Add(item); if (marked) { item.Dirty = true; } } /// <internalonly/> int IList.Add(object item) { ListItem newItem = (ListItem) item; int returnValue = listItems.Add(newItem); if (marked) { newItem.Dirty = true; } return returnValue; } /// <devdoc> /// </devdoc> public void AddRange(ListItem[] items) { if (items == null) { throw new ArgumentNullException("items"); } foreach(ListItem item in items) { Add(item); } } /// <devdoc> /// <para>Removes all <see cref='System.Web.UI.WebControls.ListItem'/> controls from the collection.</para> /// </devdoc> public void Clear() { listItems.Clear(); if (marked) saveAll = true; } /// <devdoc> /// <para>Returns a value indicating whether the /// collection contains the specified item.</para> /// </devdoc> public bool Contains(ListItem item) { return listItems.Contains(item); } /// <internalonly/> bool IList.Contains(object item) { return Contains((ListItem) item); } /// <devdoc> /// <para>Copies contents from the collection to a specified <see cref='System.Array' qualify='true'/> with a /// specified starting index.</para> /// </devdoc> public void CopyTo(Array array, int index) { listItems.CopyTo(array,index); } public ListItem FindByText(string text) { int index = FindByTextInternal(text, true); if (index != -1) { return (ListItem)listItems[index]; } return null; } internal int FindByTextInternal(string text, bool includeDisabled) { int i = 0; foreach (ListItem item in listItems) { if (item.Text.Equals(text) && (includeDisabled || item.Enabled)) { return i; } i++; } return -1; } public ListItem FindByValue(string value) { int index = FindByValueInternal(value, true); if (index != -1) { return (ListItem)listItems[index]; } return null; } internal int FindByValueInternal(string value, bool includeDisabled) { int i = 0; foreach (ListItem item in listItems) { if (item.Value.Equals(value) && (includeDisabled || item.Enabled)) { return i; } i++; } return -1; } /// <devdoc> /// <para>Returns an enumerator of all <see cref='System.Web.UI.WebControls.ListItem'/> controls within the /// collection.</para> /// </devdoc> public IEnumerator GetEnumerator() { return listItems.GetEnumerator(); } /// <devdoc> /// <para>Returns an ordinal index value that represents the /// position of the specified <see cref='System.Web.UI.WebControls.ListItem'/> within the collection.</para> /// </devdoc> public int IndexOf(ListItem item) { return listItems.IndexOf(item); } /// <internalonly/> int IList.IndexOf(object item) { return IndexOf((ListItem) item); } /// <devdoc> /// <para>Adds the specified item to the collection at the specified index /// location.</para> /// </devdoc> public void Insert(int index,string item) { Insert(index,new ListItem(item)); } /// <devdoc> /// <para>Inserts the specified <see cref='System.Web.UI.WebControls.ListItem'/> to the collection at the specified /// index location.</para> /// </devdoc> public void Insert(int index,ListItem item) { listItems.Insert(index,item); if (marked) saveAll = true; } /// <internalonly/> void IList.Insert(int index, object item) { Insert(index, (ListItem) item); } /// <internalonly/> bool IList.IsFixedSize { get { return false; } } /// <devdoc> /// <para>Gets a value indicating whether the collection is read-only.</para> /// </devdoc> public bool IsReadOnly { get { return listItems.IsReadOnly; } } /// <devdoc> /// <para>Gets a value indicating whether access to the collection is synchronized /// (thread-safe).</para> /// </devdoc> public bool IsSynchronized { get { return listItems.IsSynchronized; } } /// <devdoc> /// <para>Removes the <see cref='System.Web.UI.WebControls.ListItem'/> from the collection at the specified /// index location.</para> /// </devdoc> public void RemoveAt(int index) { listItems.RemoveAt(index); if (marked) saveAll = true; } /// <devdoc> /// <para>Removes the specified item from the collection.</para> /// </devdoc> public void Remove(string item) { int index = IndexOf(new ListItem(item)); if (index >= 0) { RemoveAt(index); } } /// <devdoc> /// <para>Removes the specified <see cref='System.Web.UI.WebControls.ListItem'/> from the collection.</para> /// </devdoc> public void Remove(ListItem item) { int index = IndexOf(item); if (index >= 0) { RemoveAt(index); } } /// <internalonly/> void IList.Remove(object item) { Remove((ListItem) item); } /// <devdoc> /// <para>Gets the object that can be used to synchronize access to the collection. In /// this case, it is the collection itself.</para> /// </devdoc> public object SyncRoot { get { return this; } } /// <internalonly/> /// <devdoc> /// Return true if tracking state changes. /// Method of private interface, IStateManager. /// </devdoc> bool IStateManager.IsTrackingViewState { get { return marked; } } /// <internalonly/> void IStateManager.LoadViewState(object state) { LoadViewState(state); } internal void LoadViewState(object state) { if (state != null) { if (state is Pair) { // only changed items were saved Pair p = (Pair) state; ArrayList indices = (ArrayList) p.First; ArrayList items = (ArrayList) p.Second; for (int i=0; i<indices.Count; i++) { int index = (int) indices[i]; if (index < Count) this[index].LoadViewState(items[i]); else { ListItem li = new ListItem(); li.LoadViewState(items[i]); Add(li); } } } else { // all items were saved Triplet t = (Triplet) state; listItems = new ArrayList(); saveAll = true; string[] texts = (string[]) t.First; string[] values = (string[]) t.Second; bool[] enabled = (bool[]) t.Third; for (int i=0; i < texts.Length; i++) { Add(new ListItem(texts[i], values[i], enabled[i])); } } } } /// <internalonly/> void IStateManager.TrackViewState() { TrackViewState(); } internal void TrackViewState() { marked = true; for (int i=0; i < Count; i++) this[i].TrackViewState(); } /// <internalonly/> object IStateManager.SaveViewState() { return SaveViewState(); } internal object SaveViewState() { if (saveAll == true) { // save all items int count = Count; object[] texts = new string[count]; object[] values = new string[count]; bool[] enableds = new bool[count]; for (int i=0; i < count; i++) { texts[i] = this[i].Text; values[i] = this[i].Value; enableds[i] = this[i].Enabled; } return new Triplet(texts, values, enableds); } else { // save only the changed items ArrayList indices = new ArrayList(4); ArrayList items = new ArrayList(4); for (int i=0; i < Count; i++) { object item = this[i].SaveViewState(); if (item != null) { indices.Add(i); items.Add(item); } } if (indices.Count > 0) return new Pair(indices, items); return null; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using NHibernate; using NHibernate.Transform; using Orchard.ContentManagement.Records; using Orchard.Data.Providers; using Orchard.Environment.Configuration; using Orchard.Utility.Extensions; namespace Orchard.ContentManagement { public class DefaultHqlQuery : IHqlQuery { private readonly ISession _session; private readonly IEnumerable<ISqlStatementProvider> _sqlStatementProviders; private readonly ShellSettings _shellSettings; private VersionOptions _versionOptions; private string[] _includedPartRecords = new string[0]; private bool _cacheable; protected IJoin _from; protected readonly List<Tuple<IAlias, Join>> _joins = new List<Tuple<IAlias, Join>>(); protected readonly List<Tuple<IAlias, Action<IHqlExpressionFactory>>> _wheres = new List<Tuple<IAlias, Action<IHqlExpressionFactory>>>(); protected readonly List<Tuple<IAlias, Action<IHqlSortFactory>>> _sortings = new List<Tuple<IAlias, Action<IHqlSortFactory>>>(); public IContentManager ContentManager { get; private set; } public DefaultHqlQuery( IContentManager contentManager, ISession session, IEnumerable<ISqlStatementProvider> sqlStatementProviders, ShellSettings shellSettings) { _session = session; _sqlStatementProviders = sqlStatementProviders; _shellSettings = shellSettings; ContentManager = contentManager; } internal string PathToAlias(string path) { if (String.IsNullOrWhiteSpace(path)) { throw new ArgumentException("Path can't be empty"); } return Char.ToLower(path[0], CultureInfo.InvariantCulture) + path.Substring(1); } internal Join BindNamedAlias(string alias) { var tuple = _joins.FirstOrDefault(x => x.Item2.Name == alias); return tuple == null ? null : tuple.Item2; } internal IAlias BindCriteriaByPath(IAlias alias, string path, string type = null, Action<IHqlExpressionFactory> withPredicate = null) { return BindCriteriaByAlias(alias, path, PathToAlias(path), type, withPredicate); } internal IAlias BindCriteriaByAlias(IAlias alias, string path, string aliasName, string type = null, Action<IHqlExpressionFactory> withPredicate = null) { // is this Join already existing (based on aliasName) Join join = BindNamedAlias(aliasName); if (join == null) { join = new Join(path, aliasName, type, withPredicate); _joins.Add(new Tuple<IAlias, Join>(alias, join)); } return join; } internal IAlias BindTypeCriteria() { // ([ContentItemVersionRecord] >join> [ContentItemRecord]) >join> [ContentType] return BindCriteriaByAlias(BindItemCriteria(), "ContentType", "ct"); } internal IAlias BindItemCriteria(string type = "") { // [ContentItemVersionRecord] >join> [ContentItemRecord] return BindCriteriaByAlias(BindItemVersionCriteria(type), typeof(ContentItemRecord).Name, "ci"); } internal IAlias BindItemVersionCriteria(string type = "") { _from = _from ?? new Join(typeof(ContentItemVersionRecord).FullName, "civ", type); if (_from.Type.Length < type.Length) { _from.Type = type; } return _from; } internal IAlias BindPartCriteria<TRecord>(string type = null, Action<IHqlExpressionFactory> withPredicate = null) where TRecord : ContentPartRecord { return BindPartCriteria(typeof(TRecord), type, withPredicate); } internal IAlias BindPartCriteria(Type contentPartRecordType, string type = null, Action<IHqlExpressionFactory> withPredicate = null) { if (!contentPartRecordType.IsSubclassOf(typeof(ContentPartRecord))) { throw new ArgumentException("The type must inherit from ContentPartRecord", "contentPartRecordType"); } if (contentPartRecordType.IsSubclassOf(typeof(ContentPartVersionRecord))) { return BindCriteriaByPath(BindItemVersionCriteria(), contentPartRecordType.Name, type, withPredicate); } return BindCriteriaByPath(BindItemCriteria(), contentPartRecordType.Name, type, withPredicate); } internal void Where(IAlias alias, Action<IHqlExpressionFactory> predicate) { _wheres.Add(new Tuple<IAlias, Action<IHqlExpressionFactory>>(alias, predicate)); } internal IAlias ApplyHqlVersionOptionsRestrictions(VersionOptions versionOptions) { var alias = BindItemVersionCriteria(); if (versionOptions == null) { Where(alias, x => x.Eq("Published", true)); } else if (versionOptions.IsPublished) { Where(alias, x => x.Eq("Published", true)); } else if (versionOptions.IsLatest) { Where(alias, x => x.Eq("Latest", true)); } else if (versionOptions.IsDraft) { Where(alias, x => x.And(y => y.Eq("Latest", true), y => y.Eq("Published", false))); } else if (versionOptions.IsAllVersions) { // no-op... all versions will be returned by default } else { throw new ApplicationException("Invalid VersionOptions for content query"); } return alias; } public IHqlQuery Join(Action<IAliasFactory> alias) { var aliasFactory = new DefaultAliasFactory(this); alias(aliasFactory); return this; } public IHqlQuery Where(Action<IAliasFactory> alias, Action<IHqlExpressionFactory> predicate) { var aliasFactory = new DefaultAliasFactory(this); alias(aliasFactory); Where(aliasFactory.Current, predicate); return this; } public IHqlQuery OrderBy(Action<IAliasFactory> alias, Action<IHqlSortFactory> order) { var aliasFactory = new DefaultAliasFactory(this); alias(aliasFactory); _sortings.Add(new Tuple<IAlias, Action<IHqlSortFactory>>(aliasFactory.Current, order)); return this; } public IHqlQuery ForType(params string[] contentTypeNames) { if (contentTypeNames != null && contentTypeNames.Length != 0) { Where(BindTypeCriteria(), x => x.InG("Name", contentTypeNames)); } return this; } public IHqlQuery Include(params string[] contentPartRecords) { _includedPartRecords = _includedPartRecords.Union(contentPartRecords).ToArray(); return this; } public IHqlQuery ForVersion(VersionOptions options) { _versionOptions = options; return this; } public IHqlQuery<T> ForPart<T>() where T : IContent { return new DefaultHqlQuery<T>(this); } public IEnumerable<ContentItem> List() { return Slice(0, 0); } public IEnumerable<ContentItem> Slice(int skip, int count) { ApplyHqlVersionOptionsRestrictions(_versionOptions); _cacheable = true; var hql = ToHql(false); var query = _session .CreateQuery(hql) .SetCacheable(_cacheable) ; if (skip != 0) { query.SetFirstResult(skip); } if (count != 0 && count != Int32.MaxValue) { query.SetMaxResults(count); } var ids = query .SetResultTransformer(Transformers.AliasToEntityMap) .List<IDictionary>() .Select(x => (int)x["Id"]); return ContentManager.GetManyByVersionId(ids, new QueryHints().ExpandRecords(_includedPartRecords)); } public int Count() { ApplyHqlVersionOptionsRestrictions(_versionOptions); var hql = ToHql(true); hql = "select count(Id) from Orchard.ContentManagement.Records.ContentItemVersionRecord where Id in ( " + hql + " )"; return Convert.ToInt32(_session.CreateQuery(hql) .SetCacheable(true) .UniqueResult()) ; } public string ToHql(bool count) { var sb = new StringBuilder(); if (count) { sb.Append("select distinct civ.Id as Id").AppendLine(); } else { sb.Append("select distinct civ.Id as Id"); // add sort properties in the select foreach (var sort in _sortings) { var sortFactory = new DefaultHqlSortFactory(); sort.Item2(sortFactory); if (!sortFactory.Randomize) { sb.Append(", "); sb.Append(sort.Item1.Name).Append(".").Append(sortFactory.PropertyName); } else { // select distinct can't be used with newid() _cacheable = false; sb.Replace("select distinct", "select "); } } sb.AppendLine(); } sb.Append("from ").Append(_from.TableName).Append(" as ").Append(_from.Name).AppendLine(); foreach (var join in _joins) { sb.Append(join.Item2.Type + " " + join.Item1.Name + "." + join.Item2.TableName + " as " + join.Item2.Name); if (join.Item2.WithPredicate != null) { var predicate = join.Item2.WithPredicate; var expressionFactory = new DefaultHqlExpressionFactory(); predicate(expressionFactory); sb.Append(" with " + expressionFactory.Criterion.ToHql(join.Item2)); } sb.AppendLine(); } // generating where clause if (_wheres.Any()) { sb.Append("where "); var expressions = new List<string>(); foreach (var where in _wheres) { var expressionFactory = new DefaultHqlExpressionFactory(); where.Item2(expressionFactory); expressions.Add(expressionFactory.Criterion.ToHql(where.Item1)); } sb.Append("(").Append(String.Join(") AND (", expressions.ToArray())).Append(")").AppendLine(); } // generating order by clause bool firstSort = true; foreach (var sort in _sortings) { if (!firstSort) { sb.Append(", "); } else { sb.Append("order by "); firstSort = false; } var sortFactory = new DefaultHqlSortFactory(); sort.Item2(sortFactory); if (sortFactory.Randomize) { string command = null; foreach (var sqlStatementProvider in _sqlStatementProviders) { if (!String.Equals(sqlStatementProvider.DataProvider, _shellSettings.DataProvider)) { continue; } command = sqlStatementProvider.GetStatement("random") ?? command; } if (command != null) { sb.Append(command); } } else { sb.Append(sort.Item1.Name).Append(".").Append(sortFactory.PropertyName); if (!sortFactory.Ascending) { sb.Append(" desc"); } } } // no order clause was specified, use a default sort order, unless it's a count // query hence it doesn't need one if (firstSort && !count) { sb.Append("order by civ.Id"); } return sb.ToString(); } } public class DefaultHqlQuery<TPart> : IHqlQuery<TPart> where TPart : IContent { private readonly DefaultHqlQuery _query; public DefaultHqlQuery(DefaultHqlQuery query) { _query = query; } public IContentManager ContentManager { get { return _query.ContentManager; } } public IHqlQuery<TPart> ForType(params string[] contentTypes) { _query.ForType(contentTypes); return new DefaultHqlQuery<TPart>(_query); } public IHqlQuery<TPart> ForVersion(VersionOptions options) { _query.ForVersion(options); return new DefaultHqlQuery<TPart>(_query); } IEnumerable<TPart> IHqlQuery<TPart>.List() { return _query.List().AsPart<TPart>(); } IEnumerable<TPart> IHqlQuery<TPart>.Slice(int skip, int count) { return _query.Slice(skip, count).AsPart<TPart>(); } int IHqlQuery<TPart>.Count() { return _query.Count(); } public IHqlQuery<TPart> Join(Action<IAliasFactory> alias) { _query.Join(alias); return new DefaultHqlQuery<TPart>(_query); } public IHqlQuery<TPart> Where(Action<IAliasFactory> alias, Action<IHqlExpressionFactory> predicate) { _query.Where(alias, predicate); return new DefaultHqlQuery<TPart>(_query); } public IHqlQuery<TPart> OrderBy(Action<IAliasFactory> alias, Action<IHqlSortFactory> order) { _query.OrderBy(alias, order); return new DefaultHqlQuery<TPart>(_query); } } public class Alias : IAlias { public Alias(string name) { if (String.IsNullOrEmpty(name)) { throw new ArgumentException("Alias can't be empty"); } Name = name.Strip('-'); } public DefaultHqlQuery<IContent> Query { get; set; } public string Name { get; set; } } public interface IJoin : IAlias { string TableName { get; set; } string Type { get; set; } Action<IHqlExpressionFactory> WithPredicate { get; set; } } public class Sort { public Sort(IAlias alias, string propertyName, bool ascending) { Alias = alias; PropertyName = propertyName; Ascending = ascending; } public IAlias Alias { get; set; } public string PropertyName { get; set; } public bool Ascending { get; set; } } public class Join : Alias, IJoin { public Join(string tableName, string alias) : this(tableName, alias, "join", null) {} public Join(string tableName, string alias, string type) : this(tableName, alias, type, null) { } public Join(string tableName, string alias, string type, Action<IHqlExpressionFactory> withPredicate) : base(alias) { if (String.IsNullOrEmpty(tableName)) { throw new ArgumentException("Table Name can't be empty"); } TableName = tableName; Type = type ?? "join"; WithPredicate = withPredicate; } public string TableName { get; set; } public string Type { get; set; } public Action<IHqlExpressionFactory> WithPredicate { get; set; } } public class DefaultHqlSortFactory : IHqlSortFactory { public bool Ascending { get; set; } public string PropertyName { get; set; } public bool Randomize { get; set; } public void Asc(string propertyName) { PropertyName = propertyName; Ascending = true; } public void Desc(string propertyName) { PropertyName = propertyName; Ascending = false; } public void Random() { Randomize = true; } } public class DefaultAliasFactory : IAliasFactory{ private readonly DefaultHqlQuery _query; public IAlias Current { get; private set; } public DefaultAliasFactory(DefaultHqlQuery query) { _query = query; Current = _query.BindItemCriteria(); } public IAliasFactory ContentPartRecord<TRecord>(string type = null, Action<IHqlExpressionFactory> withPredicate = null) where TRecord : ContentPartRecord { Current = _query.BindPartCriteria<TRecord>(type, withPredicate); return this; } public IAliasFactory ContentPartRecord(Type contentPartRecord, string type = null, Action<IHqlExpressionFactory> withPredicate = null) { if(!contentPartRecord.IsSubclassOf(typeof(ContentPartRecord))) { throw new ArgumentException("Type must inherit from ContentPartRecord", "contentPartRecord"); } Current = _query.BindPartCriteria(contentPartRecord, type, withPredicate); return this; } public IAliasFactory Property(string propertyName, string alias) { Current = _query.BindCriteriaByAlias(Current, propertyName, alias); return this; } public IAliasFactory Named(string alias) { Current = _query.BindNamedAlias(alias); return this; } public IAliasFactory ContentItem() { return Named("ci"); } public IAliasFactory ContentItemVersion() { Current = _query.BindItemVersionCriteria(); return this; } public IAliasFactory ContentType() { return Named("ct"); } } public class DefaultHqlExpressionFactory : IHqlExpressionFactory { public IHqlCriterion Criterion { get; private set; } public void Eq(string propertyName, object value) { Criterion = HqlRestrictions.Eq(propertyName, value); } public void Like(string propertyName, string value, HqlMatchMode matchMode) { Criterion = HqlRestrictions.Like(propertyName, value, matchMode); } public void InsensitiveLike(string propertyName, string value, HqlMatchMode matchMode) { Criterion = HqlRestrictions.InsensitiveLike(propertyName, value, matchMode); } public void Gt(string propertyName, object value) { Criterion = HqlRestrictions.Gt(propertyName, value); } public void Lt(string propertyName, object value) { Criterion = HqlRestrictions.Lt(propertyName, value); } public void Le(string propertyName, object value) { Criterion = HqlRestrictions.Le(propertyName, value); } public void Ge(string propertyName, object value) { Criterion = HqlRestrictions.Ge(propertyName, value); } public void Between(string propertyName, object lo, object hi) { Criterion = HqlRestrictions.Between(propertyName, lo, hi); } public void In(string propertyName, object[] values) { Criterion = HqlRestrictions.In(propertyName, values); } public void In(string propertyName, ICollection values) { Criterion = HqlRestrictions.In(propertyName, values); } public void InG<T>(string propertyName, ICollection<T> values) { Criterion = HqlRestrictions.InG(propertyName, values); } public void IsNull(string propertyName) { Criterion = HqlRestrictions.IsNull(propertyName); } public void EqProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.EqProperty(propertyName, otherPropertyName); } public void NotEqProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.NotEqProperty(propertyName, otherPropertyName); } public void GtProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.GtProperty(propertyName, otherPropertyName); } public void GeProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.GeProperty(propertyName, otherPropertyName); } public void LtProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.LtProperty(propertyName, otherPropertyName); } public void LeProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.LeProperty(propertyName, otherPropertyName); } public void IsNotNull(string propertyName) { Criterion = HqlRestrictions.IsNotNull(propertyName); } public void IsNotEmpty(string propertyName) { Criterion = HqlRestrictions.IsNotEmpty(propertyName); } public void IsEmpty(string propertyName) { Criterion = HqlRestrictions.IsEmpty(propertyName); } public void And(Action<IHqlExpressionFactory> lhs, Action<IHqlExpressionFactory> rhs) { lhs(this); var a = Criterion; rhs(this); var b = Criterion; Criterion = HqlRestrictions.And(a, b); } public void Or(Action<IHqlExpressionFactory> lhs, Action<IHqlExpressionFactory> rhs) { lhs(this); var a = Criterion; rhs(this); var b = Criterion; Criterion = HqlRestrictions.Or(a, b); } public void Not(Action<IHqlExpressionFactory> expression) { expression(this); var a = Criterion; Criterion = HqlRestrictions.Not(a); } public void Conjunction(Action<IHqlExpressionFactory> expression, params Action<IHqlExpressionFactory>[] otherExpressions) { var junction = HqlRestrictions.Conjunction(); foreach (var exp in Enumerable.Empty<Action<IHqlExpressionFactory>>().Union(new[] { expression }).Union(otherExpressions)) { exp(this); junction.Add(Criterion); } Criterion = junction; } public void Disjunction(Action<IHqlExpressionFactory> expression, params Action<IHqlExpressionFactory>[] otherExpressions) { var junction = HqlRestrictions.Disjunction(); foreach (var exp in Enumerable.Empty<Action<IHqlExpressionFactory>>().Union(new[] { expression }).Union(otherExpressions)) { exp(this); junction.Add(Criterion); } Criterion = junction; } public void AllEq(IDictionary propertyNameValues) { Criterion = HqlRestrictions.AllEq(propertyNameValues); } public void NaturalId() { Criterion = HqlRestrictions.NaturalId(); } } public enum HqlMatchMode { Exact, Start, End, Anywhere } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; namespace System.Xml { internal static class XmlConvertEx { private static XmlCharType xmlCharType = XmlCharType.Instance; private static readonly char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' }; #region XPath public static double ToXPathDouble(object o) { string str = o as string; if (str != null) { str = TrimString(str); if (str.Length != 0 && str[0] != '+') { double d; if (Double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out d)) { return d; } } return Double.NaN; } if (o is double) { return (double)o; } if (o is bool) { return ((bool)o) ? 1.0 : 0.0; } try { return Convert.ToDouble(o, NumberFormatInfo.InvariantInfo); } catch (FormatException) { } catch (OverflowException) { } catch (ArgumentNullException) { } return Double.NaN; } // Rounding to closest integer. // If there are few such integers then we choose the one closest to positive infinity public static double XPathRound(double value) { double temp = Math.Round(value); return (value - temp == 0.5) ? temp + 1 : temp; } #endregion public static string TrimString(string value) { return value.Trim(WhitespaceChars); } public static string[] SplitString(string value) { return value.Split(WhitespaceChars, StringSplitOptions.RemoveEmptyEntries); } public static Uri ToUri(string s) { if (!string.IsNullOrEmpty(s)) { //string.Empty is a valid uri but not " " s = TrimString(s); if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } } Uri uri; if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri)) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } return uri; } public static string EscapeValueForDebuggerDisplay(string value) { System.Text.StringBuilder sb = null; int i = 0; int start = 0; while (i < value.Length) { char ch = value[i]; if ((int)ch < 0x20 || ch == '"') { if (sb == null) { sb = new System.Text.StringBuilder(value.Length + 4); } if (i - start > 0) { sb.Append(value, start, i - start); } start = i + 1; switch (ch) { case '"': sb.Append("\\\""); break; case '\r': sb.Append("\\r"); break; case '\n': sb.Append("\\n"); break; case '\t': sb.Append("\\t"); break; default: sb.Append(ch); break; } } i++; } if (sb == null) { return value; } if (i - start > 0) { sb.Append(value, start, i - start); } return sb.ToString(); } public static Exception CreateInvalidSurrogatePairException(char low, char hi) { return CreateInvalidSurrogatePairException(low, hi, ExceptionType.ArgumentException); } private static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType) { return CreateInvalidSurrogatePairException(low, hi, exceptionType, 0, 0); } private static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType, int lineNo, int linePos) { string[] args = new string[] { ((uint)hi).ToString( "X", CultureInfo.InvariantCulture ), ((uint)low).ToString( "X", CultureInfo.InvariantCulture ) }; return CreateException(SR.Xml_InvalidSurrogatePairWithArgs, args, exceptionType, lineNo, linePos); } private static Exception CreateException(string res, string[] args, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(SR.Format(res, args)); case ExceptionType.XmlException: default: return new System.Xml.XmlException(SR.Format(res, args), null, lineNo, linePos); } } private static Exception CreateException(string res, string arg, ExceptionType exceptionType, int lineNo, int linePos) { return CreateException(res, new string[] { arg }, exceptionType, lineNo, linePos); } private static Exception CreateException(string res, ExceptionType exceptionType, int lineNo, int linePos) { return CreateException(res, new string[] { }, exceptionType, lineNo, linePos); } public static Exception CreateInvalidCharException(string data, int invCharPos, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlExceptionHelper.BuildCharExceptionArgs(data, invCharPos), exceptionType, 0, invCharPos + 1); } public static Exception CreateInvalidHighSurrogateCharException(char hi) { return CreateInvalidHighSurrogateCharException(hi, ExceptionType.ArgumentException); } private static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType) { return CreateInvalidHighSurrogateCharException(hi, exceptionType, 0, 0); } private static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType, int lineNo, int linePos) { return CreateException(SR.Xml_InvalidSurrogateHighChar, ((uint)hi).ToString("X", CultureInfo.InvariantCulture), exceptionType, lineNo, linePos); } public static void VerifyCharData(string data, ExceptionType exceptionType) { VerifyCharData(data, exceptionType, exceptionType); } public static unsafe void VerifyCharData(string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType) { if (string.IsNullOrEmpty(data)) { return; } int i = 0; int len = data.Length; for (; ;) { while (i < len && (xmlCharType.charProperties[data[i]] & XmlCharType.fCharData) != 0) { i++; } if (i == len) { return; } char ch = data[i]; if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 == len) { throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, invSurrogateExceptionType, 0, i + 1); } ch = data[i + 1]; if (XmlCharType.IsLowSurrogate(ch)) { i += 2; continue; } else { throw CreateInvalidSurrogatePairException(data[i + 1], data[i], invSurrogateExceptionType, 0, i + 1); } } throw CreateInvalidCharException(data, i, invCharExceptionType); } } public static string VerifyQName(string name, ExceptionType exceptionType) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } int colonPosition = -1; int endPos = ValidateNames.ParseQName(name, 0, out colonPosition); if (endPos != name.Length) { throw CreateException(SR.Xml_BadNameChar, XmlExceptionHelper.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } return name; } // Trim beginning of a string using XML whitespace characters public static string TrimStringStart(string value) { return value.TrimStart(WhitespaceChars); } // Trim end of a string using XML whitespace characters public static string TrimStringEnd(string value) { return value.TrimEnd(WhitespaceChars); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace RunTests { internal sealed class TestRunner { private struct TestResult { internal readonly bool Succeeded; internal readonly string AssemblyName; internal readonly TimeSpan Elapsed; internal readonly string ErrorOutput; internal TestResult(bool succeeded, string assemblyName, TimeSpan elapsed, string errorOutput) { Succeeded = succeeded; AssemblyName = assemblyName; Elapsed = elapsed; ErrorOutput = errorOutput; } } private readonly string _xunitConsolePath; private readonly bool _useHtml; internal TestRunner(string xunitConsolePath, bool useHtml) { _xunitConsolePath = xunitConsolePath; _useHtml = useHtml; } internal async Task<bool> RunAllAsync(IEnumerable<string> assemblyList, CancellationToken cancellationToken) { var max = (int)Environment.ProcessorCount * 1.5; var allPassed = true; var waiting = new Stack<string>(assemblyList); var running = new List<Task<TestResult>>(); var completed = new List<TestResult>(); do { cancellationToken.ThrowIfCancellationRequested(); var i = 0; while (i < running.Count) { var task = running[i]; if (task.IsCompleted) { try { var testResult = await task.ConfigureAwait(false); if (!testResult.Succeeded) { allPassed = false; } completed.Add(testResult); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); allPassed = false; } running.RemoveAt(i); } else { i++; } } while (running.Count < max && waiting.Count > 0) { var task = RunTest(waiting.Pop(), cancellationToken); running.Add(task); } Console.WriteLine(" {0} running, {1} queued, {2} completed", running.Count, waiting.Count, completed.Count); Task.WaitAny(running.ToArray()); } while (running.Count > 0); Print(completed); return allPassed; } private void Print(List<TestResult> testResults) { testResults.Sort((x, y) => x.Elapsed.CompareTo(y.Elapsed)); foreach (var testResult in testResults.Where(x => !x.Succeeded)) { Console.WriteLine("Errors {0}: ", testResult.AssemblyName); Console.WriteLine(testResult.ErrorOutput); } Console.WriteLine("================"); foreach (var testResult in testResults) { var color = testResult.Succeeded ? Console.ForegroundColor : ConsoleColor.Red; ConsoleUtil.WriteLine(color, "{0,-75} {1} {2}", testResult.AssemblyName, testResult.Succeeded ? "PASSED" : "FAILED", testResult.Elapsed); } Console.WriteLine("================"); } private async Task<TestResult> RunTest(string assemblyPath, CancellationToken cancellationToken) { try { var assemblyName = Path.GetFileName(assemblyPath); var resultsDir = Path.Combine(Path.GetDirectoryName(assemblyPath), "xUnitResults"); var resultsFile = Path.Combine(resultsDir, $"{assemblyName}.{(_useHtml ? "html" : "xml")}"); var outputLogPath = Path.Combine(resultsDir, $"{assemblyName}.out.log"); // NOTE: xUnit doesn't always create the log directory Directory.CreateDirectory(resultsDir); // NOTE: xUnit seems to have an occasional issue creating logs create // an empty log just in case, so our runner will still fail. File.Create(resultsFile).Close(); var builder = new StringBuilder(); builder.AppendFormat(@"""{0}""", assemblyPath); builder.AppendFormat(@" -{0} ""{1}""", _useHtml ? "html" : "xml", resultsFile); builder.Append(" -noshadow -verbose"); var errorOutput = new StringBuilder(); var start = DateTime.UtcNow; var xunitPath = _xunitConsolePath; var processOutput = await ProcessRunner.RunProcessAsync( xunitPath, builder.ToString(), lowPriority: false, displayWindow: false, captureOutput: true, cancellationToken: cancellationToken).ConfigureAwait(false); var span = DateTime.UtcNow - start; if (processOutput.ExitCode != 0) { File.WriteAllLines(outputLogPath, processOutput.OutputLines); // On occasion we get a non-0 output but no actual data in the result file. The could happen // if xunit manages to crash when running a unit test (a stack overflow could cause this, for instance). // To avoid losing information, write the process output to the console. In addition, delete the results // file to avoid issues with any tool attempting to interpret the (potentially malformed) text. var resultData = string.Empty; try { resultData = File.ReadAllText(resultsFile).Trim(); } catch { // Happens if xunit didn't produce a log file } if (resultData.Length == 0) { // Delete the output file. File.Delete(resultsFile); } errorOutput.AppendLine($"Command: {_xunitConsolePath} {builder}"); errorOutput.AppendLine($"xUnit output: {outputLogPath}"); if (processOutput.ErrorLines.Any()) { foreach (var line in processOutput.ErrorLines) { errorOutput.AppendLine(line); } } else { errorOutput.AppendLine($"xunit produced no error output but had exit code {processOutput.ExitCode}"); } // If the results are html, use Process.Start to open in the browser. if (_useHtml && resultData.Length > 0) { Process.Start(resultsFile); } } return new TestResult(processOutput.ExitCode == 0, assemblyName, span, errorOutput.ToString()); } catch (Exception ex) { throw new Exception($"Unable to run {assemblyPath} with {_xunitConsolePath}", ex); } } private static void DeleteFile(string filePath) { try { if (File.Exists(filePath)) { File.Delete(filePath); } } catch { // Ignore } } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComUtils.MasterSetup.DS { public class MST_DeliveryTermDS { public MST_DeliveryTermDS() { } private const string THIS = "PCSComUtils.MasterSetup.DS.MST_DeliveryTermDS"; //************************************************************************** /// <Description> /// This method uses to add data to MST_DeliveryTerm /// </Description> /// <Inputs> /// MST_DeliveryTermVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { MST_DeliveryTermVO objObject = (MST_DeliveryTermVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO MST_DeliveryTerm(" + MST_DeliveryTermTable.CODE_FLD + "," + MST_DeliveryTermTable.DESCRIPTION_FLD + ")" + "VALUES(?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(MST_DeliveryTermTable.CODE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_DeliveryTermTable.CODE_FLD].Value = objObject.Code; ocmdPCS.Parameters.Add(new OleDbParameter(MST_DeliveryTermTable.DESCRIPTION_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_DeliveryTermTable.DESCRIPTION_FLD].Value = objObject.Description; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from MST_DeliveryTerm /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + MST_DeliveryTermTable.TABLE_NAME + " WHERE " + "DeliveryTermID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from MST_DeliveryTerm /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// MST_DeliveryTermVO /// </Outputs> /// <Returns> /// MST_DeliveryTermVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + MST_DeliveryTermTable.DELIVERYTERMID_FLD + "," + MST_DeliveryTermTable.CODE_FLD + "," + MST_DeliveryTermTable.DESCRIPTION_FLD + " FROM " + MST_DeliveryTermTable.TABLE_NAME +" WHERE " + MST_DeliveryTermTable.DELIVERYTERMID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); MST_DeliveryTermVO objObject = new MST_DeliveryTermVO(); while (odrPCS.Read()) { objObject.DeliveryTermID = int.Parse(odrPCS[MST_DeliveryTermTable.DELIVERYTERMID_FLD].ToString().Trim()); objObject.Code = odrPCS[MST_DeliveryTermTable.CODE_FLD].ToString().Trim(); objObject.Description = odrPCS[MST_DeliveryTermTable.DESCRIPTION_FLD].ToString().Trim(); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to MST_DeliveryTerm /// </Description> /// <Inputs> /// MST_DeliveryTermVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; MST_DeliveryTermVO objObject = (MST_DeliveryTermVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE MST_DeliveryTerm SET " + MST_DeliveryTermTable.CODE_FLD + "= ?" + "," + MST_DeliveryTermTable.DESCRIPTION_FLD + "= ?" +" WHERE " + MST_DeliveryTermTable.DELIVERYTERMID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(MST_DeliveryTermTable.CODE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_DeliveryTermTable.CODE_FLD].Value = objObject.Code; ocmdPCS.Parameters.Add(new OleDbParameter(MST_DeliveryTermTable.DESCRIPTION_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_DeliveryTermTable.DESCRIPTION_FLD].Value = objObject.Description; ocmdPCS.Parameters.Add(new OleDbParameter(MST_DeliveryTermTable.DELIVERYTERMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_DeliveryTermTable.DELIVERYTERMID_FLD].Value = objObject.DeliveryTermID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from MST_DeliveryTerm /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + MST_DeliveryTermTable.DELIVERYTERMID_FLD + "," + MST_DeliveryTermTable.CODE_FLD + "," + MST_DeliveryTermTable.DESCRIPTION_FLD + " FROM " + MST_DeliveryTermTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,MST_DeliveryTermTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + MST_DeliveryTermTable.DELIVERYTERMID_FLD + "," + MST_DeliveryTermTable.CODE_FLD + "," + MST_DeliveryTermTable.DESCRIPTION_FLD + " FROM " + MST_DeliveryTermTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,MST_DeliveryTermTable.TABLE_NAME); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
// // AsyncTests.Framework.TestSuite // // Authors: // Martin Baulig (martin.baulig@gmail.com) // // Copyright 2012 Xamarin Inc. (http://www.xamarin.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Linq; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Configuration; using System.Collections.Generic; using Mono.Addins; [assembly:AddinRoot ("AsyncTests", "0.1")] namespace AsyncTests.Framework { public class TestSuite { Assembly assembly; List<TestFixture> fixtures; static readonly ITestFramework[] frameworks; static readonly ITestHost[] hosts; static readonly ITestCategory[] categories; static readonly ITestCategoryFilter[] filters; static readonly Configuration config; static TestSuite () { AddinManager.Initialize (); AddinManager.Registry.Update (); frameworks = AddinManager.GetExtensionObjects<ITestFramework> () ?? new ITestFramework[0]; hosts = AddinManager.GetExtensionObjects<ITestHost> () ?? new ITestHost[0]; categories = AddinManager.GetExtensionObjects<ITestCategory> () ?? new ITestCategory[0]; filters = categories.Where (category => category is ITestCategoryFilter). Select (x => (ITestCategoryFilter)x).ToArray (); config = ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.PerUserRoamingAndLocal); } TestSuite (Assembly assembly) { this.assembly = assembly; } public Assembly Assembly { get { return assembly; } } public static Configuration Configuration { get { return config; } } public string Name { get { return assembly.GetName ().Name; } } public static ITestCategory[] Categories { get { return categories; } } internal static ITestCategoryFilter[] CategoryFilters { get { return filters; } } public IList<TestFixture> Fixtures { get { return fixtures.AsReadOnly (); } } public int CountFixtures { get { return fixtures.Count; } } public int CountTests { get { return fixtures.Sum (fixture => fixture.CountTests); } } internal static bool Filter (TestCase test, ITestRunner runner, ITestCategory category) { if (!test.IsEnabled || !category.IsEnabled (test) || !runner.IsEnabled (test)) return false; if (test.Categories.Where (c => !c.Equals (category)).Any (c => c.Explicit)) return false; return filters.Where (f => !f.Equals (category)).All (f => f.Filter (test)); } public static T GetConfiguration<T> () where T : TestConfiguration { return (T)GetConfiguration (typeof (T)); } internal static TestConfiguration GetConfiguration (Type type) { var name = type.FullName; var section = (TestConfiguration)config.GetSection (name); config.Save (ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection (name); if (section == null) { section = (TestConfiguration)Activator.CreateInstance (type); config.Sections.Add (name, section); config.Save (ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection (name); } return section; } public static Task<TestSuite> Create (Assembly assembly) { var tcs = new TaskCompletionSource<TestSuite> (); ThreadPool.QueueUserWorkItem (_ => { try { var suite = new TestSuite (assembly); suite.DoResolve (); tcs.SetResult (suite); } catch (Exception ex) { tcs.SetException (ex); } } ); return tcs.Task; } void DoResolve () { fixtures = new List<TestFixture> (); foreach (var framework in frameworks) { if (!IsEqualOrSubclassOf<AsyncTestFixtureAttribute> (framework.FixtureAttributeType)) { Log ("Framework '{0}' has invalid FixtureAttributeType '{1}'", framework.GetType ().FullName, framework.FixtureAttributeType.FullName); continue; } if (!IsEqualOrSubclassOf<AsyncTestAttribute> (framework.TestAttributeType)) { Log ("Framework '{0}' has invalid FixtureAttributeType '{1}'", framework.GetType ().FullName, framework.TestAttributeType.FullName); continue; } if (!IsEqualOrSubclassOf<TestContext> (framework.ContextType)) { Log ("Framework '{0}' has invalid ContextType '{1}'", framework.GetType ().FullName, framework.ContextType.FullName); continue; } foreach (var type in assembly.GetExportedTypes ()) { var attr = (AsyncTestFixtureAttribute)type.GetCustomAttribute ( framework.FixtureAttributeType, false); if ((attr == null) || attr.GetType ().IsSubclassOf (framework.FixtureAttributeType)) continue; fixtures.Add (new TestFixture (this, framework, attr, type)); } } foreach (var fixture in fixtures) { fixture.Resolve (); } } bool IsEqualOrSubclassOf<T> (Type type) { return type.Equals (typeof (T)) || type.IsSubclassOf (typeof (T)); } internal int CurrentIteration { get; private set; } internal int MaxIterations { get; private set; } public static ITestCategory AllTests = new AllTestsCategory (); public Task<TestResultCollection> Run (CancellationToken cancellationToken) { return Run (AllTests, 1, cancellationToken); } public async Task<TestResultCollection> Run (ITestCategory category, int repeatCount, CancellationToken cancellationToken) { var result = new TestResultCollection (Name); try { for (int i = 0; i < hosts.Length; i++) await hosts [i].SetUp (this); } catch (Exception ex) { Log ("SetUp failed: {0}", ex); result.AddChild (new TestError (Name, "SetUp failed", ex)); return result; } if (repeatCount == 1) { CurrentIteration = MaxIterations = 1; await DoRun (category, result, cancellationToken); } else { MaxIterations = repeatCount; for (CurrentIteration = 0; CurrentIteration < repeatCount; CurrentIteration++) { var name = string.Format ("{0} (iteration {1})", Name, CurrentIteration + 1); var iteration = new TestResultCollection (name); result.AddChild (iteration); await DoRun (category, iteration, cancellationToken); } } try { for (int i = 0; i < hosts.Length; i++) await hosts [i].TearDown (this); } catch (Exception ex) { Log ("TearDown failed: {0}", ex); result.AddChild (new TestError (Name, "TearDown failed", ex)); } OnStatusMessageEvent ("Test suite finished."); return result; } async Task DoRun (ITestCategory category, TestResultCollection result, CancellationToken cancellationToken) { foreach (var fixture in fixtures) { if (!fixture.IsEnabled (category)) continue; try { result.AddChild (await fixture.Run (category, cancellationToken)); } catch (Exception ex) { Log ("Test fixture {0} failed: {1}", fixture.Name, ex); result.AddChild (new TestError (fixture.Name, "Test fixture failed", ex)); } } } protected internal void Log (string message, params object[] args) { Debug.WriteLine (string.Format (message, args), "TestSuite"); } public event EventHandler<StatusMessageEventArgs> StatusMessageEvent; protected internal void OnStatusMessageEvent (string message, params object[] args) { OnStatusMessageEvent (new StatusMessageEventArgs (string.Format (message, args))); } protected void OnStatusMessageEvent (StatusMessageEventArgs args) { if (StatusMessageEvent != null) StatusMessageEvent (this, args); } public class StatusMessageEventArgs : EventArgs { public string Message { get; private set; } public Exception Error { get; private set; } public StatusMessageEventArgs (string message) { this.Message = message; } public StatusMessageEventArgs (string message, Exception error) { this.Message = message; this.Error = error; } } } }
using Lucene.Net.Documents; using System; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * 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 BinaryDocValuesField = BinaryDocValuesField; using BinaryDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.BinaryDocValuesUpdate; using BytesRef = Lucene.Net.Util.BytesRef; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using InPlaceMergeSorter = Lucene.Net.Util.InPlaceMergeSorter; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; using PagedGrowableWriter = Lucene.Net.Util.Packed.PagedGrowableWriter; using PagedMutable = Lucene.Net.Util.Packed.PagedMutable; /// <summary> /// A <see cref="DocValuesFieldUpdates"/> which holds updates of documents, of a single /// <see cref="BinaryDocValuesField"/>. /// <para/> /// @lucene.experimental /// </summary> internal class BinaryDocValuesFieldUpdates : DocValuesFieldUpdates { new internal sealed class Iterator : DocValuesFieldUpdates.Iterator { private readonly PagedGrowableWriter offsets; private readonly int size; private readonly PagedGrowableWriter lengths; private readonly PagedMutable docs; private readonly FixedBitSet docsWithField; private long idx = 0; // long so we don't overflow if size == Integer.MAX_VALUE private int doc = -1; private readonly BytesRef value; private int offset, length; internal Iterator(int size, PagedGrowableWriter offsets, PagedGrowableWriter lengths, PagedMutable docs, BytesRef values, FixedBitSet docsWithField) { this.offsets = offsets; this.size = size; this.lengths = lengths; this.docs = docs; this.docsWithField = docsWithField; value = (BytesRef)values.Clone(); } public override object Value { get { if (offset == -1) { return null; } else { value.Offset = offset; value.Length = length; return value; } } } public override int NextDoc() { if (idx >= size) { offset = -1; return doc = DocIdSetIterator.NO_MORE_DOCS; } doc = (int)docs.Get(idx); ++idx; while (idx < size && docs.Get(idx) == doc) { ++idx; } // idx points to the "next" element long prevIdx = idx - 1; if (!docsWithField.Get((int)prevIdx)) { offset = -1; } else { // cannot change 'value' here because nextDoc is called before the // value is used, and it's a waste to clone the BytesRef when we // obtain the value offset = (int)offsets.Get(prevIdx); length = (int)lengths.Get(prevIdx); } return doc; } public override int Doc { get { return doc; } } public override void Reset() { doc = -1; offset = -1; idx = 0; } } private FixedBitSet docsWithField; private PagedMutable docs; private PagedGrowableWriter offsets, lengths; private BytesRef values; private int size; public BinaryDocValuesFieldUpdates(string field, int maxDoc) : base(field, DocValuesFieldUpdatesType.BINARY) { docsWithField = new FixedBitSet(64); docs = new PagedMutable(1, 1024, PackedInt32s.BitsRequired(maxDoc - 1), PackedInt32s.COMPACT); offsets = new PagedGrowableWriter(1, 1024, 1, PackedInt32s.FAST); lengths = new PagedGrowableWriter(1, 1024, 1, PackedInt32s.FAST); values = new BytesRef(16); // start small size = 0; } public override void Add(int doc, object value) { // TODO: if the Sorter interface changes to take long indexes, we can remove that limitation if (size == int.MaxValue) { throw new InvalidOperationException("cannot support more than System.Int32.MaxValue doc/value entries"); } BytesRef val = (BytesRef)value; if (val == null) { val = BinaryDocValuesUpdate.MISSING; } // grow the structures to have room for more elements if (docs.Count == size) { docs = docs.Grow(size + 1); offsets = offsets.Grow(size + 1); lengths = lengths.Grow(size + 1); docsWithField = FixedBitSet.EnsureCapacity(docsWithField, (int)docs.Count); } if (val != BinaryDocValuesUpdate.MISSING) { // only mark the document as having a value in that field if the value wasn't set to null (MISSING) docsWithField.Set(size); } docs.Set(size, doc); offsets.Set(size, values.Length); lengths.Set(size, val.Length); values.Append(val); ++size; } public override DocValuesFieldUpdates.Iterator GetIterator() { PagedMutable docs = this.docs; PagedGrowableWriter offsets = this.offsets; PagedGrowableWriter lengths = this.lengths; BytesRef values = this.values; FixedBitSet docsWithField = this.docsWithField; new InPlaceMergeSorterAnonymousInnerClassHelper(this, docs, offsets, lengths, docsWithField).Sort(0, size); return new Iterator(size, offsets, lengths, docs, values, docsWithField); } private class InPlaceMergeSorterAnonymousInnerClassHelper : InPlaceMergeSorter { private readonly BinaryDocValuesFieldUpdates outerInstance; private PagedMutable docs; private PagedGrowableWriter offsets; private PagedGrowableWriter lengths; private FixedBitSet docsWithField; public InPlaceMergeSorterAnonymousInnerClassHelper(BinaryDocValuesFieldUpdates outerInstance, PagedMutable docs, PagedGrowableWriter offsets, PagedGrowableWriter lengths, FixedBitSet docsWithField) { this.outerInstance = outerInstance; this.docs = docs; this.offsets = offsets; this.lengths = lengths; this.docsWithField = docsWithField; } protected override void Swap(int i, int j) { long tmpDoc = docs.Get(j); docs.Set(j, docs.Get(i)); docs.Set(i, tmpDoc); long tmpOffset = offsets.Get(j); offsets.Set(j, offsets.Get(i)); offsets.Set(i, tmpOffset); long tmpLength = lengths.Get(j); lengths.Set(j, lengths.Get(i)); lengths.Set(i, tmpLength); bool tmpBool = docsWithField.Get(j); if (docsWithField.Get(i)) { docsWithField.Set(j); } else { docsWithField.Clear(j); } if (tmpBool) { docsWithField.Set(i); } else { docsWithField.Clear(i); } } protected override int Compare(int i, int j) { int x = (int)docs.Get(i); int y = (int)docs.Get(j); return (x < y) ? -1 : ((x == y) ? 0 : 1); } } [MethodImpl(MethodImplOptions.NoInlining)] public override void Merge(DocValuesFieldUpdates other) { BinaryDocValuesFieldUpdates otherUpdates = (BinaryDocValuesFieldUpdates)other; int newSize = size + otherUpdates.size; if (newSize > int.MaxValue) { throw new InvalidOperationException("cannot support more than System.Int32.MaxValue doc/value entries; size=" + size + " other.size=" + otherUpdates.size); } docs = docs.Grow(newSize); offsets = offsets.Grow(newSize); lengths = lengths.Grow(newSize); docsWithField = FixedBitSet.EnsureCapacity(docsWithField, (int)docs.Count); for (int i = 0; i < otherUpdates.size; i++) { int doc = (int)otherUpdates.docs.Get(i); if (otherUpdates.docsWithField.Get(i)) { docsWithField.Set(size); } docs.Set(size, doc); offsets.Set(size, values.Length + otherUpdates.offsets.Get(i)); // correct relative offset lengths.Set(size, otherUpdates.lengths.Get(i)); ++size; } values.Append(otherUpdates.values); } public override bool Any() { return size > 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System { // DateTimeOffset is a value type that consists of a DateTime and a time zone offset, // ie. how far away the time is from GMT. The DateTime is stored whole, and the offset // is stored as an Int16 internally to save space, but presented as a TimeSpan. // // The range is constrained so that both the represented clock time and the represented // UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime // for actual UTC times, and a slightly constrained range on one end when an offset is // present. // // This class should be substitutable for date time in most cases; so most operations // effectively work on the clock time. However, the underlying UTC time is what counts // for the purposes of identity, sorting and subtracting two instances. // // // There are theoretically two date times stored, the UTC and the relative local representation // or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable // for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this // out and for internal readability. [StructLayout(LayoutKind.Auto)] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct DateTimeOffset : IComparable, IFormattable, IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>, ISerializable, IDeserializationCallback { // Constants internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14; internal const Int64 MinOffset = -MaxOffset; private const long UnixEpochTicks = TimeSpan.TicksPerDay * DateTime.DaysTo1970; // 621,355,968,000,000,000 private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800 private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 internal const long UnixMinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; internal const long UnixMaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; // Static Fields public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero); public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero); // Instance Fields private DateTime _dateTime; private Int16 _offsetMinutes; // Constructors // Constructs a DateTimeOffset from a tick count and offset public DateTimeOffset(long ticks, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); // Let the DateTime constructor do the range checks DateTime dateTime = new DateTime(ticks); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds, // extracts the local offset. For UTC, creates a UTC instance with a zero offset. public DateTimeOffset(DateTime dateTime) { TimeSpan offset; if (dateTime.Kind != DateTimeKind.Utc) { // Local and Unspecified are both treated as Local offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else { offset = new TimeSpan(0); } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time // consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that // the offset corresponds to the local. public DateTimeOffset(DateTime dateTime, TimeSpan offset) { if (dateTime.Kind == DateTimeKind.Local) { if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) { throw new ArgumentException(SR.Argument_OffsetLocalMismatch, nameof(offset)); } } else if (dateTime.Kind == DateTimeKind.Utc) { if (offset != TimeSpan.Zero) { throw new ArgumentException(SR.Argument_OffsetUtcMismatch, nameof(offset)); } } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond and offset public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond, Calendar and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset); } // Returns a DateTimeOffset representing the current date and time. The // resolution of the returned value depends on the system timer. For // Windows NT 3.5 and later the timer resolution is approximately 10ms, // for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98 // it is approximately 55ms. // public static DateTimeOffset Now { get { return new DateTimeOffset(DateTime.Now); } } public static DateTimeOffset UtcNow { get { return new DateTimeOffset(DateTime.UtcNow); } } public DateTime DateTime { get { return ClockDateTime; } } public DateTime UtcDateTime { get { return DateTime.SpecifyKind(_dateTime, DateTimeKind.Utc); } } public DateTime LocalDateTime { get { return UtcDateTime.ToLocalTime(); } } // Adjust to a given offset with the same UTC time. Can throw ArgumentException // public DateTimeOffset ToOffset(TimeSpan offset) { return new DateTimeOffset((_dateTime + offset).Ticks, offset); } // Instance Properties // The clock or visible time represented. This is just a wrapper around the internal date because this is // the chosen storage mechanism. Going through this helper is good for readability and maintainability. // This should be used for display but not identity. private DateTime ClockDateTime { get { return new DateTime((_dateTime + Offset).Ticks, DateTimeKind.Unspecified); } } // Returns the date part of this DateTimeOffset. The resulting value // corresponds to this DateTimeOffset with the time-of-day part set to // zero (midnight). // public DateTime Date { get { return ClockDateTime.Date; } } // Returns the day-of-month part of this DateTimeOffset. The returned // value is an integer between 1 and 31. // public int Day { get { return ClockDateTime.Day; } } // Returns the day-of-week part of this DateTimeOffset. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek DayOfWeek { get { return ClockDateTime.DayOfWeek; } } // Returns the day-of-year part of this DateTimeOffset. The returned value // is an integer between 1 and 366. // public int DayOfYear { get { return ClockDateTime.DayOfYear; } } // Returns the hour part of this DateTimeOffset. The returned value is an // integer between 0 and 23. // public int Hour { get { return ClockDateTime.Hour; } } // Returns the millisecond part of this DateTimeOffset. The returned value // is an integer between 0 and 999. // public int Millisecond { get { return ClockDateTime.Millisecond; } } // Returns the minute part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Minute { get { return ClockDateTime.Minute; } } // Returns the month part of this DateTimeOffset. The returned value is an // integer between 1 and 12. // public int Month { get { return ClockDateTime.Month; } } public TimeSpan Offset { get { return new TimeSpan(0, _offsetMinutes, 0); } } // Returns the second part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Second { get { return ClockDateTime.Second; } } // Returns the tick count for this DateTimeOffset. The returned value is // the number of 100-nanosecond intervals that have elapsed since 1/1/0001 // 12:00am. // public long Ticks { get { return ClockDateTime.Ticks; } } public long UtcTicks { get { return UtcDateTime.Ticks; } } // Returns the time-of-day part of this DateTimeOffset. The returned value // is a TimeSpan that indicates the time elapsed since midnight. // public TimeSpan TimeOfDay { get { return ClockDateTime.TimeOfDay; } } // Returns the year part of this DateTimeOffset. The returned value is an // integer between 1 and 9999. // public int Year { get { return ClockDateTime.Year; } } // Returns the DateTimeOffset resulting from adding the given // TimeSpan to this DateTimeOffset. // public DateTimeOffset Add(TimeSpan timeSpan) { return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // days to this DateTimeOffset. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddDays(double days) { return new DateTimeOffset(ClockDateTime.AddDays(days), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // hours to this DateTimeOffset. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddHours(double hours) { return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset); } // Returns the DateTimeOffset resulting from the given number of // milliseconds to this DateTimeOffset. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to this DateTimeOffset. The value // argument is permitted to be negative. // public DateTimeOffset AddMilliseconds(double milliseconds) { return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // minutes to this DateTimeOffset. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddMinutes(double minutes) { return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset); } public DateTimeOffset AddMonths(int months) { return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // seconds to this DateTimeOffset. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddSeconds(double seconds) { return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // 100-nanosecond ticks to this DateTimeOffset. The value argument // is permitted to be negative. // public DateTimeOffset AddTicks(long ticks) { return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // years to this DateTimeOffset. The result is computed by incrementing // (or decrementing) the year part of this DateTimeOffset by value // years. If the month and day of this DateTimeOffset is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of this DateTimeOffset. // public DateTimeOffset AddYears(int years) { return new DateTimeOffset(ClockDateTime.AddYears(years), Offset); } // Compares two DateTimeOffset values, returning an integer that indicates // their relationship. // public static int Compare(DateTimeOffset first, DateTimeOffset second) { return DateTime.Compare(first.UtcDateTime, second.UtcDateTime); } // Compares this DateTimeOffset to a given object. This method provides an // implementation of the IComparable interface. The object // argument must be another DateTimeOffset, or otherwise an exception // occurs. Null is considered less than any instance. // int IComparable.CompareTo(Object obj) { if (obj == null) return 1; if (!(obj is DateTimeOffset)) { throw new ArgumentException(SR.Arg_MustBeDateTimeOffset); } DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime; DateTime utc = UtcDateTime; if (utc > objUtc) return 1; if (utc < objUtc) return -1; return 0; } public int CompareTo(DateTimeOffset other) { DateTime otherUtc = other.UtcDateTime; DateTime utc = UtcDateTime; if (utc > otherUtc) return 1; if (utc < otherUtc) return -1; return 0; } // Checks if this DateTimeOffset is equal to a given object. Returns // true if the given object is a boxed DateTimeOffset and its value // is equal to the value of this DateTimeOffset. Returns false // otherwise. // public override bool Equals(Object obj) { if (obj is DateTimeOffset) { return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime); } return false; } public bool Equals(DateTimeOffset other) { return UtcDateTime.Equals(other.UtcDateTime); } public bool EqualsExact(DateTimeOffset other) { // // returns true when the ClockDateTime, Kind, and Offset match // // currently the Kind should always be Unspecified, but there is always the possibility that a future version // of DateTimeOffset overloads the Kind field // return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind); } // Compares two DateTimeOffset values for equality. Returns true if // the two DateTimeOffset values are equal, or false if they are // not equal. // public static bool Equals(DateTimeOffset first, DateTimeOffset second) { return DateTime.Equals(first.UtcDateTime, second.UtcDateTime); } // Creates a DateTimeOffset from a Windows filetime. A Windows filetime is // a long representing the date and time as the number of // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am. // public static DateTimeOffset FromFileTime(long fileTime) { return new DateTimeOffset(DateTime.FromFileTime(fileTime)); } public static DateTimeOffset FromUnixTimeSeconds(long seconds) { if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds) { throw new ArgumentOutOfRangeException(nameof(seconds), SR.Format(SR.ArgumentOutOfRange_Range, UnixMinSeconds, UnixMaxSeconds)); } long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) { const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) { throw new ArgumentOutOfRangeException(nameof(milliseconds), SR.Format(SR.ArgumentOutOfRange_Range, MinMilliseconds, MaxMilliseconds)); } long ticks = milliseconds * TimeSpan.TicksPerMillisecond + UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } // ----- SECTION: private serialization instance methods ----------------* void IDeserializationCallback.OnDeserialization(Object sender) { try { _offsetMinutes = ValidateOffset(Offset); _dateTime = ValidateDate(ClockDateTime, Offset); } catch (ArgumentException e) { throw new SerializationException(SR.Serialization_InvalidData, e); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } info.AddValue("DateTime", _dateTime); // Do not rename (binary serialization) info.AddValue("OffsetMinutes", _offsetMinutes); // Do not rename (binary serialization) } private DateTimeOffset(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } _dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime)); // Do not rename (binary serialization) _offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16)); // Do not rename (binary serialization) } // Returns the hash code for this DateTimeOffset. // public override int GetHashCode() { return UtcDateTime.GetHashCode(); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(String input) { TimeSpan offset; DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) { return Parse(input, formatProvider, DateTimeStyles.None); } public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) { return ParseExact(input, format, formatProvider, DateTimeStyles.None); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult = DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult = DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public TimeSpan Subtract(DateTimeOffset value) { return UtcDateTime.Subtract(value.UtcDateTime); } public DateTimeOffset Subtract(TimeSpan value) { return new DateTimeOffset(ClockDateTime.Subtract(value), Offset); } public long ToFileTime() { return UtcDateTime.ToFileTime(); } public long ToUnixTimeSeconds() { // Truncate sub-second precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times. // // For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0 // ticks = 621355967990010000 // ticksFromEpoch = ticks - UnixEpochTicks = -9990000 // secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0 // // Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division, // whereas we actually always want to round *down* when converting to Unix time. This happens // automatically for positive Unix time values. Now the example becomes: // seconds = ticks / TimeSpan.TicksPerSecond = 62135596799 // secondsFromEpoch = seconds - UnixEpochSeconds = -1 // // In other words, we want to consistently round toward the time 1/1/0001 00:00:00, // rather than toward the Unix Epoch (1/1/1970 00:00:00). long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond; return seconds - UnixEpochSeconds; } public long ToUnixTimeMilliseconds() { // Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond; return milliseconds - UnixEpochMilliseconds; } public DateTimeOffset ToLocalTime() { return ToLocalTime(false); } internal DateTimeOffset ToLocalTime(bool throwOnOverflow) { return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow)); } public override String ToString() { return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset); } public String ToString(String format) { return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset); } public String ToString(IFormatProvider formatProvider) { return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), Offset); } public String ToString(String format, IFormatProvider formatProvider) { return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset); } public DateTimeOffset ToUniversalTime() { return new DateTimeOffset(UtcDateTime); } public static Boolean TryParse(String input, out DateTimeOffset result) { TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } // Ensures the TimeSpan is valid to go in a DateTimeOffset. private static Int16 ValidateOffset(TimeSpan offset) { Int64 ticks = offset.Ticks; if (ticks % TimeSpan.TicksPerMinute != 0) { throw new ArgumentException(SR.Argument_OffsetPrecision, nameof(offset)); } if (ticks < MinOffset || ticks > MaxOffset) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_OffsetOutOfRange); } return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute); } // Ensures that the time and offset are in range. private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) { // The key validation is that both the UTC and clock times fit. The clock time is validated // by the DateTime constructor. Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated."); // This operation cannot overflow because offset should have already been validated to be within // 14 hours and the DateTime instance is more than that distance from the boundaries of Int64. Int64 utcTicks = dateTime.Ticks - offset.Ticks; if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_UTCOutOfRange); } // make sure the Kind is set to Unspecified // return new DateTime(utcTicks, DateTimeKind.Unspecified); } private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) { if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidDateTimeStyles, parameterName); } if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) { throw new ArgumentException(SR.Argument_ConflictingDateTimeStyles, parameterName); } if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) { throw new ArgumentException(SR.Argument_DateTimeOffsetInvalidDateTimeStyles, parameterName); } // RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatibility with DateTime style &= ~DateTimeStyles.RoundtripKind; // AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse style &= ~DateTimeStyles.AssumeLocal; return style; } // Operators public static implicit operator DateTimeOffset(DateTime dateTime) { return new DateTimeOffset(dateTime); } public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset); } public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset); } public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime - right.UtcDateTime; } public static bool operator ==(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime == right.UtcDateTime; } public static bool operator !=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime != right.UtcDateTime; } public static bool operator <(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime < right.UtcDateTime; } public static bool operator <=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime <= right.UtcDateTime; } public static bool operator >(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime > right.UtcDateTime; } public static bool operator >=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime >= right.UtcDateTime; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.PythonTools.Debugger; using Microsoft.PythonTools.DkmDebugger.Proxies; using Microsoft.PythonTools.DkmDebugger.Proxies.Structs; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Breakpoints; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.CustomRuntimes; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Native; namespace Microsoft.PythonTools.DkmDebugger { // This class implements functionality that is logically a part of TraceManager, but has to be implemented on LocalComponent // and LocalStackWalkingComponent side due to DKM API location restrictions. internal class TraceManagerLocalHelper : DkmDataItem { // There's one of each - StepIn is owned by LocalComponent, StepOut is owned by LocalStackWalkingComponent. // See the comment on the latter for explanation on why this is necessary. public enum Kind { StepIn, StepOut } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] public struct PyObject_FieldOffsets { public readonly long ob_type; public PyObject_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyObject, PyObject.PyObject_Fields>(process); ob_type = fields.ob_type.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] public struct PyVarObject_FieldOffsets { public readonly long ob_size; public PyVarObject_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyVarObject, PyVarObject.PyVarObject_Fields>(process); ob_size = fields.ob_size.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct PyCodeObject_FieldOffsets { public readonly long co_varnames, co_filename, co_name; public PyCodeObject_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyCodeObject, PyCodeObject.Fields>(process); co_varnames = fields.co_varnames.Offset; co_filename = fields.co_filename.Offset; co_name = fields.co_name.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct PyFrameObject_FieldOffsets { public readonly long f_back, f_code, f_globals, f_locals, f_lineno; public PyFrameObject_FieldOffsets(DkmProcess process) { if (process.GetPythonRuntimeInfo().LanguageVersion <= PythonLanguageVersion.V35) { var fields = StructProxy.GetStructFields<PyFrameObject, PyFrameObject.Fields_27_35>(process); f_back = -1; f_code = fields.f_code.Offset; f_globals = fields.f_globals.Offset; f_locals = fields.f_locals.Offset; f_lineno = fields.f_lineno.Offset; } else { var fields = StructProxy.GetStructFields<PyFrameObject, PyFrameObject.Fields_36>(process); f_back = fields.f_back.Offset; f_code = fields.f_code.Offset; f_globals = fields.f_globals.Offset; f_locals = fields.f_locals.Offset; f_lineno = fields.f_lineno.Offset; } } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct PyBytesObject_FieldOffsets { public readonly long ob_sval; public PyBytesObject_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyBytesObject, PyBytesObject.Fields>(process); ob_sval = fields.ob_sval.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct PyUnicodeObject27_FieldOffsets { public readonly long length, str; public PyUnicodeObject27_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyUnicodeObject27, PyUnicodeObject27.Fields>(process); length = fields.length.Offset; str = fields.str.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct PyUnicodeObject33_FieldOffsets { public readonly long sizeof_PyASCIIObject, sizeof_PyCompactUnicodeObject; public readonly long length, state, wstr, wstr_length, data; public PyUnicodeObject33_FieldOffsets(DkmProcess process) { sizeof_PyASCIIObject = StructProxy.SizeOf<PyASCIIObject>(process); sizeof_PyCompactUnicodeObject = StructProxy.SizeOf<PyUnicodeObject33>(process); var asciiFields = StructProxy.GetStructFields<PyASCIIObject, PyASCIIObject.Fields>(process); length = asciiFields.length.Offset; state = asciiFields.state.Offset; wstr = asciiFields.wstr.Offset; var compactFields = StructProxy.GetStructFields<PyCompactUnicodeObject, PyCompactUnicodeObject.Fields>(process); wstr_length = compactFields.wstr_length.Offset; var unicodeFields = StructProxy.GetStructFields<PyUnicodeObject33, PyUnicodeObject33.Fields>(process); data = unicodeFields.data.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct FieldOffsets { public PyObject_FieldOffsets PyObject; public PyVarObject_FieldOffsets PyVarObject; public PyFrameObject_FieldOffsets PyFrameObject; public PyCodeObject_FieldOffsets PyCodeObject; public PyBytesObject_FieldOffsets PyBytesObject; public PyUnicodeObject27_FieldOffsets PyUnicodeObject27; public PyUnicodeObject33_FieldOffsets PyUnicodeObject33; public FieldOffsets(DkmProcess process, PythonRuntimeInfo pyrtInfo) { PyObject = new PyObject_FieldOffsets(process); PyVarObject = new PyVarObject_FieldOffsets(process); PyFrameObject = new PyFrameObject_FieldOffsets(process); PyCodeObject = new PyCodeObject_FieldOffsets(process); PyBytesObject = new PyBytesObject_FieldOffsets(process); if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { PyUnicodeObject27 = new PyUnicodeObject27_FieldOffsets(process); PyUnicodeObject33 = new PyUnicodeObject33_FieldOffsets(); } else { PyUnicodeObject27 = new PyUnicodeObject27_FieldOffsets(); PyUnicodeObject33 = new PyUnicodeObject33_FieldOffsets(process); } } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct Types { public ulong PyBytes_Type; public ulong PyUnicode_Type; public Types(DkmProcess process, PythonRuntimeInfo pyrtInfo) { PyBytes_Type = PyObject.GetPyType<PyBytesObject>(process).Address; if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { PyUnicode_Type = PyObject.GetPyType<PyUnicodeObject27>(process).Address; } else { PyUnicode_Type = PyObject.GetPyType<PyUnicodeObject33>(process).Address; } } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct FunctionPointers { public ulong Py_DecRef; public ulong PyFrame_FastToLocals; public ulong PyRun_StringFlags; public ulong PyErr_Fetch; public ulong PyErr_Restore; public ulong PyErr_Occurred; public ulong PyObject_Str; public FunctionPointers(DkmProcess process, PythonRuntimeInfo pyrtInfo) { Py_DecRef = pyrtInfo.DLLs.Python.GetFunctionAddress("Py_DecRef"); PyFrame_FastToLocals = pyrtInfo.DLLs.Python.GetFunctionAddress("PyFrame_FastToLocals"); PyRun_StringFlags = pyrtInfo.DLLs.Python.GetFunctionAddress("PyRun_StringFlags"); PyErr_Fetch = pyrtInfo.DLLs.Python.GetFunctionAddress("PyErr_Fetch"); PyErr_Restore = pyrtInfo.DLLs.Python.GetFunctionAddress("PyErr_Restore"); PyErr_Occurred = pyrtInfo.DLLs.Python.GetFunctionAddress("PyErr_Occurred"); PyObject_Str = pyrtInfo.DLLs.Python.GetFunctionAddress("PyObject_Str"); } } private readonly DkmProcess _process; private readonly PythonRuntimeInfo _pyrtInfo; private readonly PythonDllBreakpointHandlers _handlers; private readonly DkmNativeInstructionAddress _traceFunc; private readonly DkmNativeInstructionAddress _evalFrameFunc; private readonly PointerProxy _defaultEvalFrameFunc; private readonly UInt32Proxy _pyTracingPossible; private readonly ByteProxy _isTracing; // A step-in gate is a function inside the Python interpreter or one of the libaries that may call out // to native user code such that it may be a potential target of a step-in operation. For every gate, // we record its address in the process, and create a breakpoint. The breakpoints are initially disabled, // and only get enabled when a step-in operation is initiated - and then disabled again once it completes. private struct StepInGate { public DkmRuntimeInstructionBreakpoint Breakpoint; public StepInGateHandler Handler; public bool HasMultipleExitPoints; // see StepInGateAttribute } /// <summary> /// A handler for a step-in gate, run either when a breakpoint at the entry of the gate is hit, or /// when a step-in is executed while the gate is the topmost frame on the stack. The handler should /// compute any potential runtime exits and pass them to <see cref="OnPotentialRuntimeExit"/>. /// </summary> /// <param name="useRegisters"> /// If true, the handler cannot rely on symbolic expression evaluation to compute the values of any /// parameters passed to the gate, and should instead retrieve them directly from the CPU registers. /// <remarks> /// This is currently only true on x64 when entry breakpoint is hit, because x64 uses registers for /// argument passing (x86 cdecl uses the stack), and function prolog does not necessarily copy /// values to the corresponding stack locations for them - so C++ expression evaluator will produce /// incorrect results for arguments, or fail to evaluate them altogether. /// </remarks> /// </param> public delegate void StepInGateHandler(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters); private readonly List<StepInGate> _stepInGates = new List<StepInGate>(); // Breakpoints corresponding to the native functions outside of Python runtime that can potentially // be called by Python. These lists are dynamically filled for every new step operation, when one of // the Python DLL breakpoints above is hit. They are cleared after that step operation completes. private readonly List<DkmRuntimeBreakpoint> _stepInTargetBreakpoints = new List<DkmRuntimeBreakpoint>(); private readonly List<DkmRuntimeBreakpoint> _stepOutTargetBreakpoints = new List<DkmRuntimeBreakpoint>(); public unsafe TraceManagerLocalHelper(DkmProcess process, Kind kind) { _process = process; _pyrtInfo = process.GetPythonRuntimeInfo(); _traceFunc = _pyrtInfo.DLLs.DebuggerHelper.GetExportedFunctionAddress("TraceFunc"); _evalFrameFunc = _pyrtInfo.DLLs.DebuggerHelper.GetExportedFunctionAddress("EvalFrameFunc"); _defaultEvalFrameFunc = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<PointerProxy>("DefaultEvalFrameFunc"); _isTracing = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<ByteProxy>("isTracing"); _pyTracingPossible = _pyrtInfo.DLLs.Python.GetStaticVariable<UInt32Proxy>("_Py_TracingPossible"); if (kind == Kind.StepIn) { var fieldOffsets = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<CliStructProxy<FieldOffsets>>("fieldOffsets"); fieldOffsets.Write(new FieldOffsets(process, _pyrtInfo)); var types = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<CliStructProxy<Types>>("types"); types.Write(new Types(process, _pyrtInfo)); var functionPointers = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<CliStructProxy<FunctionPointers>>("functionPointers"); functionPointers.Write(new FunctionPointers(process, _pyrtInfo)); var stringEquals = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<PointerProxy>("stringEquals"); if (_pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { stringEquals.Write(_pyrtInfo.DLLs.DebuggerHelper.GetExportedFunctionAddress("StringEquals27").GetPointer()); } else { stringEquals.Write(_pyrtInfo.DLLs.DebuggerHelper.GetExportedFunctionAddress("StringEquals33").GetPointer()); } foreach (var interp in PyInterpreterState.GetInterpreterStates(process)) { if (_pyrtInfo.LanguageVersion >= PythonLanguageVersion.V36) { RegisterJITTracing(interp); } foreach (var tstate in interp.GetThreadStates()) { RegisterTracing(tstate); } } _handlers = new PythonDllBreakpointHandlers(this); LocalComponent.CreateRuntimeDllFunctionExitBreakpoints(_pyrtInfo.DLLs.Python, "new_threadstate", _handlers.new_threadstate, enable: true); LocalComponent.CreateRuntimeDllFunctionExitBreakpoints(_pyrtInfo.DLLs.Python, "PyInterpreterState_New", _handlers.PyInterpreterState_New, enable: true); foreach (var methodInfo in _handlers.GetType().GetMethods()) { var stepInAttr = (StepInGateAttribute)Attribute.GetCustomAttribute(methodInfo, typeof(StepInGateAttribute)); if (stepInAttr != null && (stepInAttr.MinVersion == PythonLanguageVersion.None || _pyrtInfo.LanguageVersion >= stepInAttr.MinVersion) && (stepInAttr.MaxVersion == PythonLanguageVersion.None || _pyrtInfo.LanguageVersion <= stepInAttr.MaxVersion)) { var handler = (StepInGateHandler)Delegate.CreateDelegate(typeof(StepInGateHandler), _handlers, methodInfo); AddStepInGate(handler, _pyrtInfo.DLLs.Python, methodInfo.Name, stepInAttr.HasMultipleExitPoints); } } if (_pyrtInfo.DLLs.CTypes != null) { OnCTypesLoaded(_pyrtInfo.DLLs.CTypes); } } } private void AddStepInGate(StepInGateHandler handler, DkmNativeModuleInstance module, string funcName, bool hasMultipleExitPoints) { var gate = new StepInGate { Handler = handler, HasMultipleExitPoints = hasMultipleExitPoints, Breakpoint = LocalComponent.CreateRuntimeDllFunctionBreakpoint(module, funcName, (thread, frameBase, vframe, retAddr) => handler(thread, frameBase, vframe, useRegisters: thread.Process.Is64Bit())) }; _stepInGates.Add(gate); } public void OnCTypesLoaded(DkmNativeModuleInstance moduleInstance) { AddStepInGate(_handlers._call_function_pointer, moduleInstance, "_call_function_pointer", hasMultipleExitPoints: false); } public unsafe void RegisterTracing(PyThreadState tstate) { tstate.use_tracing.Write(1); tstate.c_tracefunc.Write(_traceFunc.GetPointer()); _pyTracingPossible.Write(_pyTracingPossible.Read() + 1); _isTracing.Write(1); } public unsafe void RegisterJITTracing(PyInterpreterState istate) { Debug.Assert(_pyrtInfo.LanguageVersion >= PythonLanguageVersion.V36); var current = istate.eval_frame.Read(); if (current != _evalFrameFunc.GetPointer()) { _defaultEvalFrameFunc.Write(current); istate.eval_frame.Write(_evalFrameFunc.GetPointer()); } } public void OnBeginStepIn(DkmThread thread) { var frameInfo = new RemoteComponent.GetCurrentFrameInfoRequest { ThreadId = thread.UniqueId }.SendLower(thread.Process); var workList = DkmWorkList.Create(null); var topFrame = thread.GetTopStackFrame(); var curAddr = (topFrame != null) ? topFrame.InstructionAddress as DkmNativeInstructionAddress : null; foreach (var gate in _stepInGates) { gate.Breakpoint.Enable(); // A step-in may happen when we are stopped inside a step-in gate function. For example, when the gate function // calls out to user code more than once, and the user then steps out from the first call; we're now inside the // gate, but the runtime exit breakpoints for that gate have been cleared after the previous step-in completed. // To correctly handle this scenario, we need to check whether we're inside a gate with multiple exit points, and // if so, call the associated gate handler (as it the entry breakpoint for the gate is hit) so that it re-enables // the runtime exit breakpoints for that gate. if (gate.HasMultipleExitPoints && curAddr != null) { var addr = (DkmNativeInstructionAddress)gate.Breakpoint.InstructionAddress; if (addr.IsInSameFunction(curAddr)) { gate.Handler(thread, frameInfo.FrameBase, frameInfo.VFrame, useRegisters: false); } } } } public void OnBeginStepOut(DkmThread thread) { // When we're stepping out while in Python code, there are two possibilities. Either the stack looks like this: // // PythonFrame1 // PythonFrame2 // // or else it looks like this: // // PythonFrame // [Native to Python transition] // NativeFrame // // In both cases, we use native breakpoints on the return address to catch the end of step-out operation. // For Python-to-native step-out, this is the only option. For Python-to-Python, it would seem that TraceFunc // can detect it via PyTrace_RETURN, but it doesn't actually know whether the return is to Python or to // native at the point where it's reported - and, in any case, we need to let PyEval_EvalFrameEx to return // before reporting the completion of that step-out (otherwise we will show the returning frame in call stack). // Find the destination for step-out by walking the call stack and finding either the first native frame // outside of Python and helper DLLs, or the second Python frame. var inspectionSession = DkmInspectionSession.Create(_process, null); var frameFormatOptions = new DkmFrameFormatOptions(DkmVariableInfoFlags.None, DkmFrameNameFormatOptions.None, DkmEvaluationFlags.None, 10000, 10); var stackContext = DkmStackContext.Create(inspectionSession, thread, DkmCallStackFilterOptions.None, frameFormatOptions, null, null); DkmStackFrame frame = null; for (int pyFrameCount = 0; pyFrameCount != 2; ) { DkmStackFrame[] frames = null; var workList = DkmWorkList.Create(null); stackContext.GetNextFrames(workList, 1, (result) => { frames = result.Frames; }); workList.Execute(); if (frames == null || frames.Length != 1) { return; } frame = frames[0]; var frameModuleInstance = frame.ModuleInstance; if (frameModuleInstance is DkmNativeModuleInstance && frameModuleInstance != _pyrtInfo.DLLs.Python && frameModuleInstance != _pyrtInfo.DLLs.DebuggerHelper && frameModuleInstance != _pyrtInfo.DLLs.CTypes) { break; } else if (frame.RuntimeInstance != null && frame.RuntimeInstance.Id.RuntimeType == Guids.PythonRuntimeTypeGuid) { ++pyFrameCount; } } var nativeAddr = frame.InstructionAddress as DkmNativeInstructionAddress; if (nativeAddr == null) { var customAddr = frame.InstructionAddress as DkmCustomInstructionAddress; if (customAddr == null) { return; } var loc = new SourceLocation(customAddr.AdditionalData, thread.Process); nativeAddr = loc.NativeAddress; if (nativeAddr == null) { return; } } var bp = DkmRuntimeInstructionBreakpoint.Create(Guids.PythonStepTargetSourceGuid, thread, nativeAddr, false, null); bp.Enable(); _stepOutTargetBreakpoints.Add(bp); } public void OnStepComplete() { foreach (var gate in _stepInGates) { gate.Breakpoint.Disable(); } foreach (var bp in _stepInTargetBreakpoints) { bp.Close(); } _stepInTargetBreakpoints.Clear(); foreach (var bp in _stepOutTargetBreakpoints) { bp.Close(); } _stepOutTargetBreakpoints.Clear(); } // Sets a breakpoint on a given function pointer, that represents some code outside of the Python DLL that can potentially // be invoked as a result of the current step-in operation (in which case it is the step-in target). private void OnPotentialRuntimeExit(DkmThread thread, ulong funcPtr) { if (funcPtr == 0) { return; } if (_pyrtInfo.DLLs.Python.ContainsAddress(funcPtr)) { return; } else if (_pyrtInfo.DLLs.DebuggerHelper != null && _pyrtInfo.DLLs.DebuggerHelper.ContainsAddress(funcPtr)) { return; } else if (_pyrtInfo.DLLs.CTypes != null && _pyrtInfo.DLLs.CTypes.ContainsAddress(funcPtr)) { return; } var bp = _process.CreateBreakpoint(Guids.PythonStepTargetSourceGuid, funcPtr); bp.Enable(); _stepInTargetBreakpoints.Add(bp); } // Indicates that the breakpoint handler is for a Python-to-native step-in gate. [AttributeUsage(AttributeTargets.Method)] private class StepInGateAttribute : Attribute { public PythonLanguageVersion MinVersion { get; set; } public PythonLanguageVersion MaxVersion { get; set; } /// <summary> /// If true, this step-in gate function has more than one runtime exit point that can be executed in /// a single pass through the body of the function. For example, creating an instance of an object is /// a single gate that invokes both tp_new and tp_init sequentially. /// </summary> public bool HasMultipleExitPoints { get; set; } } private class PythonDllBreakpointHandlers { private readonly TraceManagerLocalHelper _owner; public PythonDllBreakpointHandlers(TraceManagerLocalHelper owner) { _owner = owner; } public void new_threadstate(DkmThread thread, ulong frameBase, ulong vframe, ulong returnAddress) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); // Addressing this local by name does not work for release builds, so read the return value directly from the register instead. var tstate = PyThreadState.TryCreate(process, cppEval.EvaluateReturnValueUInt64()); if (tstate == null) { return; } _owner.RegisterTracing(tstate); } public void PyInterpreterState_New(DkmThread thread, ulong frameBase, ulong vframe, ulong returnAddress) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); var istate = PyInterpreterState.TryCreate(process, cppEval.EvaluateReturnValueUInt64()); if (istate == null) { return; } if (process.GetPythonRuntimeInfo().LanguageVersion >= PythonLanguageVersion.V36) { _owner.RegisterJITTracing(istate); } } // This step-in gate is not marked [StepInGate] because it doesn't live in pythonXX.dll, and so we register it manually. public void _call_function_pointer(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); ulong pProc = cppEval.EvaluateUInt64(useRegisters ? "@rdx" : "pProc"); _owner.OnPotentialRuntimeExit(thread, pProc); } [StepInGate] public void call_function(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); int oparg = cppEval.EvaluateInt32(useRegisters ? "@rdx" : "oparg"); int na = oparg & 0xff; int nk = (oparg >> 8) & 0xff; int n = na + 2 * nk; ulong func = cppEval.EvaluateUInt64( "*((*(PyObject***){0}) - {1} - 1)", useRegisters ? "@rcx" : "pp_stack", n); var obj = PyObject.FromAddress(process, func); ulong ml_meth = cppEval.EvaluateUInt64( "((PyObject*){0})->ob_type == &PyCFunction_Type ? ((PyCFunctionObject*){0})->m_ml->ml_meth : 0", func); _owner.OnPotentialRuntimeExit(thread, ml_meth); } [StepInGate] public void PyCFunction_Call(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); ulong ml_meth = cppEval.EvaluateUInt64( "((PyObject*){0})->ob_type == &PyCFunction_Type ? ((PyCFunctionObject*){0})->m_ml->ml_meth : 0", useRegisters ? "@rcx" : "func"); _owner.OnPotentialRuntimeExit(thread, ml_meth); } [StepInGate] public void getset_get(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string descrVar = useRegisters ? "((PyGetSetDescrObject*)@rcx)" : "descr"; ulong get = cppEval.EvaluateUInt64(descrVar + "->d_getset->get"); _owner.OnPotentialRuntimeExit(thread, get); } [StepInGate] public void getset_set(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string descrVar = useRegisters ? "((PyGetSetDescrObject*)@rcx)" : "descr"; ulong set = cppEval.EvaluateUInt64(descrVar + "->d_getset->set"); _owner.OnPotentialRuntimeExit(thread, set); } [StepInGate(HasMultipleExitPoints = true)] public void type_call(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string typeVar = useRegisters ? "((PyTypeObject*)@rcx)" : "type"; ulong tp_new = cppEval.EvaluateUInt64(typeVar + "->tp_new"); _owner.OnPotentialRuntimeExit(thread, tp_new); ulong tp_init = cppEval.EvaluateUInt64(typeVar + "->tp_init"); _owner.OnPotentialRuntimeExit(thread, tp_init); } [StepInGate] public void PyType_GenericNew(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string typeVar = useRegisters ? "((PyTypeObject*)@rcx)" : "type"; ulong tp_alloc = cppEval.EvaluateUInt64(typeVar + "->tp_alloc"); _owner.OnPotentialRuntimeExit(thread, tp_alloc); } [StepInGate] public void PyObject_Print(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string opVar = useRegisters ? "((PyObject*)@rcx)" : "op"; ulong tp_print = cppEval.EvaluateUInt64(opVar + "->ob_type->tp_print"); _owner.OnPotentialRuntimeExit(thread, tp_print); } [StepInGate] public void PyObject_GetAttrString(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_getattr = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_getattr"); _owner.OnPotentialRuntimeExit(thread, tp_getattr); } [StepInGate] public void PyObject_SetAttrString(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_setattr = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_setattr"); _owner.OnPotentialRuntimeExit(thread, tp_setattr); } [StepInGate] public void PyObject_GetAttr(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_getattr = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_getattr"); _owner.OnPotentialRuntimeExit(thread, tp_getattr); ulong tp_getattro = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_getattro"); _owner.OnPotentialRuntimeExit(thread, tp_getattro); } [StepInGate] public void PyObject_SetAttr(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_setattr = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_setattr"); _owner.OnPotentialRuntimeExit(thread, tp_setattr); ulong tp_setattro = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_setattro"); _owner.OnPotentialRuntimeExit(thread, tp_setattro); } [StepInGate] public void PyObject_Repr(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_repr = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_repr"); _owner.OnPotentialRuntimeExit(thread, tp_repr); } [StepInGate] public void PyObject_Hash(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_hash = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_hash"); _owner.OnPotentialRuntimeExit(thread, tp_hash); } [StepInGate] public void PyObject_Call(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string funcVar = useRegisters ? "((PyObject*)@rcx)" : "func"; ulong tp_call = cppEval.EvaluateUInt64(funcVar + "->ob_type->tp_call"); _owner.OnPotentialRuntimeExit(thread, tp_call); } [StepInGate] public void PyObject_Str(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_str = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_str"); _owner.OnPotentialRuntimeExit(thread, tp_str); } [StepInGate(MaxVersion = PythonLanguageVersion.V27, HasMultipleExitPoints = true)] public void do_cmp(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; string wVar = useRegisters ? "((PyObject*)@rdx)" : "w"; ulong tp_compare1 = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_compare"); _owner.OnPotentialRuntimeExit(thread, tp_compare1); ulong tp_richcompare1 = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare1); ulong tp_compare2 = cppEval.EvaluateUInt64(wVar + "->ob_type->tp_compare"); _owner.OnPotentialRuntimeExit(thread, tp_compare2); ulong tp_richcompare2 = cppEval.EvaluateUInt64(wVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare2); } [StepInGate(MaxVersion = PythonLanguageVersion.V27, HasMultipleExitPoints = true)] public void PyObject_RichCompare(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; string wVar = useRegisters ? "((PyObject*)@rdx)" : "w"; ulong tp_compare1 = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_compare"); _owner.OnPotentialRuntimeExit(thread, tp_compare1); ulong tp_richcompare1 = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare1); ulong tp_compare2 = cppEval.EvaluateUInt64(wVar + "->ob_type->tp_compare"); _owner.OnPotentialRuntimeExit(thread, tp_compare2); ulong tp_richcompare2 = cppEval.EvaluateUInt64(wVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare2); } [StepInGate(MinVersion = PythonLanguageVersion.V33, HasMultipleExitPoints = true)] public void do_richcompare(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; string wVar = useRegisters ? "((PyObject*)@rdx)" : "w"; ulong tp_richcompare1 = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare1); ulong tp_richcompare2 = cppEval.EvaluateUInt64(wVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare2); } [StepInGate] public void PyObject_GetIter(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string oVar = useRegisters ? "((PyObject*)@rcx)" : "o"; ulong tp_iter = cppEval.EvaluateUInt64(oVar + "->ob_type->tp_iter"); _owner.OnPotentialRuntimeExit(thread, tp_iter); } [StepInGate] public void PyIter_Next(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string iterVar = useRegisters ? "((PyObject*)@rcx)" : "iter"; ulong tp_iternext = cppEval.EvaluateUInt64(iterVar + "->ob_type->tp_iternext"); _owner.OnPotentialRuntimeExit(thread, tp_iternext); } [StepInGate] public void builtin_next(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string argsVar = useRegisters ? "((PyTupleObject*)@rdx)" : "((PyTupleObject*)args)"; ulong tp_iternext = cppEval.EvaluateUInt64(argsVar + "->ob_item[0]->ob_type->tp_iternext"); _owner.OnPotentialRuntimeExit(thread, tp_iternext); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI; using NPOI.OpenXml4Net.OPC; using NPOI.OpenXml4Net.OPC.Internal; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.Util; using NPOI.XSSF; using NPOI.XSSF.Model; using NPOI.XSSF.UserModel; using NUnit.Framework; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using TestCases.HSSF; using TestCases.SS.UserModel; namespace TestCases.XSSF.UserModel { [TestFixture] public class TestXSSFWorkbook : BaseTestXWorkbook { public TestXSSFWorkbook() : base(XSSFITestDataProvider.instance) { } /** * Tests that we can save, and then re-load a new document */ [Test, RunSerialyAndSweepTmpFiles] public void SaveLoadNew() { XSSFWorkbook wb1 = new XSSFWorkbook(); //check that the default date system is Set to 1900 CT_WorkbookPr pr = wb1.GetCTWorkbook().workbookPr; Assert.IsNotNull(pr); Assert.IsTrue(pr.IsSetDate1904()); Assert.IsFalse(pr.date1904, "XSSF must use the 1900 date system"); ISheet sheet1 = wb1.CreateSheet("sheet1"); ISheet sheet2 = wb1.CreateSheet("sheet2"); wb1.CreateSheet("sheet3"); IRichTextString rts = wb1.GetCreationHelper().CreateRichTextString("hello world"); sheet1.CreateRow(0).CreateCell((short)0).SetCellValue(1.2); sheet1.CreateRow(1).CreateCell((short)0).SetCellValue(rts); sheet2.CreateRow(0); Assert.AreEqual(0, wb1.GetSheetAt(0).FirstRowNum); Assert.AreEqual(1, wb1.GetSheetAt(0).LastRowNum); Assert.AreEqual(0, wb1.GetSheetAt(1).FirstRowNum); Assert.AreEqual(0, wb1.GetSheetAt(1).LastRowNum); Assert.AreEqual(0, wb1.GetSheetAt(2).FirstRowNum); Assert.AreEqual(0, wb1.GetSheetAt(2).LastRowNum); FileInfo file = TempFile.CreateTempFile("poi-", ".xlsx"); Stream out1 = File.OpenWrite(file.FullName); wb1.Write(out1); out1.Close(); // Check the namespace Contains what we'd expect it to OPCPackage pkg = OPCPackage.Open(file.ToString()); PackagePart wbRelPart = pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/_rels/workbook.xml.rels")); Assert.IsNotNull(wbRelPart); Assert.IsTrue(wbRelPart.IsRelationshipPart); Assert.AreEqual(ContentTypes.RELATIONSHIPS_PART, wbRelPart.ContentType); PackagePart wbPart = pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/workbook.xml")); // Links to the three sheets, shared strings and styles Assert.IsTrue(wbPart.HasRelationships); Assert.AreEqual(5, wbPart.Relationships.Size); wb1.Close(); // Load back the XSSFWorkbook XSSFWorkbook wb2 = new XSSFWorkbook(pkg); Assert.AreEqual(3, wb2.NumberOfSheets); Assert.IsNotNull(wb2.GetSheetAt(0)); Assert.IsNotNull(wb2.GetSheetAt(1)); Assert.IsNotNull(wb2.GetSheetAt(2)); Assert.IsNotNull(wb2.GetSharedStringSource()); Assert.IsNotNull(wb2.GetStylesSource()); Assert.AreEqual(0, wb2.GetSheetAt(0).FirstRowNum); Assert.AreEqual(1, wb2.GetSheetAt(0).LastRowNum); Assert.AreEqual(0, wb2.GetSheetAt(1).FirstRowNum); Assert.AreEqual(0, wb2.GetSheetAt(1).LastRowNum); Assert.AreEqual(0, wb2.GetSheetAt(2).FirstRowNum); Assert.AreEqual(0, wb2.GetSheetAt(2).LastRowNum); sheet1 = wb2.GetSheetAt(0); Assert.AreEqual(1.2, sheet1.GetRow(0).GetCell(0).NumericCellValue, 0.0001); Assert.AreEqual("hello world", sheet1.GetRow(1).GetCell(0).RichStringCellValue.String); pkg.Close(); Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files."); } [Test] public void Existing() { XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("Formatting.xlsx"); Assert.IsNotNull(workbook.GetSharedStringSource()); Assert.IsNotNull(workbook.GetStylesSource()); // And check a few low level bits too OPCPackage pkg = OPCPackage.Open(HSSFTestDataSamples.OpenSampleFileStream("Formatting.xlsx")); PackagePart wbPart = pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/workbook.xml")); // Links to the three sheets, shared, styles and themes Assert.IsTrue(wbPart.HasRelationships); Assert.AreEqual(6, wbPart.Relationships.Size); pkg.Close(); workbook.Close(); } [Test] public void GetCellStyleAt() { XSSFWorkbook workbook = new XSSFWorkbook(); try { short i = 0; //get default style ICellStyle cellStyleAt = workbook.GetCellStyleAt(i); Assert.IsNotNull(cellStyleAt); //get custom style StylesTable styleSource = workbook.GetStylesSource(); XSSFCellStyle customStyle = new XSSFCellStyle(styleSource); XSSFFont font = new XSSFFont(); font.FontName = ("Verdana"); customStyle.SetFont(font); int x = styleSource.PutStyle(customStyle); cellStyleAt = workbook.GetCellStyleAt((short)x); Assert.IsNotNull(cellStyleAt); } finally { } } [Test] public void GetFontAt() { XSSFWorkbook workbook = new XSSFWorkbook(); try { StylesTable styleSource = workbook.GetStylesSource(); short i = 0; //get default font IFont fontAt = workbook.GetFontAt(i); Assert.IsNotNull(fontAt); //get customized font XSSFFont customFont = new XSSFFont(); customFont.IsItalic = (true); int x = styleSource.PutFont(customFont); fontAt = workbook.GetFontAt((short)x); Assert.IsNotNull(fontAt); } finally { workbook.Close(); } } [Test] public void GetNumCellStyles() { XSSFWorkbook workbook = new XSSFWorkbook(); try { //get default cellStyles Assert.AreEqual(1, workbook.NumCellStyles); } finally { workbook.Close(); } } [Test] public void LoadSave() { XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("Formatting.xlsx"); Assert.AreEqual(3, workbook.NumberOfSheets); Assert.AreEqual("dd/mm/yyyy", workbook.GetSheetAt(0).GetRow(1).GetCell(0).RichStringCellValue.String); Assert.IsNotNull(workbook.GetSharedStringSource()); Assert.IsNotNull(workbook.GetStylesSource()); // Write out, and check // Load up again, check all still there XSSFWorkbook wb2 = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook); Assert.AreEqual(3, wb2.NumberOfSheets); Assert.IsNotNull(wb2.GetSheetAt(0)); Assert.IsNotNull(wb2.GetSheetAt(1)); Assert.IsNotNull(wb2.GetSheetAt(2)); Assert.AreEqual("dd/mm/yyyy", wb2.GetSheetAt(0).GetRow(1).GetCell(0).RichStringCellValue.String); Assert.AreEqual("yyyy/mm/dd", wb2.GetSheetAt(0).GetRow(2).GetCell(0).RichStringCellValue.String); Assert.AreEqual("yyyy-mm-dd", wb2.GetSheetAt(0).GetRow(3).GetCell(0).RichStringCellValue.String); Assert.AreEqual("yy/mm/dd", wb2.GetSheetAt(0).GetRow(4).GetCell(0).RichStringCellValue.String); Assert.IsNotNull(wb2.GetSharedStringSource()); Assert.IsNotNull(wb2.GetStylesSource()); workbook.Close(); wb2.Close(); } [Test] public void Styles() { XSSFWorkbook wb1 = XSSFTestDataSamples.OpenSampleWorkbook("Formatting.xlsx"); StylesTable ss = wb1.GetStylesSource(); Assert.IsNotNull(ss); StylesTable st = ss; // Has 8 number formats Assert.AreEqual(8, st.NumDataFormats); // Has 2 fonts Assert.AreEqual(2, st.GetFonts().Count); // Has 2 Fills Assert.AreEqual(2, st.GetFills().Count); // Has 1 border Assert.AreEqual(1, st.GetBorders().Count); // Add two more styles Assert.AreEqual(StylesTable.FIRST_CUSTOM_STYLE_ID + 8, st.PutNumberFormat("testFORMAT")); Assert.AreEqual(StylesTable.FIRST_CUSTOM_STYLE_ID + 8, st.PutNumberFormat("testFORMAT")); Assert.AreEqual(StylesTable.FIRST_CUSTOM_STYLE_ID + 9, st.PutNumberFormat("testFORMAT2")); Assert.AreEqual(10, st.NumDataFormats); // Save, load back in again, and check XSSFWorkbook wb2 = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb1); wb1.Close(); ss = wb2.GetStylesSource(); Assert.IsNotNull(ss); Assert.AreEqual(10, st.NumDataFormats); Assert.AreEqual(2, st.GetFonts().Count); Assert.AreEqual(2, st.GetFills().Count); Assert.AreEqual(1, st.GetBorders().Count); wb2.Close(); } [Test] public void IncrementSheetId() { XSSFWorkbook wb = new XSSFWorkbook(); try { int sheetId = (int)(wb.CreateSheet() as XSSFSheet).sheet.sheetId; Assert.AreEqual(1, sheetId); sheetId = (int)(wb.CreateSheet() as XSSFSheet).sheet.sheetId; Assert.AreEqual(2, sheetId); //test file with gaps in the sheetId sequence XSSFWorkbook wbBack = XSSFTestDataSamples.OpenSampleWorkbook("47089.xlsm"); try { int lastSheetId = (int)(wbBack.GetSheetAt(wbBack.NumberOfSheets - 1) as XSSFSheet).sheet.sheetId; sheetId = (int)(wbBack.CreateSheet() as XSSFSheet).sheet.sheetId; Assert.AreEqual(lastSheetId + 1, sheetId); } finally { wbBack.Close(); } } finally { wb.Close(); } } /** * Test Setting of core properties such as Title and Author */ [Test] public void WorkbookProperties() { XSSFWorkbook workbook = new XSSFWorkbook(); try { POIXMLProperties props = workbook.GetProperties(); Assert.IsNotNull(props); //the Application property must be set for new workbooks, see Bugzilla #47559 Assert.AreEqual("NPOI", props.ExtendedProperties.GetUnderlyingProperties().Application); PackagePropertiesPart opcProps = props.CoreProperties.GetUnderlyingProperties(); Assert.IsNotNull(opcProps); opcProps.SetTitleProperty("Testing Bugzilla #47460"); Assert.AreEqual("NPOI", opcProps.GetCreatorProperty()); opcProps.SetCreatorProperty("poi-dev@poi.apache.org"); XSSFWorkbook wbBack = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook); Assert.AreEqual("NPOI", wbBack.GetProperties().ExtendedProperties.GetUnderlyingProperties().Application); opcProps = wbBack.GetProperties().CoreProperties.GetUnderlyingProperties(); Assert.AreEqual("Testing Bugzilla #47460", opcProps.GetTitleProperty()); Assert.AreEqual("poi-dev@poi.apache.org", opcProps.GetCreatorProperty()); } finally { workbook.Close(); } } /** * Verify that the attached Test data was not modified. If this Test method * fails, the Test data is not working properly. */ [Test] public void Bug47668() { XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("47668.xlsx"); IList allPictures = workbook.GetAllPictures(); Assert.AreEqual(1, allPictures.Count); PackagePartName imagePartName = PackagingUriHelper .CreatePartName("/xl/media/image1.jpeg"); PackagePart imagePart = workbook.Package.GetPart(imagePartName); Assert.IsNotNull(imagePart); foreach (XSSFPictureData pictureData in allPictures) { PackagePart picturePart = pictureData.GetPackagePart(); Assert.AreSame(imagePart, picturePart); } XSSFSheet sheet0 = (XSSFSheet)workbook.GetSheetAt(0); XSSFDrawing Drawing0 = (XSSFDrawing)sheet0.CreateDrawingPatriarch(); XSSFPictureData pictureData0 = (XSSFPictureData)Drawing0.GetRelations()[0]; byte[] data0 = pictureData0.Data; CRC32 crc0 = new CRC32(); crc0.Update(data0); XSSFSheet sheet1 = workbook.GetSheetAt(1) as XSSFSheet; XSSFDrawing Drawing1 = sheet1.CreateDrawingPatriarch() as XSSFDrawing; XSSFPictureData pictureData1 = (XSSFPictureData)Drawing1.GetRelations()[0]; byte[] data1 = pictureData1.Data; CRC32 crc1 = new CRC32(); crc1.Update(data1); Assert.AreEqual(crc0.Value, crc1.Value); workbook.Close(); } /** * When deleting a sheet make sure that we adjust sheet indices of named ranges */ [Test] public void Bug47737() { XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("47737.xlsx"); Assert.AreEqual(2, wb.NumberOfNames); Assert.IsNotNull(wb.GetCalculationChain()); XSSFName nm0 = (XSSFName)wb.GetNameAt(0); Assert.IsTrue(nm0.GetCTName().IsSetLocalSheetId()); Assert.AreEqual(0u, nm0.GetCTName().localSheetId); XSSFName nm1 = (XSSFName)wb.GetNameAt(1); Assert.IsTrue(nm1.GetCTName().IsSetLocalSheetId()); Assert.AreEqual(1u, nm1.GetCTName().localSheetId); wb.RemoveSheetAt(0); Assert.AreEqual(1, wb.NumberOfNames); XSSFName nm2 = (XSSFName)wb.GetNameAt(0); Assert.IsTrue(nm2.GetCTName().IsSetLocalSheetId()); Assert.AreEqual(0u, nm2.GetCTName().localSheetId); //calculation chain is Removed as well Assert.IsNull(wb.GetCalculationChain()); wb.Close(); } /** * Problems with XSSFWorkbook.RemoveSheetAt when workbook Contains chart */ [Test] public void Bug47813() { XSSFWorkbook wb1 = XSSFTestDataSamples.OpenSampleWorkbook("47813.xlsx"); Assert.AreEqual(3, wb1.NumberOfSheets); Assert.IsNotNull(wb1.GetCalculationChain()); Assert.AreEqual("Numbers", wb1.GetSheetName(0)); //the second sheet is of type 'chartsheet' Assert.AreEqual("Chart", wb1.GetSheetName(1)); Assert.IsTrue(wb1.GetSheetAt(1) is XSSFChartSheet); Assert.AreEqual("SomeJunk", wb1.GetSheetName(2)); wb1.RemoveSheetAt(2); Assert.AreEqual(2, wb1.NumberOfSheets); Assert.IsNull(wb1.GetCalculationChain()); XSSFWorkbook wb2 = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb1); Assert.AreEqual(2, wb2.NumberOfSheets); Assert.IsNull(wb2.GetCalculationChain()); Assert.AreEqual("Numbers", wb2.GetSheetName(0)); Assert.AreEqual("Chart", wb2.GetSheetName(1)); wb2.Close(); wb1.Close(); } /** * Problems with the count of the number of styles * coming out wrong */ [Test] public void Bug49702() { // First try with a new file XSSFWorkbook wb1 = new XSSFWorkbook(); // Should have one style Assert.AreEqual(1, wb1.NumCellStyles); wb1.GetCellStyleAt((short)0); try { wb1.GetCellStyleAt((short)1); Assert.Fail("Shouldn't be able to get style at 1 that doesn't exist"); } catch (ArgumentOutOfRangeException) { } // Add another one ICellStyle cs = wb1.CreateCellStyle(); cs.DataFormat = ((short)11); // Re-check Assert.AreEqual(2, wb1.NumCellStyles); wb1.GetCellStyleAt((short)0); wb1.GetCellStyleAt((short)1); try { wb1.GetCellStyleAt((short)2); Assert.Fail("Shouldn't be able to get style at 2 that doesn't exist"); } catch (ArgumentOutOfRangeException) { } // Save and reload XSSFWorkbook nwb = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb1); Assert.AreEqual(2, nwb.NumCellStyles); nwb.GetCellStyleAt((short)0); nwb.GetCellStyleAt((short)1); try { nwb.GetCellStyleAt((short)2); Assert.Fail("Shouldn't be able to Get style at 2 that doesn't exist"); } catch (ArgumentOutOfRangeException) { } // Now with an existing file XSSFWorkbook wb2 = XSSFTestDataSamples.OpenSampleWorkbook("sample.xlsx"); Assert.AreEqual(3, wb2.NumCellStyles); wb2.GetCellStyleAt((short)0); wb2.GetCellStyleAt((short)1); wb2.GetCellStyleAt((short)2); try { wb2.GetCellStyleAt((short)3); Assert.Fail("Shouldn't be able to Get style at 3 that doesn't exist"); } catch (ArgumentOutOfRangeException) { } wb2.Close(); wb1.Close(); nwb.Close(); } [Test] public void RecalcId() { XSSFWorkbook wb = new XSSFWorkbook(); Assert.IsFalse(wb.GetForceFormulaRecalculation()); CT_Workbook ctWorkbook = wb.GetCTWorkbook(); Assert.IsFalse(ctWorkbook.IsSetCalcPr()); wb.SetForceFormulaRecalculation(true); // resets the EngineId flag to zero CT_CalcPr calcPr = ctWorkbook.calcPr; Assert.IsNotNull(calcPr); Assert.AreEqual(0, (int)calcPr.calcId); calcPr.calcId = 100; Assert.IsTrue(wb.GetForceFormulaRecalculation()); wb.SetForceFormulaRecalculation(true); // resets the EngineId flag to zero Assert.AreEqual(0, (int)calcPr.calcId); Assert.IsFalse(wb.GetForceFormulaRecalculation()); // calcMode="manual" is unset when forceFormulaRecalculation=true calcPr.calcMode = (ST_CalcMode.manual); wb.SetForceFormulaRecalculation(true); Assert.AreEqual(ST_CalcMode.auto, calcPr.calcMode); } [Test] public void ChangeSheetNameWithSharedFormulas() { ChangeSheetNameWithSharedFormulas("shared_formulas.xlsx"); } [Test] public void ColumnWidthPOI52233() { XSSFWorkbook workbook = new XSSFWorkbook(); ISheet sheet = workbook.CreateSheet(); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); cell.SetCellValue("hello world"); sheet = workbook.CreateSheet(); sheet.SetColumnWidth(4, 5000); sheet.SetColumnWidth(5, 5000); sheet.GroupColumn((short)4, (short)5); accessWorkbook(workbook); MemoryStream stream = new MemoryStream(); try { workbook.Write(stream); } finally { stream.Close(); } accessWorkbook(workbook); workbook.Close(); } private void accessWorkbook(XSSFWorkbook workbook) { workbook.GetSheetAt(1).SetColumnGroupCollapsed(4, true); workbook.GetSheetAt(1).SetColumnGroupCollapsed(4, false); Assert.AreEqual("hello world", workbook.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue); Assert.AreEqual(2048, workbook.GetSheetAt(0).GetColumnWidth(0)); // <-works } [Test] public void Bug48495() { IWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("48495.xlsx"); assertSheetOrder(wb, "Sheet1"); ISheet sheet = wb.GetSheetAt(0); sheet.ShiftRows(2, sheet.LastRowNum, 1, true, false); IRow newRow = sheet.GetRow(2); if (newRow == null) newRow = sheet.CreateRow(2); newRow.CreateCell(0).SetCellValue(" Another Header"); wb.CloneSheet(0); assertSheetOrder(wb, "Sheet1", "Sheet1 (2)"); IWorkbook read = XSSFTestDataSamples.WriteOutAndReadBack(wb); Assert.IsNotNull(read); assertSheetOrder(read, "Sheet1", "Sheet1 (2)"); read.Close(); wb.Close(); } [Test] public void Bug47090a() { IWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("47090.xlsx"); assertSheetOrder(workbook, "Sheet1", "Sheet2"); workbook.RemoveSheetAt(0); assertSheetOrder(workbook, "Sheet2"); workbook.CreateSheet(); assertSheetOrder(workbook, "Sheet2", "Sheet1"); IWorkbook read = XSSFTestDataSamples.WriteOutAndReadBack(workbook); assertSheetOrder(read, "Sheet2", "Sheet1"); read.Close(); workbook.Close(); } [Test] public void Bug47090b() { IWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("47090.xlsx"); assertSheetOrder(workbook, "Sheet1", "Sheet2"); workbook.RemoveSheetAt(1); assertSheetOrder(workbook, "Sheet1"); workbook.CreateSheet(); assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point! IWorkbook read = XSSFTestDataSamples.WriteOutAndReadBack(workbook); assertSheetOrder(read, "Sheet1", "Sheet0"); read.Close(); workbook.Close(); } [Test] public void Bug47090c() { IWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("47090.xlsx"); assertSheetOrder(workbook, "Sheet1", "Sheet2"); workbook.RemoveSheetAt(0); assertSheetOrder(workbook, "Sheet2"); workbook.CloneSheet(0); assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)"); IWorkbook read = XSSFTestDataSamples.WriteOutAndReadBack(workbook); assertSheetOrder(read, "Sheet2", "Sheet2 (2)"); read.Close(); workbook.Close(); } [Test] public void Bug47090d() { IWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("47090.xlsx"); assertSheetOrder(workbook, "Sheet1", "Sheet2"); workbook.CreateSheet(); assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0"); workbook.RemoveSheetAt(0); assertSheetOrder(workbook, "Sheet2", "Sheet0"); workbook.CreateSheet(); assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1"); IWorkbook read = XSSFTestDataSamples.WriteOutAndReadBack(workbook); assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1"); read.Close(); workbook.Close(); } [Test] public void Bug51158() { // create a workbook XSSFWorkbook wb1 = new XSSFWorkbook(); XSSFSheet sheet = wb1.CreateSheet("Test Sheet") as XSSFSheet; XSSFRow row = sheet.CreateRow(2) as XSSFRow; XSSFCell cell = row.CreateCell(3) as XSSFCell; cell.SetCellValue("test1"); //XSSFCreationHelper helper = workbook.GetCreationHelper(); //cell.Hyperlink=(/*setter*/helper.CreateHyperlink(0)); XSSFComment comment = (sheet.CreateDrawingPatriarch() as XSSFDrawing).CreateCellComment(new XSSFClientAnchor()) as XSSFComment; Assert.IsNotNull(comment); comment.SetString("some comment"); // ICellStyle cs = workbook.CreateCellStyle(); // cs.ShrinkToFit=(/*setter*/false); // row.CreateCell(0).CellStyle=(/*setter*/cs); // write the first excel file XSSFWorkbook wb2 = XSSFTestDataSamples.WriteOutAndReadBack(wb1) as XSSFWorkbook; Assert.IsNotNull(wb2); sheet = wb2.GetSheetAt(0) as XSSFSheet; row = sheet.GetRow(2) as XSSFRow; Assert.AreEqual("test1", row.GetCell(3).StringCellValue); Assert.IsNull(row.GetCell(4)); // add a new cell to the sheet cell = row.CreateCell(4) as XSSFCell; cell.SetCellValue("test2"); // write the second excel file XSSFWorkbook wb3 = XSSFTestDataSamples.WriteOutAndReadBack(wb2) as XSSFWorkbook; Assert.IsNotNull(wb3); sheet = wb3.GetSheetAt(0) as XSSFSheet; row = sheet.GetRow(2) as XSSFRow; Assert.AreEqual("test1", row.GetCell(3).StringCellValue); Assert.AreEqual("test2", row.GetCell(4).StringCellValue); wb3.Close(); wb2.Close(); wb1.Close(); } [Test] public void Bug51158a() { // create a workbook XSSFWorkbook workbook = new XSSFWorkbook(); try { workbook.CreateSheet("Test Sheet"); XSSFSheet sheetBack = workbook.GetSheetAt(0) as XSSFSheet; // Committing twice did add the XML twice without Clearing the part in between sheetBack.Commit(); // ensure that a memory based package part does not have lingering data from previous Commit() calls if (sheetBack.GetPackagePart() is MemoryPackagePart) { ((MemoryPackagePart)sheetBack.GetPackagePart()).Clear(); } sheetBack.Commit(); String str = Encoding.UTF8.GetString(IOUtils.ToByteArray(sheetBack.GetPackagePart().GetInputStream())); //System.out.Println(str); Assert.AreEqual(1, countMatches(str, "<worksheet")); } finally { workbook.Close(); } } private static int INDEX_NOT_FOUND = -1; private static int countMatches(string str, string sub) { if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(sub)) { return 0; } int count = 0; int idx = 0; while ((idx = IndexOf(str, sub, idx)) != INDEX_NOT_FOUND) { count++; idx += sub.Length; } return count; } private static int IndexOf(string cs, string searchChar, int start) { return cs.ToString().IndexOf(searchChar.ToString(), start); } [Test] public void AddPivotCache() { XSSFWorkbook wb = new XSSFWorkbook(); try { CT_Workbook ctWb = wb.GetCTWorkbook(); CT_PivotCache pivotCache = wb.AddPivotCache("0"); //Ensures that pivotCaches is Initiated Assert.IsTrue(ctWb.IsSetPivotCaches()); Assert.AreSame(pivotCache, ctWb.pivotCaches.GetPivotCacheArray(0)); Assert.AreEqual("0", pivotCache.id); } finally { wb.Close(); } } protected void SetPivotData(XSSFWorkbook wb) { XSSFSheet sheet = wb.CreateSheet() as XSSFSheet; IRow row1 = sheet.CreateRow(0); // Create a cell and Put a value in it. ICell cell = row1.CreateCell(0); cell.SetCellValue("Names"); ICell cell2 = row1.CreateCell(1); cell2.SetCellValue("#"); ICell cell7 = row1.CreateCell(2); cell7.SetCellValue("Data"); IRow row2 = sheet.CreateRow(1); ICell cell3 = row2.CreateCell(0); cell3.SetCellValue("Jan"); ICell cell4 = row2.CreateCell(1); cell4.SetCellValue(10); ICell cell8 = row2.CreateCell(2); cell8.SetCellValue("Apa"); IRow row3 = sheet.CreateRow(2); ICell cell5 = row3.CreateCell(0); cell5.SetCellValue("Ben"); ICell cell6 = row3.CreateCell(1); cell6.SetCellValue(9); ICell cell9 = row3.CreateCell(2); cell9.SetCellValue("Bepa"); AreaReference source = new AreaReference("A1:B2", SpreadsheetVersion.EXCEL2007); sheet.CreatePivotTable(source, new CellReference("H5")); } [Test] public void LoadWorkbookWithPivotTable() { String fileName = Path.Combine(TestContext.CurrentContext.TestDirectory, "ooxml-pivottable.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(); SetPivotData(wb); FileStream fileOut = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite); wb.Write(fileOut); fileOut.Close(); XSSFWorkbook wb2 = (XSSFWorkbook)WorkbookFactory.Create(fileName); Assert.IsTrue(wb2.PivotTables.Count == 1); } [Test] public void AddPivotTableToWorkbookWithLoadedPivotTable() { String fileName = "ooxml-pivottable.xlsx"; XSSFWorkbook wb = new XSSFWorkbook(); SetPivotData(wb); FileStream fileOut = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite); wb.Write(fileOut); fileOut.Close(); XSSFWorkbook wb2 = (XSSFWorkbook)WorkbookFactory.Create(fileName); SetPivotData(wb2); Assert.IsTrue(wb2.PivotTables.Count == 2); } [Test] public void SetFirstVisibleTab_57373() { XSSFWorkbook wb = new XSSFWorkbook(); try { /*Sheet sheet1 =*/ wb.CreateSheet(); ISheet sheet2 = wb.CreateSheet(); int idx2 = wb.GetSheetIndex(sheet2); ISheet sheet3 = wb.CreateSheet(); int idx3 = wb.GetSheetIndex(sheet3); // add many sheets so "first visible" is relevant for (int i = 0; i < 30; i++) { wb.CreateSheet(); } wb.FirstVisibleTab = (/*setter*/idx2); wb.SetActiveSheet(idx3); //wb.Write(new FileOutputStream(new File("C:\\temp\\test.xlsx"))); Assert.AreEqual(idx2, wb.FirstVisibleTab); Assert.AreEqual(idx3, wb.ActiveSheetIndex); IWorkbook wbBack = XSSFTestDataSamples.WriteOutAndReadBack(wb); sheet2 = wbBack.GetSheetAt(idx2); sheet3 = wbBack.GetSheetAt(idx3); Assert.AreEqual(idx2, wb.FirstVisibleTab); Assert.AreEqual(idx3, wb.ActiveSheetIndex); wbBack.Close(); } finally { wb.Close(); } } /** * Tests that we can save a workbook with macros and reload it. */ [Test] public void TestSetVBAProject() { FileInfo file; byte[] allBytes = new byte[256]; for (int i = 0; i < 256; i++) { allBytes[i] = (byte)(i - 128); } XSSFWorkbook wb1 = new XSSFWorkbook(); wb1.CreateSheet(); wb1.SetVBAProject(new ByteArrayInputStream(allBytes)); file = TempFile.CreateTempFile("poi-", ".xlsm"); Stream out1 = new FileStream(file.FullName, FileMode.Open, FileAccess.ReadWrite); wb1.Write(out1); out1.Close(); wb1.Close(); // Check the package contains what we'd expect it to OPCPackage pkg = OPCPackage.Open(file); PackagePart wbPart = pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/workbook.xml")); Assert.IsTrue(wbPart.HasRelationships); PackageRelationshipCollection relationships = wbPart.Relationships.GetRelationships(XSSFRelation.VBA_MACROS.Relation); Assert.AreEqual(1, relationships.Size); Assert.AreEqual(XSSFRelation.VBA_MACROS.DefaultFileName, relationships.GetRelationship(0).TargetUri.ToString()); PackagePart vbaPart = pkg.GetPart(PackagingUriHelper.CreatePartName(XSSFRelation.VBA_MACROS.DefaultFileName)); Assert.IsNotNull(vbaPart); Assert.IsFalse(vbaPart.IsRelationshipPart); Assert.AreEqual(XSSFRelation.VBA_MACROS.ContentType, vbaPart.ContentType); byte[] fromFile = IOUtils.ToByteArray(vbaPart.GetInputStream()); CollectionAssert.AreEqual(allBytes, fromFile); // Load back the XSSFWorkbook just to check nothing explodes XSSFWorkbook wb2 = new XSSFWorkbook(pkg); Assert.AreEqual(1, wb2.NumberOfSheets); Assert.AreEqual(XSSFWorkbookType.XLSM, wb2.WorkbookType); pkg.Close(); } [Test] public void TestBug54399() { XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("54399.xlsx"); for (int i = 0; i < workbook.NumberOfSheets; i++) { //System.out.println("i:" + i); workbook.SetSheetName(i, "SheetRenamed" + (i + 1)); } workbook.Close(); } /** * Iterator<XSSFSheet> XSSFWorkbook.iterator was committed in r700472 on 2008-09-30 * and has been replaced with Iterator<Sheet> XSSFWorkbook.iterator * * In order to make code for looping over sheets in workbooks standard, regardless * of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously * available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator * have been replaced with Iterator<Sheet> {@link #iterator} and * Iterator<Sheet> {@link #sheetIterator}. This makes iterating over sheets in a workbook * similar to iterating over rows in a sheet and cells in a row. * * Note: this breaks backwards compatibility! Existing codebases will need to * upgrade their code with either of the following options presented in this test case. * */ [Test] public void Bug58245_XSSFSheetIterator() { XSSFWorkbook wb = new XSSFWorkbook(); wb.CreateSheet(); // ===================================================================== // Case 1: Existing code uses XSSFSheet for-each loop // ===================================================================== // Original code (no longer valid) /* for (XSSFSheet sh : wb) { sh.createRow(0); } */ // Option A: foreach (XSSFSheet sh in wb) { sh.CreateRow(0); } // Option B (preferred for new code): foreach (ISheet sh in wb) { sh.CreateRow(0); } // ===================================================================== // Case 2: Existing code creates an iterator variable // ===================================================================== // Original code (no longer valid) /* Iterator<XSSFSheet> it = wb.iterator(); XSSFSheet sh = it.next(); sh.createRow(0); */ // Option A: { IEnumerator<ISheet> it = wb.GetEnumerator(); it.MoveNext(); XSSFSheet sh = it.Current as XSSFSheet; sh.CreateRow(0); } // Option B: { //IEnumerator<XSSFSheet> it = wb.XssfSheetIterator(); //XSSFSheet sh = it.Current; //sh.CreateRow(0); } // Option C (preferred for new code): { IEnumerator<ISheet> it = wb.GetEnumerator(); it.MoveNext(); ISheet sh = it.Current; sh.CreateRow(0); } wb.Close(); } [Test] public void TestBug56957CloseWorkbook() { FileInfo file = TempFile.CreateTempFile("TestBug56957_", ".xlsx"); //String dateExp = "Sun Nov 09 00:00:00 CET 2014"; DateTime dateExp = LocaleUtil.GetLocaleCalendar(2014, 11, 9); IWorkbook workbook = null; try { // as the file is written to, we make a copy before actually working on it FileHelper.CopyFile(HSSFTestDataSamples.GetSampleFile("56957.xlsx"), file); Assert.IsTrue(file.Exists); // read-only mode works! workbook = WorkbookFactory.Create(OPCPackage.Open(file, PackageAccess.READ)); DateTime dateAct = workbook.GetSheetAt(0).GetRow(0).GetCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).DateCellValue; Assert.AreEqual(dateExp, dateAct); workbook.Close(); workbook = null; workbook = WorkbookFactory.Create(OPCPackage.Open(file, PackageAccess.READ)); dateAct = workbook.GetSheetAt(0).GetRow(0).GetCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).DateCellValue; Assert.AreEqual(dateExp, dateAct); workbook.Close(); workbook = null; // now check read/write mode workbook = WorkbookFactory.Create(OPCPackage.Open(file, PackageAccess.READ_WRITE)); dateAct = workbook.GetSheetAt(0).GetRow(0).GetCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).DateCellValue; Assert.AreEqual(dateExp, dateAct); workbook.Close(); workbook = null; workbook = WorkbookFactory.Create(OPCPackage.Open(file, PackageAccess.READ_WRITE)); dateAct = workbook.GetSheetAt(0).GetRow(0).GetCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).DateCellValue; Assert.AreEqual(dateExp, dateAct); workbook.Close(); workbook = null; } finally { if (workbook != null) { workbook.Close(); } Assert.IsTrue(file.Exists); file.Delete(); file.Refresh(); Assert.IsTrue(!file.Exists); } } [Test] public void CloseDoesNotModifyWorkbook() { String filename = "SampleSS.xlsx"; FileInfo file = POIDataSamples.GetSpreadSheetInstance().GetFileInfo(filename); IWorkbook wb; // Some tests commented out because close() modifies the file // See bug 58779 // String //wb = new XSSFWorkbook(file.Path); //assertCloseDoesNotModifyFile(filename, wb); // File //wb = new XSSFWorkbook(file); //assertCloseDoesNotModifyFile(filename, wb); // InputStream wb = new XSSFWorkbook(file.OpenRead()); assertCloseDoesNotModifyFile(filename, wb); // OPCPackage //wb = new XSSFWorkbook(OPCPackage.open(file)); //assertCloseDoesNotModifyFile(filename, wb); } [Test] public void TestCloseBeforeWrite() { IWorkbook wb = new XSSFWorkbook(); wb.CreateSheet("somesheet"); // test what happens if we close the Workbook before we write it out wb.Close(); try { XSSFTestDataSamples.WriteOutAndReadBack(wb); Assert.Fail("Expecting IOException here"); } catch (RuntimeException e) { // expected here Assert.IsTrue(e.InnerException is IOException, "Had: " + e.InnerException); } } /** * See bug #57840 test data tables */ [Test] public void GetTable() { XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("WithTable.xlsx"); XSSFTable table1 = wb.GetTable("Tabella1"); Assert.IsNotNull(table1, "Tabella1 was not found in workbook"); Assert.AreEqual("Tabella1", table1.Name, "Table name"); Assert.AreEqual("Foglio1", table1.SheetName, "Sheet name"); // Table lookup should be case-insensitive Assert.AreSame(table1, wb.GetTable("TABELLA1"), "Case insensitive table name lookup"); // If workbook does not contain any data tables matching the provided name, getTable should return null Assert.IsNull(wb.GetTable(null), "Null table name should not throw NPE"); Assert.IsNull(wb.GetTable("Foglio1"), "Should not be able to find non-existent table"); // If a table is added after getTable is called it should still be reachable by XSSFWorkbook.getTable // This test makes sure that if any caching is done that getTable never uses a stale cache XSSFTable table2 = (wb.GetSheet("Foglio2") as XSSFSheet).CreateTable(); table2.Name = "Table2"; Assert.AreSame(table2, wb.GetTable("Table2"), "Did not find Table2"); // If table name is modified after getTable is called, the table can only be found by its new name // This test makes sure that if any caching is done that getTable never uses a stale cache table1.Name = "Table1"; Assert.AreSame(table1, wb.GetTable("TABLE1"), "Did not find Tabella1 renamed to Table1"); wb.Close(); } [Test] public void TestRemoveSheet() { // Test removing a sheet maintains the named ranges correctly XSSFWorkbook wb = new XSSFWorkbook(); wb.CreateSheet("Sheet1"); wb.CreateSheet("Sheet2"); XSSFName sheet1Name = wb.CreateName() as XSSFName; sheet1Name.NameName = "name1"; sheet1Name.SheetIndex = 0; sheet1Name.RefersToFormula = "Sheet1!$A$1"; XSSFName sheet2Name = wb.CreateName() as XSSFName; sheet2Name.NameName = "name1"; sheet2Name.SheetIndex = 1; sheet2Name.RefersToFormula = "Sheet2!$A$1"; Assert.IsTrue(wb.GetAllNames().Contains(sheet1Name)); Assert.IsTrue(wb.GetAllNames().Contains(sheet2Name)); Assert.AreEqual(2, wb.GetNames("name1").Count); Assert.AreEqual(sheet1Name, wb.GetNames("name1")[0]); Assert.AreEqual(sheet2Name, wb.GetNames("name1")[1]); // Remove sheet1, we should only have sheet2Name now wb.RemoveSheetAt(0); Assert.IsFalse(wb.GetAllNames().Contains(sheet1Name)); Assert.IsTrue(wb.GetAllNames().Contains(sheet2Name)); Assert.AreEqual(1, wb.GetNames("name1").Count); Assert.AreEqual(sheet2Name, wb.GetNames("name1")[0]); // Check by index as well for sanity Assert.AreEqual(1, wb.NumberOfNames); Assert.AreEqual(0, wb.GetNameIndex("name1")); Assert.AreEqual(sheet2Name, wb.GetNameAt(0)); wb.Close(); } } }
// 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; using System.Diagnostics; namespace System.Xml { // Represents a collection of attributes that can be accessed by name or index. public sealed class XmlAttributeCollection : XmlNamedNodeMap, ICollection { internal XmlAttributeCollection(XmlNode parent) : base(parent) { } // Gets the attribute with the specified index. [System.Runtime.CompilerServices.IndexerName("ItemOf")] public XmlAttribute this[int i] { get { try { return (XmlAttribute)nodes[i]; } catch (ArgumentOutOfRangeException) { throw new IndexOutOfRangeException(SR.Xdom_IndexOutOfRange); } } } // Gets the attribute with the specified name. [System.Runtime.CompilerServices.IndexerName("ItemOf")] public XmlAttribute this[string name] { get { int hash = XmlNameHelper.GetHashCode(name); for (int i = 0; i < nodes.Count; i++) { XmlAttribute node = (XmlAttribute)nodes[i]; if (hash == node.LocalNameHash && name == node.Name) { return node; } } return null; } } // Gets the attribute with the specified LocalName and NamespaceUri. [System.Runtime.CompilerServices.IndexerName("ItemOf")] public XmlAttribute this[string localName, string namespaceURI] { get { int hash = XmlNameHelper.GetHashCode(localName); for (int i = 0; i < nodes.Count; i++) { XmlAttribute node = (XmlAttribute)nodes[i]; if (hash == node.LocalNameHash && localName == node.LocalName && namespaceURI == node.NamespaceURI) { return node; } } return null; } } internal int FindNodeOffset(XmlAttribute node) { for (int i = 0; i < nodes.Count; i++) { XmlAttribute tmp = (XmlAttribute)nodes[i]; if (tmp.LocalNameHash == node.LocalNameHash && tmp.Name == node.Name && tmp.NamespaceURI == node.NamespaceURI) { return i; } } return -1; } // Adds a XmlNode using its Name property public override XmlNode SetNamedItem(XmlNode node) { if (node == null) return null; if (!(node is XmlAttribute)) throw new ArgumentException(SR.Xdom_AttrCol_Object); int offset = FindNodeOffset(node.LocalName, node.NamespaceURI); if (offset == -1) { return InternalAppendAttribute((XmlAttribute)node); } else { XmlNode oldNode = base.RemoveNodeAt(offset); InsertNodeAt(offset, node); return oldNode; } } // Inserts the specified node as the first node in the collection. public XmlAttribute Prepend(XmlAttribute node) { if (node.OwnerDocument != null && node.OwnerDocument != parent.OwnerDocument) throw new ArgumentException(SR.Xdom_NamedNode_Context); if (node.OwnerElement != null) Detach(node); RemoveDuplicateAttribute(node); InsertNodeAt(0, node); return node; } // Inserts the specified node as the last node in the collection. public XmlAttribute Append(XmlAttribute node) { XmlDocument doc = node.OwnerDocument; if (doc == null || doc.IsLoading == false) { if (doc != null && doc != parent.OwnerDocument) { throw new ArgumentException(SR.Xdom_NamedNode_Context); } if (node.OwnerElement != null) { Detach(node); } AddNode(node); } else { base.AddNodeForLoad(node, doc); InsertParentIntoElementIdAttrMap(node); } return node; } // Inserts the specified attribute immediately before the specified reference attribute. public XmlAttribute InsertBefore(XmlAttribute newNode, XmlAttribute refNode) { if (newNode == refNode) return newNode; if (refNode == null) return Append(newNode); if (refNode.OwnerElement != parent) throw new ArgumentException(SR.Xdom_AttrCol_Insert); if (newNode.OwnerDocument != null && newNode.OwnerDocument != parent.OwnerDocument) throw new ArgumentException(SR.Xdom_NamedNode_Context); if (newNode.OwnerElement != null) Detach(newNode); int offset = FindNodeOffset(refNode.LocalName, refNode.NamespaceURI); Debug.Assert(offset != -1); // the if statement above guarantees that the ref node is in the collection int dupoff = RemoveDuplicateAttribute(newNode); if (dupoff >= 0 && dupoff < offset) offset--; InsertNodeAt(offset, newNode); return newNode; } // Inserts the specified attribute immediately after the specified reference attribute. public XmlAttribute InsertAfter(XmlAttribute newNode, XmlAttribute refNode) { if (newNode == refNode) return newNode; if (refNode == null) return Prepend(newNode); if (refNode.OwnerElement != parent) throw new ArgumentException(SR.Xdom_AttrCol_Insert); if (newNode.OwnerDocument != null && newNode.OwnerDocument != parent.OwnerDocument) throw new ArgumentException(SR.Xdom_NamedNode_Context); if (newNode.OwnerElement != null) Detach(newNode); int offset = FindNodeOffset(refNode.LocalName, refNode.NamespaceURI); Debug.Assert(offset != -1); // the if statement above guarantees that the ref node is in the collection int dupoff = RemoveDuplicateAttribute(newNode); if (dupoff >= 0 && dupoff <= offset) offset--; InsertNodeAt(offset + 1, newNode); return newNode; } // Removes the specified attribute node from the map. public XmlAttribute Remove(XmlAttribute node) { int cNodes = nodes.Count; for (int offset = 0; offset < cNodes; offset++) { if (nodes[offset] == node) { RemoveNodeAt(offset); return node; } } return null; } // Removes the attribute node with the specified index from the map. public XmlAttribute RemoveAt(int i) { if (i < 0 || i >= Count) return null; return (XmlAttribute)RemoveNodeAt(i); } // Removes all attributes from the map. public void RemoveAll() { int n = Count; while (n > 0) { n--; RemoveAt(n); } } void ICollection.CopyTo(Array array, int index) { for (int i = 0, max = Count; i < max; i++, index++) { array.SetValue(nodes[i], index); } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } int ICollection.Count { get { return base.Count; } } public void CopyTo(XmlAttribute[] array, int index) { for (int i = 0, max = Count; i < max; i++, index++) array[index] = (XmlAttribute)(((XmlNode)nodes[i]).CloneNode(true)); } internal override XmlNode AddNode(XmlNode node) { //should be sure by now that the node doesn't have the same name with an existing node in the collection RemoveDuplicateAttribute((XmlAttribute)node); XmlNode retNode = base.AddNode(node); Debug.Assert(retNode is XmlAttribute); InsertParentIntoElementIdAttrMap((XmlAttribute)node); return retNode; } internal override XmlNode InsertNodeAt(int i, XmlNode node) { XmlNode retNode = base.InsertNodeAt(i, node); InsertParentIntoElementIdAttrMap((XmlAttribute)node); return retNode; } internal override XmlNode RemoveNodeAt(int i) { //remove the node without checking replacement XmlNode retNode = base.RemoveNodeAt(i); Debug.Assert(retNode is XmlAttribute); RemoveParentFromElementIdAttrMap((XmlAttribute)retNode); // after remove the attribute, we need to check if a default attribute node should be created and inserted into the tree XmlAttribute defattr = parent.OwnerDocument.GetDefaultAttribute((XmlElement)parent, retNode.Prefix, retNode.LocalName, retNode.NamespaceURI); if (defattr != null) InsertNodeAt(i, defattr); return retNode; } internal void Detach(XmlAttribute attr) { attr.OwnerElement.Attributes.Remove(attr); } //insert the parent element node into the map internal void InsertParentIntoElementIdAttrMap(XmlAttribute attr) { XmlElement parentElem = parent as XmlElement; if (parentElem != null) { if (parent.OwnerDocument == null) return; XmlName attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName); if (attrname != null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName) { parent.OwnerDocument.AddElementWithId(attr.Value, parentElem); //add the element into the hashtable } } } //remove the parent element node from the map when the ID attribute is removed internal void RemoveParentFromElementIdAttrMap(XmlAttribute attr) { XmlElement parentElem = parent as XmlElement; if (parentElem != null) { if (parent.OwnerDocument == null) return; XmlName attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName); if (attrname != null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName) { parent.OwnerDocument.RemoveElementWithId(attr.Value, parentElem); //remove the element from the hashtable } } } //the function checks if there is already node with the same name existing in the collection // if so, remove it because the new one will be inserted to replace this one (could be in different position though ) // by the calling function later internal int RemoveDuplicateAttribute(XmlAttribute attr) { int ind = FindNodeOffset(attr.LocalName, attr.NamespaceURI); if (ind != -1) { XmlAttribute at = (XmlAttribute)nodes[ind]; base.RemoveNodeAt(ind); RemoveParentFromElementIdAttrMap(at); } return ind; } internal void ResetParentInElementIdAttrMap(string oldVal, string newVal) { XmlElement parentElem = parent as XmlElement; Debug.Assert(parentElem != null); XmlDocument doc = parent.OwnerDocument; Debug.Assert(doc != null); doc.RemoveElementWithId(oldVal, parentElem); //add the element into the hashtable doc.AddElementWithId(newVal, parentElem); } // WARNING: // For performance reasons, this function does not check // for xml attributes within the collection with the same full name. // This means that any caller of this function must be sure that // a duplicate attribute does not exist. internal XmlAttribute InternalAppendAttribute(XmlAttribute node) { // a duplicate node better not exist Debug.Assert(-1 == FindNodeOffset(node)); XmlNode retNode = base.AddNode(node); Debug.Assert(retNode is XmlAttribute); InsertParentIntoElementIdAttrMap((XmlAttribute)node); return (XmlAttribute)retNode; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace WixSharp { /// <summary> /// Defines service installer for the file being installed. It encapsulates functionality provided /// by <c>ServiceInstall</c> and <c>ServiceConfig</c> WiX elements. /// </summary> /// <example>The following sample demonstrates how to install service: /// <code> /// File service; /// var project = /// new Project("My Product", /// new Dir(@"%ProgramFiles%\My Company\My Product", /// service = new File(@"..\SimpleService\MyApp.exe"))); /// /// service.ServiceInstaller = new ServiceInstaller /// { /// Name = "WixSharp.TestSvc", /// StartOn = SvcEvent.Install, /// StopOn = SvcEvent.InstallUninstall_Wait, /// RemoveOn = SvcEvent.Uninstall_Wait, /// }; /// ... /// /// Compiler.BuildMsi(project); /// </code> /// </example> public partial class ServiceInstaller : WixEntity { /// <summary> /// Initializes a new instance of the <see cref="ServiceInstaller"/> class. /// </summary> public ServiceInstaller() { } /// <summary> /// Initializes a new instance of the <see cref="ServiceInstaller"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The name.</param> public ServiceInstaller(string name) { this.Name = name; } /// <summary> /// The error control associated with the service startup. The default value is <c>SvcErrorControl.normal</c>. /// </summary> public SvcErrorControl ErrorControl = SvcErrorControl.normal; /// <summary> /// Defines the way service starts. The default value is <c>SvcStartType.auto</c>. /// </summary> public SvcStartType StartType = SvcStartType.auto; /// <summary> /// The display name of the service as it is listed in the Control Panel. /// If not specified the name of the service will be used instead. /// </summary> public string DisplayName; /// <summary> /// The description of the service as it is listed in the Control Panel. /// </summary> public string Description; /// <summary> /// The type of the service (e.g. kernel/system driver, process). The default value is <c>SvcType.ownProcess</c>. /// </summary> public SvcType Type = SvcType.ownProcess; /// <summary> /// Associates 'start service' action with the specific service installation event. /// The default value is <c>SvcEvent.Install</c>. Meaning "start the service when it is installed". /// <para> /// Set this member to <c>null</c> if you don't want to start the service at any stage of the installation. /// </para> /// </summary> public SvcEvent StartOn = SvcEvent.Install; /// <summary> /// Associates 'stop service' action with the specific service installation event. /// The default value is <c>SvcEvent.InstallUninstall_Wait</c>. Meaning "stop the /// service when it is being installed and uninstalled and wait for the action completion". /// <para> /// Set this member to <c>null</c> if you don't want to stop the service at any stage of the installation. /// </para> /// </summary> public SvcEvent StopOn = SvcEvent.InstallUninstall_Wait; /// <summary> /// Associates 'remove service' action with the specific service installation event. /// The default value is <c>SvcEvent.Uninstall</c>. Meaning "remove the service when it is uninstalled". /// <para> /// Set this member to <c>null</c> if you don't want to remove the service at any stage of the installation. /// </para> /// </summary> public SvcEvent RemoveOn = SvcEvent.Uninstall; /// <summary> /// Semicolon separated list of the names of the external service the service being installed depends on. /// It supposed to be names (not the display names) of a previously installed services. /// <para>For example: DependsOn = "Dnscache;Dhcp"</para> /// </summary> public string DependsOn = ""; /// <summary> /// Fully qualified names must be used even for local accounts, /// e.g.: ".\LOCAL_ACCOUNT". Valid only when ServiceType is ownProcess. /// </summary> public string Account; /// <summary> /// Contains any command line arguments or properties required to run the service. /// </summary> public string Arguments; /// <summary> /// Determines whether the existing service description will be ignored. If 'yes', the service description will be null, /// even if the Description attribute is set. /// </summary> public bool? EraseDescription; /// <summary> /// Whether or not the service interacts with the desktop. /// </summary> public bool? Interactive; /// <summary> /// The load ordering group that this service should be a part of. /// </summary> public string LoadOrderGroup; /// <summary> /// The password for the account. Valid only when the account has a password. /// </summary> public string Password; /// <summary> /// The overall install should fail if this service fails to install. /// </summary> public bool? Vital; /// <summary> /// Renders ServiceInstaller properties to appropriate WiX elements /// </summary> /// <param name="project"> /// Project instance - may be modified to include WixUtilExtension namespace, /// if necessary. /// </param> /// <returns> /// Collection of XML entities to be added to the project XML result /// </returns> internal object[] ToXml(Project project) { var result = new List<XElement>(); result.Add(ServiceInstallToXml(project)); if (StopOn != null) result.Add(SvcEventToXml("Stop", StopOn)); if (StartOn != null) result.Add(SvcEventToXml("Start", StartOn)); if (RemoveOn != null) result.Add(SvcEventToXml("Remove", RemoveOn)); return result.ToArray(); } XElement ServiceInstallToXml(Project project) { var serviceInstall = new XElement("ServiceInstall", new XAttribute("Id", Id), new XAttribute("Name", Name), new XAttribute("DisplayName", DisplayName ?? Name), new XAttribute("Description", Description ?? DisplayName ?? Name), new XAttribute("Type", Type), new XAttribute("Start", StartType), new XAttribute("ErrorControl", ErrorControl)); serviceInstall.SetAttribute("Account", Account) .SetAttribute("Arguments", Arguments) .SetAttribute("Interactive", Interactive) .SetAttribute("LoadOrderGroup", LoadOrderGroup) .SetAttribute("Password", Password) .SetAttribute("EraseDescription", EraseDescription) .SetAttribute("Vital", Vital) .AddAttributes(Attributes); foreach (var item in DependsOn.Split(';')) { if (item.IsNotEmpty()) serviceInstall.AddElement("ServiceDependency", "Id=" + item); } if (DelayedAutoStart.HasValue || PreShutdownDelay.HasValue || ServiceSid != null) { var serviceConfig = new XElement("ServiceConfig"); serviceConfig.SetAttribute("DelayedAutoStart", DelayedAutoStart) .SetAttribute("PreShutdownDelay", PreShutdownDelay) .SetAttribute("ServiceSid", ServiceSid) .SetAttribute("OnInstall", ConfigureServiceTrigger.Install.PresentIn(ConfigureServiceTrigger)) .SetAttribute("OnReinstall", ConfigureServiceTrigger.Reinstall.PresentIn(ConfigureServiceTrigger)) .SetAttribute("OnUninstall", ConfigureServiceTrigger.Uninstall.PresentIn(ConfigureServiceTrigger)); serviceInstall.Add(serviceConfig); } if (IsFailureActionSet || ProgramCommandLine != null || RebootMessage != null || ResetPeriodInDays.HasValue || RestartServiceDelayInSeconds.HasValue) { project.IncludeWixExtension(WixExtension.Util); var serviceConfig = new XElement(WixExtension.Util.ToXNamespace() + "ServiceConfig"); serviceConfig.SetAttribute("FirstFailureActionType", FirstFailureActionType) .SetAttribute("SecondFailureActionType", SecondFailureActionType) .SetAttribute("ThirdFailureActionType", ThirdFailureActionType) .SetAttribute("ProgramCommandLine", ProgramCommandLine) .SetAttribute("RebootMessage", RebootMessage) .SetAttribute("ResetPeriodInDays", ResetPeriodInDays) .SetAttribute("RestartServiceDelayInSeconds", RestartServiceDelayInSeconds); serviceInstall.Add(serviceConfig); } return serviceInstall; } bool IsFailureActionSet { get { return FirstFailureActionType != FailureActionType.none || SecondFailureActionType != FailureActionType.none || ThirdFailureActionType!= FailureActionType.none; } } XElement SvcEventToXml(string controlType, SvcEvent value) { return new XElement("ServiceControl", new XAttribute("Id", controlType + this.Id), new XAttribute("Name", this.Name), new XAttribute(controlType, value.Type), new XAttribute("Wait", value.Wait.ToYesNo())); } #region ServiceConfig attributes /// <summary> /// Specifies whether an auto-start service should delay its start until after all other auto-start services. /// This property only affects auto-start services. If this property is not initialized the setting is not configured. /// </summary> public bool? DelayedAutoStart; //public object FailureActionsWhen { get; set; } //note implementing util:serviceconfig instead /// <summary> /// Specifies time in milliseconds that the Service Control Manager (SCM) waits after notifying /// the service of a system shutdown. If this attribute is not present the default value, 3 minutes, is used. /// </summary> public int? PreShutdownDelay; /// <summary> /// Specifies the service SID to apply to the service /// </summary> public ServiceSid ServiceSid; /// <summary> /// Specifies whether to configure the service when the parent Component is installed, reinstalled, or uninstalled /// </summary> /// <remarks> /// Defaults to ConfigureServiceTrigger.Install. /// Strictly applies to the configuration of properties: DelayedAutoStart, PreShutdownDelay, ServiceSid. /// </remarks> public ConfigureServiceTrigger ConfigureServiceTrigger = ConfigureServiceTrigger.Install; #endregion #region Util:ServiceConfig attributes /// <summary> /// Action to take on the first failure of the service /// </summary> public FailureActionType FirstFailureActionType = FailureActionType.none; /// <summary> /// If any of the three *ActionType attributes is "runCommand", /// this specifies the command to run when doing so. /// </summary> public string ProgramCommandLine; /// <summary> /// If any of the three *ActionType attributes is "reboot", /// this specifies the message to broadcast to server users before doing so. /// </summary> public string RebootMessage; /// <summary> /// Number of days after which to reset the failure count to zero if there are no failures. /// </summary> public int? ResetPeriodInDays; /// <summary> /// If any of the three *ActionType attributes is "restart", /// this specifies the number of seconds to wait before doing so. /// </summary> public int? RestartServiceDelayInSeconds; /// <summary> /// Action to take on the second failure of the service. /// </summary> public FailureActionType SecondFailureActionType = FailureActionType.none; /// <summary> /// Action to take on the third failure of the service. /// </summary> public FailureActionType ThirdFailureActionType = FailureActionType.none; #endregion } /// <summary> /// /// Flags for indicating when the service should be configured. /// </summary> [Flags] public enum ConfigureServiceTrigger { #pragma warning disable 1591 /// <summary> /// Not a valid value for ServiceConfig.On(Install, Reinstall, Uninstall) /// </summary> None = 0, Install = 1, Reinstall = 2, Uninstall = 4 #pragma warning restore 1591 } /// <summary> /// Defines details of the setup event triggering the service actions to be performed during the service installation. /// </summary> public class SvcEvent { /// <summary> /// Specifies when the service action occur. It can be one of the <see cref="SvcEventType"/> values. /// </summary> public SvcEventType Type; /// <summary> /// The flag indicating if after triggering the service action the setup should wait until te action is completed. /// </summary> public bool Wait; /// <summary> /// Predefined instance of <see cref="SvcEvent"/> with <c>Type</c> set to <see cref="SvcEventType.install"/> /// and <c>Wait</c> to <c>false</c>. It triggers the action during the service installation without /// waiting for the completion. /// </summary> static public SvcEvent Install = new SvcEvent { Type = SvcEventType.install, Wait = false }; /// <summary> /// Predefined instance of <see cref="SvcEvent"/> with <c>Type</c> set to <see cref="SvcEventType.install"/> /// and <c>Wait</c> to <c>true</c>. It triggers the action during the service installation with /// waiting for the completion. /// </summary> static public SvcEvent Install_Wait = new SvcEvent { Type = SvcEventType.install, Wait = true }; /// <summary> /// Predefined instance of <see cref="SvcEvent"/> with <c>Type</c> set to <see cref="SvcEventType.uninstall"/> /// and <c>Wait</c> to <c>false</c>. It triggers the action during the service installation /// without waiting for the completion. /// </summary> static public SvcEvent Uninstall = new SvcEvent { Type = SvcEventType.uninstall, Wait = false }; /// <summary> /// Predefined instance of <see cref="SvcEvent"/> with <c>Type</c> set to <see cref="SvcEventType.uninstall"/> /// and <c>Wait</c> to <c>true</c>. It triggers the action during the service installation with /// waiting for the completion. /// </summary> static public SvcEvent Uninstall_Wait = new SvcEvent { Type = SvcEventType.uninstall, Wait = true }; /// <summary> /// Predefined instance of <see cref="SvcEvent"/> with <c>Type</c> set to <see cref="SvcEventType.both"/> /// and <c>Wait</c> to <c>false</c>. It triggers the action during the service installation without /// waiting for the completion. /// </summary> static public SvcEvent InstallUninstall = new SvcEvent { Type = SvcEventType.both, Wait = false }; /// <summary> /// Predefined instance of <see cref="SvcEvent"/> with <c>Type</c> set to <see cref="SvcEventType.both"/> /// and <c>Wait</c> to <c>true</c>. It triggers the action during the service installation with /// waiting for the completion. /// </summary> static public SvcEvent InstallUninstall_Wait = new SvcEvent { Type = SvcEventType.both, Wait = true }; } /// <summary> /// Specifies the service SID to apply to the service. /// Valid values are "none", "restricted", "unrestricted" or a /// Formatted property that resolves to "0" (for "none"), /// "3" (for "restricted") or "1" (for "unrestricted"). /// </summary> public class ServiceSid : StringEnum<ServiceSid> { /// <summary> /// Initializes a new instance of the <see cref="ServiceSid"/> class. /// </summary> /// <param name="value">The value.</param> public ServiceSid(string value) : base(value) { } #pragma warning disable 1591 public static ServiceSid none = new ServiceSid("none"); public static ServiceSid restricted = new ServiceSid("restricted"); public static ServiceSid unrestricted = new ServiceSid("unrestricted"); #pragma warning restore 1591 } /// <summary> /// Possible values for ServiceInstall.(First|Second|Third)FailureActionType /// </summary> public enum FailureActionType { #pragma warning disable 1591 none, reboot, restart, runCommand #pragma warning restore 1591 } }
namespace SideBySide; public class ParameterCollection : IDisposable { public ParameterCollection() { m_command = new(); m_parameterCollection = m_command.Parameters; } public void Dispose() { m_command.Dispose(); } [Theory] [InlineData("Baz", 0)] [InlineData("@Test", 1)] [InlineData("?Foo", 2)] [InlineData("Bar", -1)] [InlineData("@Bar", -1)] [InlineData("?Bar", -1)] [InlineData("", -1)] #if !BASELINE [InlineData("@Baz", 0)] [InlineData("?Baz", 0)] [InlineData("@'Baz'", 0)] [InlineData("?Test", 1)] [InlineData("Test", 1)] [InlineData("@`Test`", 1)] [InlineData("Foo", 2)] [InlineData("@Foo", 2)] [InlineData("@\"Foo\"", 2)] #endif public void FindByName(string parameterName, int position) { m_parameterCollection.Add(new() { ParameterName = "Baz", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test", Value = 1 }); m_parameterCollection.Add(new() { ParameterName = "?Foo", Value = 2 }); int index = m_parameterCollection.IndexOf(parameterName); Assert.Equal(position, index); Assert.Equal(position != -1, m_parameterCollection.Contains(parameterName)); if (position == -1) { Assert.Throws<ArgumentException>(() => m_parameterCollection[parameterName]); } else { var parameter = m_parameterCollection[parameterName]; Assert.NotNull(parameter); Assert.Same(m_parameterCollection[position], parameter); } } [Theory] [InlineData("@test")] [InlineData("@Test")] [InlineData("@tEsT")] [InlineData("@TEST")] #if !BASELINE [InlineData("test")] [InlineData("@`test`")] [InlineData("@'test'")] #endif public void FindByNameIgnoringCase(string parameterName) { m_parameterCollection.AddWithValue("@Test", 1); Assert.Equal(1, m_parameterCollection.Count); Assert.True(m_parameterCollection.Contains(parameterName)); Assert.Equal(0, m_parameterCollection.IndexOf(parameterName)); var parameter = m_parameterCollection[parameterName]; Assert.Equal("@Test", parameter.ParameterName); Assert.Equal(1, parameter.Value); parameter = m_parameterCollection[0]; Assert.Equal("@Test", parameter.ParameterName); m_parameterCollection.RemoveAt(parameterName); Assert.Equal(0, m_parameterCollection.Count); } [Theory] [InlineData("@test")] [InlineData("@TEST")] #if !BASELINE [InlineData("test")] // https://bugs.mysql.com/bug.php?id=93370 [InlineData("@'test'")] [InlineData("@`TEST`")] #endif public void AddDuplicateParameter(string parameterName) { m_parameterCollection.AddWithValue("@test", 1); Assert.Throws<MySqlException>(() => { m_parameterCollection.AddWithValue(parameterName, 2); }); } [Fact] public void IndexOfNull() { #if !BASELINE Assert.Equal(-1, m_parameterCollection.IndexOf(null)); #else Assert.Throws<ArgumentNullException>(() => m_parameterCollection.IndexOf(null)); #endif } [Fact] public void Clear() { m_parameterCollection.Add(new() { ParameterName = "@Test1", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test2", Value = 1 }); Assert.Equal(0, m_parameterCollection.IndexOf("@Test1")); Assert.Equal(1, m_parameterCollection.IndexOf("@Test2")); m_parameterCollection.Clear(); Assert.Equal(0, m_parameterCollection.Count); Assert.Equal(-1, m_parameterCollection.IndexOf("@Test1")); Assert.Equal(-1, m_parameterCollection.IndexOf("@Test2")); } [Fact] public void RemoveAtIndex() { m_parameterCollection.Add(new() { ParameterName = "@Test1", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test2", Value = 1 }); Assert.Equal(0, m_parameterCollection.IndexOf("@Test1")); Assert.Equal(1, m_parameterCollection.IndexOf("@Test2")); m_parameterCollection.RemoveAt(0); Assert.Equal(1, m_parameterCollection.Count); Assert.Equal(-1, m_parameterCollection.IndexOf("@Test1")); Assert.Equal(0, m_parameterCollection.IndexOf("@Test2")); } [Fact] public void RemoveAtString() { m_parameterCollection.Add(new() { ParameterName = "@Test1", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test2", Value = 1 }); Assert.Equal(0, m_parameterCollection.IndexOf("@Test1")); Assert.Equal(1, m_parameterCollection.IndexOf("@Test2")); m_parameterCollection.RemoveAt("@Test1"); Assert.Equal(1, m_parameterCollection.Count); Assert.Equal(-1, m_parameterCollection.IndexOf("@Test1")); Assert.Equal(0, m_parameterCollection.IndexOf("@Test2")); } [Fact] public void SetParameterIndex() { m_parameterCollection.Add(new() { ParameterName = "@Test1", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test2", Value = 1 }); Assert.Equal(0, m_parameterCollection.IndexOf("@Test1")); Assert.Equal(1, m_parameterCollection.IndexOf("@Test2")); m_parameterCollection[0] = new() { ParameterName = "@Test3", Value = 2 }; Assert.Equal(2, m_parameterCollection.Count); Assert.Equal(-1, m_parameterCollection.IndexOf("@Test1")); Assert.Equal(0, m_parameterCollection.IndexOf("@Test3")); Assert.Equal(1, m_parameterCollection.IndexOf("@Test2")); } [Fact] public void SetParameterString() { m_parameterCollection.Add(new() { ParameterName = "@Test1", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test2", Value = 1 }); Assert.Equal(0, m_parameterCollection.IndexOf("@Test1")); Assert.Equal(1, m_parameterCollection.IndexOf("@Test2")); m_parameterCollection["@Test1"] = new() { ParameterName = "@Test3", Value = 2 }; Assert.Equal(2, m_parameterCollection.Count); Assert.Equal(-1, m_parameterCollection.IndexOf("@Test1")); Assert.Equal(0, m_parameterCollection.IndexOf("@Test3")); Assert.Equal(1, m_parameterCollection.IndexOf("@Test2")); m_parameterCollection.AddWithValue("@Test4", 2); Assert.Equal(2, m_parameterCollection.IndexOf("@Test4")); Assert.Equal(3, m_parameterCollection.Count); } [Fact] public void AddMySqlParameter() { var parameter = new MySqlParameter("test", MySqlDbType.Double, 3); var parameter2 = m_parameterCollection.Add(parameter); Assert.Same(parameter, parameter2); Assert.Same(parameter, m_parameterCollection[0]); } [Fact] public void AddNameType() { var parameter = m_parameterCollection.Add("test", MySqlDbType.Double); Assert.Equal("test", parameter.ParameterName); Assert.Equal(MySqlDbType.Double, parameter.MySqlDbType); Assert.Same(parameter, m_parameterCollection[0]); } [Fact] public void AddNameTypeSize() { var parameter = m_parameterCollection.Add("test", MySqlDbType.Double, 10); Assert.Equal("test", parameter.ParameterName); Assert.Equal(MySqlDbType.Double, parameter.MySqlDbType); Assert.Equal(10, parameter.Size); Assert.Same(parameter, m_parameterCollection[0]); } [Fact] public void CopyTo() { m_parameterCollection.Add(new() { ParameterName = "@Test1", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test2", Value = 1 }); var array = new DbParameter[2]; m_parameterCollection.CopyTo(array, 0); Assert.Same(array[0], m_parameterCollection[0]); Assert.Same(array[1], m_parameterCollection[1]); } [Fact] public void CopyToIndex() { m_parameterCollection.Add(new() { ParameterName = "@Test1", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test2", Value = 1 }); var array = new DbParameter[4]; m_parameterCollection.CopyTo(array, 1); Assert.Null(array[0]); Assert.Same(array[1], m_parameterCollection[0]); Assert.Same(array[2], m_parameterCollection[1]); Assert.Null(array[3]); } [Fact] public void CopyToNullArray() { m_parameterCollection.Add(new() { ParameterName = "@Test1", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test2", Value = 1 }); Assert.Throws<ArgumentNullException>(() => m_parameterCollection.CopyTo(null, 0)); } [Fact] public void CopyToSmallArray() { m_parameterCollection.Add(new() { ParameterName = "@Test1", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test2", Value = 1 }); Assert.Throws<ArgumentException>(() => m_parameterCollection.CopyTo(new DbParameter[1], 0)); } [Fact] public void CopyToIndexOutOfRange() { m_parameterCollection.Add(new() { ParameterName = "@Test1", Value = 0 }); m_parameterCollection.Add(new() { ParameterName = "@Test2", Value = 1 }); Assert.Throws<ArgumentException>(() => m_parameterCollection.CopyTo(new DbParameter[2], 3)); } [Fact] public void ChangeParameterNameAfterAdd() { using var cmd = new MySqlCommand(); using var cmd2 = new MySqlCommand(); var parameter = cmd.CreateParameter(); parameter.ParameterName = "@a"; cmd2.Parameters.Add(parameter); cmd.Parameters.Add(parameter); parameter.ParameterName = "@b"; Assert.Equal(parameter, cmd.Parameters["@b"]); Assert.Throws<ArgumentException>(() => cmd.Parameters["@a"]); // only works for the last collection that contained the parameter Assert.Throws<ArgumentException>(() => cmd2.Parameters["@b"]); Assert.Equal(parameter, cmd2.Parameters["@a"]); } [Fact] public void SetParameterNameAfterAdd() { using var cmd = new MySqlCommand(); var parameter = cmd.CreateParameter(); cmd.Parameters.Add(parameter); parameter.ParameterName = "@a"; Assert.Equal(parameter, cmd.Parameters["@a"]); } [Fact] public void SetTwoParametersToSameNAme() { using var cmd = new MySqlCommand(); var parameter1 = cmd.CreateParameter(); cmd.Parameters.Add(parameter1); var parameter2 = cmd.CreateParameter(); cmd.Parameters.Add(parameter2); parameter1.ParameterName = "@a"; #if !BASELINE Assert.Throws<MySqlException>(() => parameter2.ParameterName = "@a"); #else Assert.Throws<ArgumentException>(() => parameter2.ParameterName = "@a"); #endif } MySqlCommand m_command; MySqlParameterCollection m_parameterCollection; }
using Cinemachine.Utility; using UnityEngine; namespace Cinemachine { /// <summary> /// This is a CinemachineComponent in the Body section of the component pipeline. /// Its job is to position the camera in a fixed relationship to the vcam's Follow /// target object, with offsets and damping. /// /// The Tansposer will only change the camera's position in space. It will not /// re-orient or otherwise aim the camera. To to that, you need to instruct /// the vcam in the Aim section of its pipeline. /// </summary> [DocumentationSorting(5, DocumentationSortingAttribute.Level.UserRef)] [AddComponentMenu("")] // Don't display in add component menu [RequireComponent(typeof(CinemachinePipeline))] [SaveDuringPlay] public class CinemachineTransposer : CinemachineComponentBase { /// <summary> /// The coordinate space to use when interpreting the offset from the target /// </summary> [DocumentationSorting(5.01f, DocumentationSortingAttribute.Level.UserRef)] public enum BindingMode { /// <summary> /// Camera will be bound to the Follow target using a frame of reference consisting /// of the target's local frame at the moment when the virtual camera was enabled, /// or when the target was assigned. /// </summary> LockToTargetOnAssign = 0, /// <summary> /// Camera will be bound to the Follow target using a frame of reference consisting /// of the target's local frame, with the tilt and roll zeroed out. /// </summary> LockToTargetWithWorldUp = 1, /// <summary> /// Camera will be bound to the Follow target using a frame of reference consisting /// of the target's local frame, with the roll zeroed out. /// </summary> LockToTargetNoRoll = 2, /// <summary> /// Camera will be bound to the Follow target using the target's local frame. /// </summary> LockToTarget = 3, /// <summary>Camera will be bound to the Follow target using a world space offset.</summary> WorldSpace = 4, /// <summary>Offsets will be calculated relative to the target, using Camera-local axes</summary> SimpleFollowWithWorldUp = 5 } /// <summary>The coordinate space to use when interpreting the offset from the target</summary> [Tooltip("The coordinate space to use when interpreting the offset from the target. This is also used to set the camera's Up vector, which will be maintained when aiming the camera.")] public BindingMode m_BindingMode = BindingMode.LockToTargetWithWorldUp; /// <summary>The distance which the transposer will attempt to maintain from the transposer subject</summary> [Tooltip("The distance vector that the transposer will attempt to maintain from the Follow target")] public Vector3 m_FollowOffset = Vector3.back * 10f; /// <summary>How aggressively the camera tries to maintain the offset in the X-axis. /// Small numbers are more responsive, rapidly translating the camera to keep the target's /// x-axis offset. Larger numbers give a more heavy slowly responding camera. /// Using different settings per axis can yield a wide range of camera behaviors</summary> [Range(0f, 20f)] [Tooltip("How aggressively the camera tries to maintain the offset in the X-axis. Small numbers are more responsive, rapidly translating the camera to keep the target's x-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] public float m_XDamping = 1f; /// <summary>How aggressively the camera tries to maintain the offset in the Y-axis. /// Small numbers are more responsive, rapidly translating the camera to keep the target's /// y-axis offset. Larger numbers give a more heavy slowly responding camera. /// Using different settings per axis can yield a wide range of camera behaviors</summary> [Range(0f, 20f)] [Tooltip("How aggressively the camera tries to maintain the offset in the Y-axis. Small numbers are more responsive, rapidly translating the camera to keep the target's y-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] public float m_YDamping = 1f; /// <summary>How aggressively the camera tries to maintain the offset in the Z-axis. /// Small numbers are more responsive, rapidly translating the camera to keep the /// target's z-axis offset. Larger numbers give a more heavy slowly responding camera. /// Using different settings per axis can yield a wide range of camera behaviors</summary> [Range(0f, 20f)] [Tooltip("How aggressively the camera tries to maintain the offset in the Z-axis. Small numbers are more responsive, rapidly translating the camera to keep the target's z-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")] public float m_ZDamping = 1f; /// <summary>How aggressively the camera tries to track the target rotation's X angle. /// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.</summary> [Range(0f, 20f)] [Tooltip("How aggressively the camera tries to track the target rotation's X angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")] public float m_PitchDamping = 0; /// <summary>How aggressively the camera tries to track the target rotation's Y angle. /// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.</summary> [Range(0f, 20f)] [Tooltip("How aggressively the camera tries to track the target rotation's Y angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")] public float m_YawDamping = 0; /// <summary>How aggressively the camera tries to track the target rotation's Z angle. /// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.</summary> [Range(0f, 20f)] [Tooltip("How aggressively the camera tries to track the target rotation's Z angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")] public float m_RollDamping = 0f; protected virtual void OnValidate() { m_FollowOffset = EffectiveOffset; } /// <summary>Get the target offset, with sanitization</summary> protected Vector3 EffectiveOffset { get { Vector3 offset = m_FollowOffset; if (m_BindingMode == BindingMode.SimpleFollowWithWorldUp) { offset.x = 0; offset.z = -Mathf.Abs(offset.z); } return offset; } } /// <summary>True if component is enabled and has a valid Follow target</summary> public override bool IsValid { get { return enabled && FollowTarget != null; } } /// <summary>Get the Cinemachine Pipeline stage that this component implements. /// Always returns the Body stage</summary> public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Body; } } /// <summary>Positions the virtual camera according to the transposer rules.</summary> /// <param name="curState">The current camera state</param> /// <param name="deltaTime">Used for damping. If less than 0, no damping is done.</param> public override void MutateCameraState(ref CameraState curState, float deltaTime) { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineTransposer.MutateCameraState"); InitPrevFrameStateInfo(ref curState, deltaTime); if (IsValid) { Vector3 pos; Quaternion orient; Vector3 offset = EffectiveOffset; TrackTarget(deltaTime, curState.ReferenceUp, offset, out pos, out orient); curState.RawPosition = pos + orient * offset; curState.ReferenceUp = orient * Vector3.up; } //UnityEngine.Profiling.Profiler.EndSample(); } /// <summary>API for the editor, to process a position drag from the user. /// This implementation adds the delta to the follow offset.</summary> /// <param name="delta">The amount dragged this frame</param> public override void OnPositionDragged(Vector3 delta) { Quaternion targetOrientation = GetReferenceOrientation(VcamState.ReferenceUp); Vector3 localOffset = Quaternion.Inverse(targetOrientation) * delta; m_FollowOffset += localOffset; m_FollowOffset = EffectiveOffset; } /// <summary>Initializes the state for previous frame if appropriate.</summary> protected void InitPrevFrameStateInfo( ref CameraState curState, float deltaTime) { if (m_previousTarget != FollowTarget || deltaTime < 0) { m_previousTarget = FollowTarget; m_targetOrientationOnAssign = (m_previousTarget == null) ? Quaternion.identity : FollowTarget.rotation; } if (deltaTime < 0) { m_PreviousTargetPosition = curState.RawPosition; m_PreviousReferenceOrientation = GetReferenceOrientation(curState.ReferenceUp); } } /// <summary>Positions the virtual camera according to the transposer rules.</summary> /// <param name="deltaTime">Used for damping. If less than 0, no damping is done.</param> /// <param name="up">Current camera up</param> /// <param name="desiredCameraOffset">Where we want to put the camera relative to the follow target</param> /// <param name="outTargetPosition">Resulting camera position</param> /// <param name="outTargetOrient">Damped target orientation</param> protected void TrackTarget( float deltaTime, Vector3 up, Vector3 desiredCameraOffset, out Vector3 outTargetPosition, out Quaternion outTargetOrient) { Quaternion targetOrientation = GetReferenceOrientation(up); Quaternion dampedOrientation = targetOrientation; if (deltaTime >= 0) { Vector3 relative = (Quaternion.Inverse(m_PreviousReferenceOrientation) * targetOrientation).eulerAngles; for (int i = 0; i < 3; ++i) if (relative[i] > 180) relative[i] -= 360; relative = Damper.Damp(relative, AngularDamping, deltaTime); dampedOrientation = m_PreviousReferenceOrientation * Quaternion.Euler(relative); } m_PreviousReferenceOrientation = dampedOrientation; Vector3 targetPosition = FollowTarget.position; Vector3 currentPosition = m_PreviousTargetPosition; Vector3 worldOffset = targetPosition - currentPosition; // Adjust for damping, which is done in camera-offset-local coords if (deltaTime >= 0) { Quaternion dampingSpace; if (desiredCameraOffset.AlmostZero()) dampingSpace = VcamState.RawOrientation; else dampingSpace = Quaternion.LookRotation(dampedOrientation * desiredCameraOffset.normalized, up); Vector3 localOffset = Quaternion.Inverse(dampingSpace) * worldOffset; localOffset = Damper.Damp(localOffset, Damping, deltaTime); worldOffset = dampingSpace * localOffset; } outTargetPosition = m_PreviousTargetPosition = currentPosition + worldOffset; outTargetOrient = dampedOrientation; } /// <summary> /// Damping speeds for each of the 3 axes of the offset from target /// </summary> protected Vector3 Damping { get { switch (m_BindingMode) { case BindingMode.SimpleFollowWithWorldUp: return new Vector3(0, m_YDamping, m_ZDamping); default: return new Vector3(m_XDamping, m_YDamping, m_ZDamping); } } } /// <summary> /// Damping speeds for each of the 3 axes of the target's rotation /// </summary> protected Vector3 AngularDamping { get { switch (m_BindingMode) { case BindingMode.LockToTargetNoRoll: return new Vector3(m_PitchDamping, m_YawDamping, 0); case BindingMode.LockToTargetWithWorldUp: return new Vector3(0, m_YawDamping, 0); case BindingMode.LockToTargetOnAssign: case BindingMode.WorldSpace: case BindingMode.SimpleFollowWithWorldUp: return Vector3.zero; default: return new Vector3(m_PitchDamping, m_YawDamping, m_RollDamping); } } } /// <summary>Internal API for the Inspector Editor, so it can draw a marker at the target</summary> public Vector3 GeTargetCameraPosition(Vector3 worldUp) { if (!IsValid) return Vector3.zero; return FollowTarget.position + GetReferenceOrientation(worldUp) * EffectiveOffset; } /// <summary>State information for damping</summary> Vector3 m_PreviousTargetPosition = Vector3.zero; Quaternion m_PreviousReferenceOrientation = Quaternion.identity; Quaternion m_targetOrientationOnAssign = Quaternion.identity; Transform m_previousTarget = null; /// <summary>Internal API for the Inspector Editor, so it can draw a marker at the target</summary> public Quaternion GetReferenceOrientation(Vector3 worldUp) { if (FollowTarget != null) { Quaternion targetOrientation = FollowTarget.rotation; switch (m_BindingMode) { case BindingMode.LockToTargetOnAssign: return m_targetOrientationOnAssign; case BindingMode.LockToTargetWithWorldUp: return Uppify(targetOrientation, worldUp); case BindingMode.LockToTargetNoRoll: return Quaternion.LookRotation(targetOrientation * Vector3.forward, worldUp); case BindingMode.LockToTarget: return targetOrientation; case BindingMode.SimpleFollowWithWorldUp: { Vector3 dir = FollowTarget.position - VcamState.RawPosition; if (dir.AlmostZero()) break; return Uppify(Quaternion.LookRotation(dir, worldUp), worldUp); } default: break; } } return Quaternion.identity; } static Quaternion Uppify(Quaternion q, Vector3 up) { Quaternion r = Quaternion.FromToRotation(q * Vector3.up, up); return r * q; } } }
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 BullsAndCows.RestApi.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; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Tournament.Components; using osu.Game.Tournament.Models; using osu.Game.Tournament.Screens.Ladder.Components; using osuTK; using osuTK.Graphics; namespace osu.Game.Tournament.Screens.Schedule { public class ScheduleScreen : TournamentScreen // IProvidesVideo { private readonly Bindable<TournamentMatch> currentMatch = new Bindable<TournamentMatch>(); private Container mainContainer; private LadderInfo ladder; [BackgroundDependencyLoader] private void load(LadderInfo ladder) { this.ladder = ladder; RelativeSizeAxes = Axes.Both; InternalChildren = new Drawable[] { new TourneyVideo("schedule") { RelativeSizeAxes = Axes.Both, Loop = true, }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding(100) { Bottom = 50 }, Children = new Drawable[] { new GridContainer { RelativeSizeAxes = Axes.Both, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(), }, Content = new[] { new Drawable[] { new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Children = new Drawable[] { new DrawableTournamentHeaderText(), new Container { Margin = new MarginPadding { Top = 40 }, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new Box { Colour = Color4.White, Size = new Vector2(50, 10), }, new TournamentSpriteTextWithBackground("Schedule") { X = 60, Scale = new Vector2(0.8f) } } }, } }, }, new Drawable[] { mainContainer = new Container { RelativeSizeAxes = Axes.Both, } } } } } }, }; } protected override void LoadComplete() { base.LoadComplete(); currentMatch.BindTo(ladder.CurrentMatch); currentMatch.BindValueChanged(matchChanged, true); } private void matchChanged(ValueChangedEvent<TournamentMatch> match) { var upcoming = ladder.Matches.Where(p => !p.Completed.Value && p.Team1.Value != null && p.Team2.Value != null && Math.Abs(p.Date.Value.DayOfYear - DateTimeOffset.UtcNow.DayOfYear) < 4); var conditionals = ladder .Matches.Where(p => !p.Completed.Value && (p.Team1.Value == null || p.Team2.Value == null) && Math.Abs(p.Date.Value.DayOfYear - DateTimeOffset.UtcNow.DayOfYear) < 4) .SelectMany(m => m.ConditionalMatches.Where(cp => m.Acronyms.TrueForAll(a => cp.Acronyms.Contains(a)))); upcoming = upcoming.Concat(conditionals); upcoming = upcoming.OrderBy(p => p.Date.Value).Take(8); ScheduleContainer comingUpNext; mainContainer.Child = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, Height = 0.74f, Child = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Children = new Drawable[] { new ScheduleContainer("recent matches") { RelativeSizeAxes = Axes.Both, Width = 0.4f, ChildrenEnumerable = ladder.Matches .Where(p => p.Completed.Value && p.Team1.Value != null && p.Team2.Value != null && Math.Abs(p.Date.Value.DayOfYear - DateTimeOffset.UtcNow.DayOfYear) < 4) .OrderByDescending(p => p.Date.Value) .Take(8) .Select(p => new ScheduleMatch(p)) }, new ScheduleContainer("upcoming matches") { RelativeSizeAxes = Axes.Both, Width = 0.6f, ChildrenEnumerable = upcoming.Select(p => new ScheduleMatch(p)) }, } } }, comingUpNext = new ScheduleContainer("coming up next") { RelativeSizeAxes = Axes.Both, Height = 0.25f, } } }; if (match.NewValue != null) { comingUpNext.Child = new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(30), Children = new Drawable[] { new ScheduleMatch(match.NewValue, false) { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, new TournamentSpriteTextWithBackground(match.NewValue.Round.Value?.Name.Value) { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Scale = new Vector2(0.5f) }, new TournamentSpriteText { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Text = match.NewValue.Team1.Value?.FullName + " vs " + match.NewValue.Team2.Value?.FullName, Font = OsuFont.Torus.With(size: 24, weight: FontWeight.SemiBold) }, new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Children = new Drawable[] { new ScheduleMatchDate(match.NewValue.Date.Value) { Font = OsuFont.Torus.With(size: 24, weight: FontWeight.Regular) } } }, } }; } } public class ScheduleMatch : DrawableTournamentMatch { public ScheduleMatch(TournamentMatch match, bool showTimestamp = true) : base(match) { Flow.Direction = FillDirection.Horizontal; Scale = new Vector2(0.8f); CurrentMatchSelectionBox.Scale = new Vector2(1.02f, 1.15f); bool conditional = match is ConditionalTournamentMatch; if (conditional) Colour = OsuColour.Gray(0.5f); if (showTimestamp) { AddInternal(new DrawableDate(Match.Date.Value) { Anchor = Anchor.TopRight, Origin = Anchor.TopLeft, Colour = OsuColour.Gray(0.7f), Alpha = conditional ? 0.6f : 1, Font = OsuFont.Torus, Margin = new MarginPadding { Horizontal = 10, Vertical = 5 }, }); AddInternal(new TournamentSpriteText { Anchor = Anchor.BottomRight, Origin = Anchor.BottomLeft, Colour = OsuColour.Gray(0.7f), Alpha = conditional ? 0.6f : 1, Margin = new MarginPadding { Horizontal = 10, Vertical = 5 }, Text = match.Date.Value.ToUniversalTime().ToString("HH:mm UTC") + (conditional ? " (conditional)" : "") }); } } } public class ScheduleMatchDate : DrawableDate { public ScheduleMatchDate(DateTimeOffset date, float textSize = OsuFont.DEFAULT_FONT_SIZE, bool italic = true) : base(date, textSize, italic) { } protected override string Format() => Date < DateTimeOffset.Now ? $"Started {base.Format()}" : $"Starting {base.Format()}"; } public class ScheduleContainer : Container { protected override Container<Drawable> Content => content; private readonly FillFlowContainer content; public ScheduleContainer(string title) { Padding = new MarginPadding { Left = 60, Top = 10 }; InternalChildren = new Drawable[] { new FillFlowContainer { RelativeSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Children = new Drawable[] { new TournamentSpriteTextWithBackground(title.ToUpperInvariant()) { Scale = new Vector2(0.5f) }, content = new FillFlowContainer { Direction = FillDirection.Vertical, RelativeSizeAxes = Axes.Both, Margin = new MarginPadding(10) }, } }, }; } } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.14.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Google Apps Activity API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/google-apps/activity/'>Google Apps Activity API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20160129 (393) * <tr><th>API Docs * <td><a href='https://developers.google.com/google-apps/activity/'> * https://developers.google.com/google-apps/activity/</a> * <tr><th>Discovery Name<td>appsactivity * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Google Apps Activity API can be found at * <a href='https://developers.google.com/google-apps/activity/'>https://developers.google.com/google-apps/activity/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Appsactivity.v1 { /// <summary>The Appsactivity Service.</summary> public class AppsactivityService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public AppsactivityService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public AppsactivityService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { activities = new ActivitiesResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "appsactivity"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/appsactivity/v1/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "appsactivity/v1/"; } } /// <summary>Available OAuth 2.0 scopes for use with the Google Apps Activity API.</summary> public class Scope { /// <summary>View the activity history of your Google Apps</summary> public static string Activity = "https://www.googleapis.com/auth/activity"; /// <summary>View and manage the files in your Google Drive</summary> public static string Drive = "https://www.googleapis.com/auth/drive"; /// <summary>View and manage metadata of files in your Google Drive</summary> public static string DriveMetadata = "https://www.googleapis.com/auth/drive.metadata"; /// <summary>View metadata for files in your Google Drive</summary> public static string DriveMetadataReadonly = "https://www.googleapis.com/auth/drive.metadata.readonly"; /// <summary>View the files in your Google Drive</summary> public static string DriveReadonly = "https://www.googleapis.com/auth/drive.readonly"; } private readonly ActivitiesResource activities; /// <summary>Gets the Activities resource.</summary> public virtual ActivitiesResource Activities { get { return activities; } } } ///<summary>A base abstract class for Appsactivity requests.</summary> public abstract class AppsactivityBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new AppsactivityBaseServiceRequest instance.</summary> protected AppsactivityBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Appsactivity parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "activities" collection of methods.</summary> public class ActivitiesResource { private const string Resource = "activities"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ActivitiesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Returns a list of activities visible to the current logged in user. Visible activities are /// determined by the visiblity settings of the object that was acted on, e.g. Drive files a user can see. An /// activity is a record of past events. Multiple events may be merged if they are similar. A request is scoped /// to activities from a given Google service using the source parameter.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Returns a list of activities visible to the current logged in user. Visible activities are /// determined by the visiblity settings of the object that was acted on, e.g. Drive files a user can see. An /// activity is a record of past events. Multiple events may be merged if they are similar. A request is scoped /// to activities from a given Google service using the source parameter.</summary> public class ListRequest : AppsactivityBaseServiceRequest<Google.Apis.Appsactivity.v1.Data.ListActivitiesResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Identifies the Drive folder containing the items for which to return activities.</summary> [Google.Apis.Util.RequestParameterAttribute("drive.ancestorId", Google.Apis.Util.RequestParameterType.Query)] public virtual string DriveAncestorId { get; set; } /// <summary>Identifies the Drive item to return activities for.</summary> [Google.Apis.Util.RequestParameterAttribute("drive.fileId", Google.Apis.Util.RequestParameterType.Query)] public virtual string DriveFileId { get; set; } /// <summary>Indicates the strategy to use when grouping singleEvents items in the associated combinedEvent /// object.</summary> /// [default: driveUi] [Google.Apis.Util.RequestParameterAttribute("groupingStrategy", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<GroupingStrategyEnum> GroupingStrategy { get; set; } /// <summary>Indicates the strategy to use when grouping singleEvents items in the associated combinedEvent /// object.</summary> public enum GroupingStrategyEnum { [Google.Apis.Util.StringValueAttribute("driveUi")] DriveUi, [Google.Apis.Util.StringValueAttribute("none")] None, } /// <summary>The maximum number of events to return on a page. The response includes a continuation token if /// there are more events.</summary> /// [default: 50] [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>A token to retrieve a specific page of results.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>The Google service from which to return activities. Possible values of source are: - /// drive.google.com</summary> [Google.Apis.Util.RequestParameterAttribute("source", Google.Apis.Util.RequestParameterType.Query)] public virtual string Source { get; set; } /// <summary>Indicates the user to return activity for. Use the special value me to indicate the currently /// authenticated user.</summary> /// [default: me] [Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserId { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "activities"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "drive.ancestorId", new Google.Apis.Discovery.Parameter { Name = "drive.ancestorId", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "drive.fileId", new Google.Apis.Discovery.Parameter { Name = "drive.fileId", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "groupingStrategy", new Google.Apis.Discovery.Parameter { Name = "groupingStrategy", IsRequired = false, ParameterType = "query", DefaultValue = "driveUi", Pattern = null, }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = "50", Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "source", new Google.Apis.Discovery.Parameter { Name = "source", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userId", new Google.Apis.Discovery.Parameter { Name = "userId", IsRequired = false, ParameterType = "query", DefaultValue = "me", Pattern = null, }); } } } } namespace Google.Apis.Appsactivity.v1.Data { /// <summary>An Activity resource is a combined view of multiple events. An activity has a list of individual events /// and a combined view of the common fields among all events.</summary> public class Activity : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The fields common to all of the singleEvents that make up the Activity.</summary> [Newtonsoft.Json.JsonPropertyAttribute("combinedEvent")] public virtual Event CombinedEvent { get; set; } /// <summary>A list of all the Events that make up the Activity.</summary> [Newtonsoft.Json.JsonPropertyAttribute("singleEvents")] public virtual System.Collections.Generic.IList<Event> SingleEvents { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents the changes associated with an action taken by a user.</summary> public class Event : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Additional event types. Some events may have multiple types when multiple actions are part of a /// single event. For example, creating a document, renaming it, and sharing it may be part of a single file- /// creation event.</summary> [Newtonsoft.Json.JsonPropertyAttribute("additionalEventTypes")] public virtual System.Collections.Generic.IList<string> AdditionalEventTypes { get; set; } /// <summary>The time at which the event occurred formatted as Unix time in milliseconds.</summary> [Newtonsoft.Json.JsonPropertyAttribute("eventTimeMillis")] public virtual System.Nullable<ulong> EventTimeMillis { get; set; } /// <summary>Whether this event is caused by a user being deleted.</summary> [Newtonsoft.Json.JsonPropertyAttribute("fromUserDeletion")] public virtual System.Nullable<bool> FromUserDeletion { get; set; } /// <summary>Extra information for move type events, such as changes in an object's parents.</summary> [Newtonsoft.Json.JsonPropertyAttribute("move")] public virtual Move Move { get; set; } /// <summary>Extra information for permissionChange type events, such as the user or group the new permission /// applies to.</summary> [Newtonsoft.Json.JsonPropertyAttribute("permissionChanges")] public virtual System.Collections.Generic.IList<PermissionChange> PermissionChanges { get; set; } /// <summary>The main type of event that occurred.</summary> [Newtonsoft.Json.JsonPropertyAttribute("primaryEventType")] public virtual string PrimaryEventType { get; set; } /// <summary>Extra information for rename type events, such as the old and new names.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rename")] public virtual Rename Rename { get; set; } /// <summary>Information specific to the Target object modified by the event.</summary> [Newtonsoft.Json.JsonPropertyAttribute("target")] public virtual Target Target { get; set; } /// <summary>Represents the user responsible for the event.</summary> [Newtonsoft.Json.JsonPropertyAttribute("user")] public virtual User User { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The response from the list request. Contains a list of activities and a token to retrieve the next page /// of results.</summary> public class ListActivitiesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>List of activities.</summary> [Newtonsoft.Json.JsonPropertyAttribute("activities")] public virtual System.Collections.Generic.IList<Activity> Activities { get; set; } /// <summary>Token for the next page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Contains information about changes in an object's parents as a result of a move type event.</summary> public class Move : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The added parent(s).</summary> [Newtonsoft.Json.JsonPropertyAttribute("addedParents")] public virtual System.Collections.Generic.IList<Parent> AddedParents { get; set; } /// <summary>The removed parent(s).</summary> [Newtonsoft.Json.JsonPropertyAttribute("removedParents")] public virtual System.Collections.Generic.IList<Parent> RemovedParents { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Contains information about a parent object. For example, a folder in Drive is a parent for all files /// within it.</summary> public class Parent : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The parent's ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>Whether this is the root folder.</summary> [Newtonsoft.Json.JsonPropertyAttribute("isRoot")] public virtual System.Nullable<bool> IsRoot { get; set; } /// <summary>The parent's title.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Contains information about the permissions and type of access allowed with regards to a Google Drive /// object. This is a subset of the fields contained in a corresponding Drive Permissions object.</summary> public class Permission : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The name of the user or group the permission applies to.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The ID for this permission. Corresponds to the Drive API's permission ID returned as part of the /// Drive Permissions resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("permissionId")] public virtual string PermissionId { get; set; } /// <summary>Indicates the Google Drive permissions role. The role determines a user's ability to read, write, /// or comment on the file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("role")] public virtual string Role { get; set; } /// <summary>Indicates how widely permissions are granted.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The user's information if the type is USER.</summary> [Newtonsoft.Json.JsonPropertyAttribute("user")] public virtual User User { get; set; } /// <summary>Whether the permission requires a link to the file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("withLink")] public virtual System.Nullable<bool> WithLink { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Contains information about a Drive object's permissions that changed as a result of a permissionChange /// type event.</summary> public class PermissionChange : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Lists all Permission objects added.</summary> [Newtonsoft.Json.JsonPropertyAttribute("addedPermissions")] public virtual System.Collections.Generic.IList<Permission> AddedPermissions { get; set; } /// <summary>Lists all Permission objects removed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("removedPermissions")] public virtual System.Collections.Generic.IList<Permission> RemovedPermissions { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Photo information for a user.</summary> public class Photo : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The URL of the photo.</summary> [Newtonsoft.Json.JsonPropertyAttribute("url")] public virtual string Url { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Contains information about a renametype event.</summary> public class Rename : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The new title.</summary> [Newtonsoft.Json.JsonPropertyAttribute("newTitle")] public virtual string NewTitle { get; set; } /// <summary>The old title.</summary> [Newtonsoft.Json.JsonPropertyAttribute("oldTitle")] public virtual string OldTitle { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Information about the object modified by the event.</summary> public class Target : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ID of the target. For example, in Google Drive, this is the file or folder ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The MIME type of the target.</summary> [Newtonsoft.Json.JsonPropertyAttribute("mimeType")] public virtual string MimeType { get; set; } /// <summary>The name of the target. For example, in Google Drive, this is the title of the file.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A representation of a user.</summary> public class User : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A boolean which indicates whether the specified User was deleted. If true, name, photo and /// permission_id will be omitted.</summary> [Newtonsoft.Json.JsonPropertyAttribute("isDeleted")] public virtual System.Nullable<bool> IsDeleted { get; set; } /// <summary>The displayable name of the user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The permission ID associated with this user. Equivalent to the Drive API's permission ID for this /// user, returned as part of the Drive Permissions resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("permissionId")] public virtual string PermissionId { get; set; } /// <summary>The profile photo of the user. Not present if the user has no profile photo.</summary> [Newtonsoft.Json.JsonPropertyAttribute("photo")] public virtual Photo Photo { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// 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 gagr = Google.Api.Gax.ResourceNames; using gcmv = Google.Cloud.Memcache.V1; using sys = System; namespace Google.Cloud.Memcache.V1 { /// <summary>Resource name for the <c>Instance</c> resource.</summary> public sealed partial class InstanceName : gax::IResourceName, sys::IEquatable<InstanceName> { /// <summary>The possible contents of <see cref="InstanceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> ProjectLocationInstance = 1, } private static gax::PathTemplate s_projectLocationInstance = new gax::PathTemplate("projects/{project}/locations/{location}/instances/{instance}"); /// <summary>Creates a <see cref="InstanceName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="InstanceName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static InstanceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new InstanceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="InstanceName"/> with the pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="InstanceName"/> constructed from the provided ids.</returns> public static InstanceName FromProjectLocationInstance(string projectId, string locationId, string instanceId) => new InstanceName(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </returns> public static string Format(string projectId, string locationId, string instanceId) => FormatProjectLocationInstance(projectId, locationId, instanceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </returns> public static string FormatProjectLocationInstance(string projectId, string locationId, string instanceId) => s_projectLocationInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary>Parses the given resource name string into a new <see cref="InstanceName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The 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) => Parse(instanceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="InstanceName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName, bool allowUnparsed) => TryParse(instanceName, allowUnparsed, out InstanceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The 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 failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceName, out InstanceName result) => TryParse(instanceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceName, bool allowUnparsed, out InstanceName result) { gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName)); gax::TemplatedResourceName resourceName; if (s_projectLocationInstance.TryParseName(instanceName, out resourceName)) { result = FromProjectLocationInstance(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(instanceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private InstanceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; InstanceId = instanceId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="InstanceName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> public InstanceName(string projectId, string locationId, string instanceId) : this(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string InstanceId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationInstance: return s_projectLocationInstance.Expand(ProjectId, LocationId, InstanceId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as 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 Instance { /// <summary> /// <see cref="gcmv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListInstancesRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetInstanceRequest { /// <summary> /// <see cref="gcmv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateInstanceRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteInstanceRequest { /// <summary> /// <see cref="gcmv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ApplyParametersRequest { /// <summary> /// <see cref="gcmv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class UpdateParametersRequest { /// <summary> /// <see cref="gcmv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding; using System.Diagnostics; [AddComponentMenu ("Pathfinding/Seeker")] /** Handles path calls for a single unit. * \ingroup relevant * This is a component which is meant to be attached to a single unit (AI, Robot, Player, whatever) to handle it's pathfinding calls. * It also handles post-processing of paths using modifiers. * \see \ref calling-pathfinding */ public class Seeker : MonoBehaviour { //====== SETTINGS ====== /* Recalculate last queried path when a graph changes. \see AstarPath.OnGraphsUpdated */ //public bool recalcOnGraphChange = true; public bool drawGizmos = true; public bool detailedGizmos = false; /** Saves nearest nodes for previous path to enable faster Get Nearest Node calls. * This variable basically does not a affect anything at the moment. So it is hidden in the inspector */ [HideInInspector] public bool saveGetNearestHints = true; public StartEndModifier startEndModifier = new StartEndModifier (); [HideInInspector] public TagMask traversableTags = new TagMask (-1,-1); [HideInInspector] /** Penalties for each tag. * Tag 0 which is the default tag, will have added a penalty of tagPenalties[0]. * These should only be positive values since the A* algorithm cannot handle negative penalties. * \note This array should always have a length of 32. * \see Pathfinding.Path.tagPenalties */ public int[] tagPenalties = new int[32]; //====== SETTINGS ====== //public delegate Path PathReturn (Path p); /** Callback for when a path is completed. Movement scripts should register to this delegate.\n * A temporary callback can also be set when calling StartPath, but that delegate will only be called for that path */ public OnPathDelegate pathCallback; /** Called before pathfinding is started */ public OnPathDelegate preProcessPath; /** For anything which requires the original nodes (Node[]) (before modifiers) to work */ public OnPathDelegate postProcessOriginalPath; /** Anything which only modifies the positions (Vector3[]) */ public OnPathDelegate postProcessPath; //public GetNextTargetDelegate getNextTarget; //DEBUG //public Path lastCompletedPath; [System.NonSerialized] public List<Vector3> lastCompletedVectorPath; [System.NonSerialized] public List<GraphNode> lastCompletedNodePath; //END DEBUG /** The current path */ [System.NonSerialized] protected Path path; /** Previous path. Used to draw gizmos */ private Path prevPath; /** Returns #path */ public Path GetCurrentPath () { return path; } private GraphNode startHint; private GraphNode endHint; private OnPathDelegate onPathDelegate; /** Temporary callback only called for the current path. This value is set by the StartPath functions */ private OnPathDelegate tmpPathCallback; /** The path ID of the last path queried */ protected uint lastPathID = 0; /** Initializes a few variables */ public void Awake () { onPathDelegate = OnPathComplete; startEndModifier.Awake (this); } /** Cleans up some variables. * Releases any eventually claimed paths. * Calls OnDestroy on the #startEndModifier. * * \see ReleaseClaimedPath * \see startEndModifier */ public void OnDestroy () { ReleaseClaimedPath (); startEndModifier.OnDestroy (this); } /** Releases an eventual claimed path. * The seeker keeps the latest path claimed so it can draw gizmos. * In some cases this might not be desireable and you want it released. * In that case, you can call this method to release it (not that path gizmos will then not be drawn). * * If you didn't understand anything from the description above, you probably don't need to use this method. */ public void ReleaseClaimedPath () { if (prevPath != null) { prevPath.ReleaseSilent (this); prevPath = null; } } private List<IPathModifier> modifiers = new List<IPathModifier> (); public void RegisterModifier (IPathModifier mod) { if (modifiers == null) { modifiers = new List<IPathModifier> (1); } modifiers.Add (mod); } public void DeregisterModifier (IPathModifier mod) { if (modifiers == null) { return; } modifiers.Remove (mod); } public enum ModifierPass { PreProcess, PostProcessOriginal, PostProcess } /** Post Processes the path. * This will run any modifiers attached to this GameObject on the path. * This is identical to calling RunModifiers(ModifierPass.PostProcess, path) * \see RunModifiers * \since Added in 3.2 */ public void PostProcess (Path p) { RunModifiers (ModifierPass.PostProcess,p); } /** Runs modifiers on path \a p */ public void RunModifiers (ModifierPass pass, Path p) { //Sort the modifiers based on priority (bubble sort (slow but since it's a small list, it works good)) bool changed = true; while (changed) { changed = false; for (int i=0;i<modifiers.Count-1;i++) { if (modifiers[i].Priority < modifiers[i+1].Priority) { IPathModifier tmp = modifiers[i]; modifiers[i] = modifiers[i+1]; modifiers[i+1] = tmp; changed = true; } } } //Call eventual delegates switch (pass) { case ModifierPass.PreProcess: if (preProcessPath != null) preProcessPath (p); break; case ModifierPass.PostProcessOriginal: if (postProcessOriginalPath != null) postProcessOriginalPath (p); break; case ModifierPass.PostProcess: if (postProcessPath != null) postProcessPath (p); break; } //No modifiers, then exit here if (modifiers.Count == 0) return; ModifierData prevOutput = ModifierData.All; IPathModifier prevMod = modifiers[0]; //Loop through all modifiers and apply post processing for (int i=0;i<modifiers.Count;i++) { //Cast to MonoModifier, i.e modifiers attached as scripts to the game object MonoModifier mMod = modifiers[i] as MonoModifier; //Ignore modifiers which are not enabled if (mMod != null && !mMod.enabled) continue; switch (pass) { case ModifierPass.PreProcess: modifiers[i].PreProcess (p); break; case ModifierPass.PostProcessOriginal: modifiers[i].ApplyOriginal (p); break; case ModifierPass.PostProcess: //Convert the path if necessary to match the required input for the modifier ModifierData newInput = ModifierConverter.Convert (p,prevOutput,modifiers[i].input); if (newInput != ModifierData.None) { modifiers[i].Apply (p,newInput); prevOutput = modifiers[i].output; } else { UnityEngine.Debug.Log ("Error converting "+(i > 0 ? prevMod.GetType ().Name : "original")+"'s output to "+(modifiers[i].GetType ().Name)+"'s input.\nTry rearranging the modifier priorities on the Seeker."); prevOutput = ModifierData.None; } prevMod = modifiers[i]; break; } if (prevOutput == ModifierData.None) { break; } } } /** Is the current path done calculating. * Returns true if the current #path has been returned or if the #path is null. * * \note Do not confuse this with Pathfinding.Path.IsDone. They do mostly return the same value, but not always. * * \since Added in 3.0.8 * \version Behaviour changed in 3.2 * */ public bool IsDone () { return path == null || path.GetState() >= PathState.Returned; } /** Called when a path has completed. * This should have been implemented as optional parameter values, but that didn't seem to work very well with delegates (the values weren't the default ones) * \see OnPathComplete(Path,bool,bool) */ public void OnPathComplete (Path p) { OnPathComplete (p,true,true); } /** Called when a path has completed. * Will post process it and return it by calling #tmpPathCallback and #pathCallback */ public void OnPathComplete (Path p, bool runModifiers, bool sendCallbacks) { AstarProfiler.StartProfile ("Seeker OnPathComplete"); if (p != null && p != path && sendCallbacks) { return; } if (this == null || p == null || p != path) return; if (!path.error && runModifiers) { AstarProfiler.StartProfile ("Seeker Modifiers"); //This will send the path for post processing to modifiers attached to this Seeker RunModifiers (ModifierPass.PostProcessOriginal, path); //This will send the path for post processing to modifiers attached to this Seeker RunModifiers (ModifierPass.PostProcess, path); AstarProfiler.EndProfile (); } if (sendCallbacks) { p.Claim (this); AstarProfiler.StartProfile ("Seeker Callbacks"); lastCompletedNodePath = p.path; lastCompletedVectorPath = p.vectorPath; //This will send the path to the callback (if any) specified when calling StartPath if (tmpPathCallback != null) { tmpPathCallback (p); } //This will send the path to any script which has registered to the callback if (pathCallback != null) { pathCallback (p); } //Recycle the previous path if (prevPath != null) { prevPath.ReleaseSilent (this); } prevPath = p; //If not drawing gizmos, then storing prevPath is quite unecessary //So clear it and set prevPath to null if (!drawGizmos) ReleaseClaimedPath (); AstarProfiler.EndProfile(); } AstarProfiler.EndProfile (); } /*public void OnEnable () { //AstarPath.OnGraphsUpdated += CheckPathValidity; } public void OnDisable () { //AstarPath.OnGraphsUpdated -= CheckPathValidity; }*/ /*public void CheckPathValidity (AstarPath active) { /*if (!recalcOnGraphChange) { return; } //Debug.Log ("Checking Path Validity"); //Debug.Break (); if (lastCompletedPath != null && !lastCompletedPath.error) { //Debug.Log ("Checking Path Validity"); StartPath (transform.position,lastCompletedPath.endPoint); /*if (!lastCompletedPath.path[0].IsWalkable (lastCompletedPath)) { StartPath (transform.position,lastCompletedPath.endPoint); return; } for (int i=0;i<lastCompletedPath.path.Length-1;i++) { if (!lastCompletedPath.path[i].ContainsConnection (lastCompletedPath.path[i+1],lastCompletedPath)) { StartPath (transform.position,lastCompletedPath.endPoint); return; } Debug.DrawLine (lastCompletedPath.path[i].position,lastCompletedPath.path[i+1].position,Color.cyan); }* }* }*/ //The frame the last call was made from this Seeker //private int lastPathCall = -1000; /** Returns a new path instance. The path will be taken from the path pool if path recycling is turned on.\n * This path can be sent to #StartPath(Path,OnPathDelegate,int) with no change, but if no change is required #StartPath(Vector3,Vector3,OnPathDelegate) does just that. * \code Seeker seeker = GetComponent (typeof(Seeker)) as Seeker; * Path p = seeker.GetNewPath (transform.position, transform.position+transform.forward*100); * p.nnConstraint = NNConstraint.Default; \endcode */ public ABPath GetNewPath (Vector3 start, Vector3 end) { //Construct a path with start and end points ABPath p = ABPath.Construct (start, end, null); return p; } /** Call this function to start calculating a path. * \param start The start point of the path * \param end The end point of the path */ public Path StartPath (Vector3 start, Vector3 end) { return StartPath (start,end,null,-1); } /** Call this function to start calculating a path. * \param start The start point of the path * \param end The end point of the path * \param callback The function to call when the path has been calculated * * \a callback will be called when the path has completed. * \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */ public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback) { return StartPath (start,end,callback,-1); } /** Call this function to start calculating a path. * \param start The start point of the path * \param end The end point of the path * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. * * \a callback will be called when the path has completed. * \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */ public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback, int graphMask) { Path p = GetNewPath (start,end); return StartPath (p, callback, graphMask); } /** Call this function to start calculating a path. * \param p The path to start calculating * \param callback The function to call when the path has been calculated * \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask. \astarproParam * * \a callback will be called when the path has completed. * \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */ public Path StartPath (Path p, OnPathDelegate callback = null, int graphMask = -1) { p.enabledTags = traversableTags.tagsChange; p.tagPenalties = tagPenalties; //Cancel a previously requested path is it has not been processed yet and also make sure that it has not been recycled and used somewhere else if (path != null && path.GetState() <= PathState.Processing && lastPathID == path.pathID) { path.Error(); path.LogError ("Canceled path because a new one was requested.\n"+ "This happens when a new path is requested from the seeker when one was already being calculated.\n" + "For example if a unit got a new order, you might request a new path directly instead of waiting for the now" + " invalid path to be calculated. Which is probably what you want.\n" + "If you are getting this a lot, you might want to consider how you are scheduling path requests."); //No callback should be sent for the canceled path } path = p; path.callback += onPathDelegate; tmpPathCallback = callback; //Set the Get Nearest Node hints if they have not already been set /*if (path.startHint == null) path.startHint = startHint; if (path.endHint == null) path.endHint = endHint; */ //Save the path id so we can make sure that if we cancel a path (see above) it should not have been recycled yet. lastPathID = path.pathID; //Delay the path call by one frame if it was sent the same frame as the previous call /*if (lastPathCall == Time.frameCount) { StartCoroutine (DelayPathStart (path)); return path; }*/ //lastPathCall = Time.frameCount; //Pre process the path RunModifiers (ModifierPass.PreProcess, path); //Send the request to the pathfinder AstarPath.StartPath (path); return path; } public IEnumerator DelayPathStart (Path p) { yield return null; //lastPathCall = Time.frameCount; RunModifiers (ModifierPass.PreProcess, p); AstarPath.StartPath (p); } public void OnDrawGizmos () { if (lastCompletedNodePath == null || !drawGizmos) { return; } if (detailedGizmos) { Gizmos.color = new Color (0.7F,0.5F,0.1F,0.5F); if (lastCompletedNodePath != null) { for (int i=0;i<lastCompletedNodePath.Count-1;i++) { Gizmos.DrawLine ((Vector3)lastCompletedNodePath[i].position,(Vector3)lastCompletedNodePath[i+1].position); } } } Gizmos.color = new Color (0,1F,0,1F); if (lastCompletedVectorPath != null) { for (int i=0;i<lastCompletedVectorPath.Count-1;i++) { Gizmos.DrawLine (lastCompletedVectorPath[i],lastCompletedVectorPath[i+1]); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.ComponentModel.DataAnnotations { public partial class AssociatedMetadataTypeTypeDescriptionProvider : System.ComponentModel.TypeDescriptionProvider { public AssociatedMetadataTypeTypeDescriptionProvider(System.Type type) { } public AssociatedMetadataTypeTypeDescriptionProvider(System.Type type, System.Type associatedMetadataType) { } public override System.ComponentModel.ICustomTypeDescriptor GetTypeDescriptor(System.Type objectType, object instance) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] [System.ObsoleteAttribute("This attribute is no longer in use and will be ignored if applied.")] public sealed partial class AssociationAttribute : System.Attribute { public AssociationAttribute(string name, string thisKey, string otherKey) { } public bool IsForeignKey { get { throw null; } set { } } public string Name { get { throw null; } } public string OtherKey { get { throw null; } } public System.Collections.Generic.IEnumerable<string> OtherKeyMembers { get { throw null; } } public string ThisKey { get { throw null; } } public System.Collections.Generic.IEnumerable<string> ThisKeyMembers { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false)] public partial class CompareAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public CompareAttribute(string otherProperty) { } public string OtherProperty { get { throw null; } } public string OtherPropertyDisplayName { get { throw null; } } public override bool RequiresValidationContext { get { throw null; } } public override string FormatErrorMessage(string name) { throw null; } protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public sealed partial class ConcurrencyCheckAttribute : System.Attribute { public ConcurrencyCheckAttribute() { } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class CreditCardAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public CreditCardAttribute() : base (default(System.ComponentModel.DataAnnotations.DataType)) { } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=true)] public sealed partial class CustomValidationAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public CustomValidationAttribute(System.Type validatorType, string method) { } public string Method { get { throw null; } } public System.Type ValidatorType { get { throw null; } } public override string FormatErrorMessage(string name) { throw null; } protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; } } public enum DataType { CreditCard = 14, Currency = 6, Custom = 0, Date = 2, DateTime = 1, Duration = 4, EmailAddress = 10, Html = 8, ImageUrl = 13, MultilineText = 9, Password = 11, PhoneNumber = 5, PostalCode = 15, Text = 7, Time = 3, Upload = 16, Url = 12, } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class DataTypeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public DataTypeAttribute(System.ComponentModel.DataAnnotations.DataType dataType) { } public DataTypeAttribute(string customDataType) { } public string CustomDataType { get { throw null; } } public System.ComponentModel.DataAnnotations.DataType DataType { get { throw null; } } public System.ComponentModel.DataAnnotations.DisplayFormatAttribute DisplayFormat { get { throw null; } protected set { } } public virtual string GetDataTypeName() { throw null; } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class DisplayAttribute : System.Attribute { public DisplayAttribute() { } public bool AutoGenerateField { get { throw null; } set { } } public bool AutoGenerateFilter { get { throw null; } set { } } public string Description { get { throw null; } set { } } public string GroupName { get { throw null; } set { } } public string Name { get { throw null; } set { } } public int Order { get { throw null; } set { } } public string Prompt { get { throw null; } set { } } public System.Type ResourceType { get { throw null; } set { } } public string ShortName { get { throw null; } set { } } public bool? GetAutoGenerateField() { throw null; } public bool? GetAutoGenerateFilter() { throw null; } public string GetDescription() { throw null; } public string GetGroupName() { throw null; } public string GetName() { throw null; } public int? GetOrder() { throw null; } public string GetPrompt() { throw null; } public string GetShortName() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true, AllowMultiple=false)] public partial class DisplayColumnAttribute : System.Attribute { public DisplayColumnAttribute(string displayColumn) { } public DisplayColumnAttribute(string displayColumn, string sortColumn) { } public DisplayColumnAttribute(string displayColumn, string sortColumn, bool sortDescending) { } public string DisplayColumn { get { throw null; } } public string SortColumn { get { throw null; } } public bool SortDescending { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class DisplayFormatAttribute : System.Attribute { public DisplayFormatAttribute() { } public bool ApplyFormatInEditMode { get { throw null; } set { } } public bool ConvertEmptyStringToNull { get { throw null; } set { } } public string DataFormatString { get { throw null; } set { } } public bool HtmlEncode { get { throw null; } set { } } public string NullDisplayText { get { throw null; } set { } } public System.Type NullDisplayTextResourceType { get { throw null; } set { } } public string GetNullDisplayText() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public sealed partial class EditableAttribute : System.Attribute { public EditableAttribute(bool allowEdit) { } public bool AllowEdit { get { throw null; } } public bool AllowInitialValue { get { throw null; } set { } } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class EmailAddressAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public EmailAddressAttribute() : base (default(System.ComponentModel.DataAnnotations.DataType)) { } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class EnumDataTypeAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public EnumDataTypeAttribute(System.Type enumType) : base (default(System.ComponentModel.DataAnnotations.DataType)) { } public System.Type EnumType { get { throw null; } } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class FileExtensionsAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public FileExtensionsAttribute() : base (default(System.ComponentModel.DataAnnotations.DataType)) { } public string Extensions { get { throw null; } set { } } public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] [System.ObsoleteAttribute("This attribute is no longer in use and will be ignored if applied.")] public sealed partial class FilterUIHintAttribute : System.Attribute { public FilterUIHintAttribute(string filterUIHint) { } public FilterUIHintAttribute(string filterUIHint, string presentationLayer) { } public FilterUIHintAttribute(string filterUIHint, string presentationLayer, params object[] controlParameters) { } public System.Collections.Generic.IDictionary<string, object> ControlParameters { get { throw null; } } public string FilterUIHint { get { throw null; } } public string PresentationLayer { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } } public partial interface IValidatableObject { System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext); } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public sealed partial class KeyAttribute : System.Attribute { public KeyAttribute() { } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class MaxLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public MaxLengthAttribute() { } public MaxLengthAttribute(int length) { } public int Length { get { throw null; } } public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public sealed partial class MetadataTypeAttribute : System.Attribute { public MetadataTypeAttribute(System.Type metadataClassType) { } public System.Type MetadataClassType { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class MinLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public MinLengthAttribute(int length) { } public int Length { get { throw null; } } public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class PhoneAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public PhoneAttribute() : base (default(System.ComponentModel.DataAnnotations.DataType)) { } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class RangeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public RangeAttribute(double minimum, double maximum) { } public RangeAttribute(int minimum, int maximum) { } public RangeAttribute(System.Type type, string minimum, string maximum) { } public bool ConvertValueInInvariantCulture { get { throw null; } set { } } public object Maximum { get { throw null; } } public object Minimum { get { throw null; } } public System.Type OperandType { get { throw null; } } public bool ParseLimitsInInvariantCulture { get { throw null; } set { } } public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public RegularExpressionAttribute(string pattern) { } public int MatchTimeoutInMilliseconds { get { throw null; } set { } } public string Pattern { get { throw null; } } public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class RequiredAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public RequiredAttribute() { } public bool AllowEmptyStrings { get { throw null; } set { } } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class ScaffoldColumnAttribute : System.Attribute { public ScaffoldColumnAttribute(bool scaffold) { } public bool Scaffold { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public partial class StringLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute { public StringLengthAttribute(int maximumLength) { } public int MaximumLength { get { throw null; } } public int MinimumLength { get { throw null; } set { } } public override string FormatErrorMessage(string name) { throw null; } public override bool IsValid(object value) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public sealed partial class TimestampAttribute : System.Attribute { public TimestampAttribute() { } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=true)] public partial class UIHintAttribute : System.Attribute { public UIHintAttribute(string uiHint) { } public UIHintAttribute(string uiHint, string presentationLayer) { } public UIHintAttribute(string uiHint, string presentationLayer, params object[] controlParameters) { } public System.Collections.Generic.IDictionary<string, object> ControlParameters { get { throw null; } } public string PresentationLayer { get { throw null; } } public string UIHint { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)] public sealed partial class UrlAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { public UrlAttribute() : base (default(System.ComponentModel.DataAnnotations.DataType)) { } public override bool IsValid(object value) { throw null; } } public abstract partial class ValidationAttribute : System.Attribute { protected ValidationAttribute() { } protected ValidationAttribute(System.Func<string> errorMessageAccessor) { } protected ValidationAttribute(string errorMessage) { } public string ErrorMessage { get { throw null; } set { } } public string ErrorMessageResourceName { get { throw null; } set { } } public System.Type ErrorMessageResourceType { get { throw null; } set { } } protected string ErrorMessageString { get { throw null; } } public virtual bool RequiresValidationContext { get { throw null; } } public virtual string FormatErrorMessage(string name) { throw null; } public System.ComponentModel.DataAnnotations.ValidationResult GetValidationResult(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; } public virtual bool IsValid(object value) { throw null; } protected virtual System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; } public void Validate(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { } public void Validate(object value, string name) { } } public sealed partial class ValidationContext : System.IServiceProvider { public ValidationContext(object instance) { } public ValidationContext(object instance, System.Collections.Generic.IDictionary<object, object> items) { } public ValidationContext(object instance, System.IServiceProvider serviceProvider, System.Collections.Generic.IDictionary<object, object> items) { } public string DisplayName { get { throw null; } set { } } public System.Collections.Generic.IDictionary<object, object> Items { get { throw null; } } public string MemberName { get { throw null; } set { } } public object ObjectInstance { get { throw null; } } public System.Type ObjectType { get { throw null; } } public object GetService(System.Type serviceType) { throw null; } public void InitializeServiceProvider(System.Func<System.Type, object> serviceProvider) { } } public partial class ValidationException : System.Exception { public ValidationException() { } public ValidationException(System.ComponentModel.DataAnnotations.ValidationResult validationResult, System.ComponentModel.DataAnnotations.ValidationAttribute validatingAttribute, object value) { } protected ValidationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public ValidationException(string message) { } public ValidationException(string errorMessage, System.ComponentModel.DataAnnotations.ValidationAttribute validatingAttribute, object value) { } public ValidationException(string message, System.Exception innerException) { } public System.ComponentModel.DataAnnotations.ValidationAttribute ValidationAttribute { get { throw null; } } public System.ComponentModel.DataAnnotations.ValidationResult ValidationResult { get { throw null; } } public object Value { get { throw null; } } } public partial class ValidationResult { public static readonly System.ComponentModel.DataAnnotations.ValidationResult Success; protected ValidationResult(System.ComponentModel.DataAnnotations.ValidationResult validationResult) { } public ValidationResult(string errorMessage) { } public ValidationResult(string errorMessage, System.Collections.Generic.IEnumerable<string> memberNames) { } public string ErrorMessage { get { throw null; } set { } } public System.Collections.Generic.IEnumerable<string> MemberNames { get { throw null; } } public override string ToString() { throw null; } } public static partial class Validator { public static bool TryValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults) { throw null; } public static bool TryValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults, bool validateAllProperties) { throw null; } public static bool TryValidateProperty(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults) { throw null; } public static bool TryValidateValue(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults, System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationAttribute> validationAttributes) { throw null; } public static void ValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { } public static void ValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, bool validateAllProperties) { } public static void ValidateProperty(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { } public static void ValidateValue(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationAttribute> validationAttributes) { } } } namespace System.ComponentModel.DataAnnotations.Schema { [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class ColumnAttribute : System.Attribute { public ColumnAttribute() { } public ColumnAttribute(string name) { } public string Name { get { throw null; } } public int Order { get { throw null; } set { } } public string TypeName { get { throw null; } set { } } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public partial class ComplexTypeAttribute : System.Attribute { public ComplexTypeAttribute() { } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class DatabaseGeneratedAttribute : System.Attribute { public DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption databaseGeneratedOption) { } public System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption DatabaseGeneratedOption { get { throw null; } } } public enum DatabaseGeneratedOption { Computed = 2, Identity = 1, None = 0, } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class ForeignKeyAttribute : System.Attribute { public ForeignKeyAttribute(string name) { } public string Name { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class InversePropertyAttribute : System.Attribute { public InversePropertyAttribute(string property) { } public string Property { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)] public partial class NotMappedAttribute : System.Attribute { public NotMappedAttribute() { } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false)] public partial class TableAttribute : System.Attribute { public TableAttribute(string name) { } public string Name { get { throw null; } } public string Schema { get { throw null; } set { } } } }
using System; using CoreGraphics; using System.Threading; using System.Threading.Tasks; using UIKit; using Toggl.Phoebe.Data; using Toggl.Phoebe.Data.Reports; using Toggl.Ross.Views.Charting; namespace Toggl.Ross.Views { public sealed class ReportView : UIView { public event EventHandler LoadStart; public event EventHandler LoadFinished; public ZoomLevel ZoomLevel { get; set; } public int TimeSpaceIndex { get; set; } public bool IsClean { get; set; } public bool IsError { get { return dataSource != null && dataSource.IsError; } } private bool _loading; public bool IsLoading { get { return _loading; } private set { if (_loading == value) { return; } _loading = value; if (_loading) { if (LoadStart != null) { LoadStart.Invoke (this, new EventArgs ()); } } else { if (LoadFinished != null) { LoadFinished.Invoke (this, new EventArgs ()); } } } } private ChartPosition _position; public ChartPosition Position { get { return _position; } set { if (_position == value) { return; } _position = value; var posY = ( _position == ChartPosition.Top) ? topY : downY; _containerView.Center = new CGPoint (_containerView.Center.X, posY); } } private bool _isDragging; public bool Dragging { get { return _isDragging; } } private bool _scrollEnabled; public bool ScrollEnabled { set { _scrollEnabled = value; if (panGesture != null) { panGesture.Enabled = _scrollEnabled; } } } public ReportView () { InitView(); } public ReportView ( CGRect frame) : base ( frame) { InitView(); } private void InitView() { ClipsToBounds = true; BackgroundColor = UIColor.White; barChart = new BarChartView (); pieChart = new DonutChartView (); _containerView = new UIView (); _containerView.Add (barChart); _containerView.Add (pieChart); AddSubview (_containerView); IsClean = true; panGesture = CreatePanGesture (); _containerView.AddGestureRecognizer (panGesture); _position = ChartPosition.Top; } UIPanGestureRecognizer panGesture; private UIView _containerView; private DonutChartView pieChart; private BarChartView barChart; private SummaryReportView dataSource; private nfloat topY; private nfloat downY; private CancellationTokenSource cts; private bool _delaying; static readonly nfloat padding = 30; static readonly nfloat navBarHeight = 64; static readonly nfloat selectorHeight = 60; public override void LayoutSubviews () { base.LayoutSubviews (); _containerView.Bounds = new CGRect ( 0, 0, Bounds.Width, Bounds.Height * 2); barChart.Frame = new CGRect ( padding/2, padding/2, Bounds.Width - padding, Bounds.Height - padding - selectorHeight ); pieChart.Frame = new CGRect (padding/2, barChart.Bounds.Height + padding, Bounds.Width - padding, Bounds.Height); topY = _containerView.Bounds.Height/2; downY = _containerView.Bounds.Height/2 - (barChart.Bounds.Height + padding); var posY = ( _position == ChartPosition.Top) ? topY : downY; _containerView.Center = new CGPoint ( Bounds.Width/2, posY); } public async void LoadData() { if ( IsClean) { try { IsLoading = true; dataSource = new SummaryReportView (); dataSource.Period = ZoomLevel; _delaying = true; cts = new CancellationTokenSource (); await Task.Delay (500, cts.Token); _delaying = false; await dataSource.Load (TimeSpaceIndex); if ( !dataSource.IsLoading) { barChart.ReportView = dataSource; pieChart.ReportView = dataSource; } IsClean = IsError; // Declare ReportView as clean if an error occurs.. } catch (Exception ex) { IsClean = true; } finally { IsLoading = false; _delaying = false; cts.Dispose (); } } } public void StopReloadData() { if (IsLoading) { if (_delaying) { cts.Cancel (); } dataSource.CancelLoad (); } } protected override void Dispose (bool disposing) { barChart.Dispose (); pieChart.Dispose (); base.Dispose (disposing); } public enum ChartPosition { Top = 0, Down = 1 } private UIPanGestureRecognizer CreatePanGesture() { UIPanGestureRecognizer result = null; nfloat dy = 0; nfloat navX = 70; result = new UIPanGestureRecognizer (() => { if ((result.State == UIGestureRecognizerState.Began || result.State == UIGestureRecognizerState.Changed) && (result.NumberOfTouches == 1)) { _isDragging = true; var p0 = result.LocationInView (this); var currentY = (_position == ChartPosition.Top) ? topY : downY; if (dy.CompareTo (0) == 0) { dy = p0.Y - currentY; } var p1 = new CGPoint ( _containerView.Center.X, p0.Y - dy); if ( p1.Y > topY || p1.Y < downY) { return; } _containerView.Center = p1; } else if (result.State == UIGestureRecognizerState.Ended) { nfloat newY; ChartPosition newPosition; if ( _position == ChartPosition.Top && _containerView.Center.Y <= topY - navX) { newPosition = ChartPosition.Down; newY = downY; } else if ( _position == ChartPosition.Down && _containerView.Center.Y >= downY + navX) { newPosition = ChartPosition.Top; newY = topY; } else { newPosition = _position; newY = (_position == ChartPosition.Top) ? topY : downY; } UIView.Animate (0.3, 0, UIViewAnimationOptions.CurveEaseOut, () => { _containerView.Center = new CGPoint ( _containerView.Center.X, newY); },() => { _isDragging = false; _position = newPosition; }); dy = 0; } }); return result; } } }
using System; namespace zadania_labki_23_listopada { class Tablica3W { private int[,,] data; private Random random; public Tablica3W(int p=1, int r=1, int c=1) { this.random=new Random(); this.data=new int[p,r,c]; this.initialize(); } private void initialize () { for (int i=0; i<this.data.GetLength(0); i++) { for(int j=0; j<this.data.GetLength(1); j++) { for(int k=0; k<this.data.GetLength(2); k++) { this.data[i,j,k]=random.Next(1,30); } } } } public void render (bool verbose=false) { for (int i=0; i<this.data.GetLength(0); i++) { if(verbose) Console.WriteLine("Page: "+i); for(int j=0; j<this.data.GetLength(1); j++) { for(int k=0; k<this.data.GetLength(2); k++) { Console.Write (this.data[i,j,k]+"\t"); } Console.WriteLine(); } Console.WriteLine(); } } } class Tablica3Wa { private Random random; private int[][][] data; public Tablica3Wa (int p=1, int r=1, int c=1) { this.random=new Random(); this.initialize(p, r, c); } private void initialize (int p=1, int r=1, int c=1) { this.data = new int[p][][]; for (int i=0; i<p; i++) { this.data[i]=new int[r][]; for(int j=0; j<r; j++) { this.data[i][j]=new int[c]; for(int k=0; k<c; k++) { this.data[i][j][k]=this.random.Next(1,30); } } } } public void render (bool verbose=false) { for (int i=0; i<this.data.GetLength(0); i++) { if(verbose) Console.WriteLine("Page: "+i); for(int j=0; j<this.data[i].GetLength(0); j++) { for(int k=0; k<this.data[i][j].GetLength(0); k++) { Console.Write(this.data[i][j][k]+"\t"); } Console.WriteLine(); } Console.WriteLine(); } } } class Complex { /* get, set Im, Re, dodawanie, odejmowanie, dzielenie, mozenie, modul, faza w stopniach */ private double Re, Im; public Complex () { this.Re=0; this.Im=0; } public Complex setRe (double _Re) { this.Re=_Re; return this; } public Complex setIm (double _Im) { this.Im=_Im; return this; } public double getRe () { return this.Re; } public double getIm () { return this.Im; } public void print() { if(this.Im>0) Console.WriteLine(this.Re+"+"+this.Im+"i"); else Console.WriteLine(this.Re+""+this.Im+"i"); } public double getModulus () { return Math.Sqrt ((this.Re*this.Re)+(this.Im*this.Im)); } public double getPhase () { if (this.Re > 0) return Math.Atan(this.Im/this.Re); else if (this.Re < 0) return Math.Atan(this.Im/this.Re)+Math.PI; return 0; } public Complex add (Complex c1) { Complex temp=new Complex(); temp.setRe (this.Re+c1.getRe()); temp.setIm (this.Im+c1.getIm()); return temp; } public Complex substract (Complex c1) { Complex temp=new Complex(); temp.setRe (this.Re-c1.getRe()); temp.setIm (this.Im-c1.getIm()); return temp; } public Complex mulitiply (Complex c1) { Complex temp=new Complex(); temp.setRe((this.Re*c1.getRe())-(this.Im*c1.getIm())).setIm((this.Re*c1.getIm())+(this.Re*c1.getRe())); return temp; } public Complex divide (Complex c1) { Complex temp=new Complex(); double divider=c1.getRe()*c1.getRe()*c1.getIm()*c1.getIm(); temp.setRe(((this.Re*c1.getRe())+(this.Im*c1.getIm()))/divider); temp.setIm(((this.Im*c1.getRe())+(this.Re*c1.getIm()))/divider); return temp; } } class MainClass { public static void Main (string[] args) { Complex liczba= new Complex(); Complex liczba2= new Complex(); Complex liczba3; liczba.setRe(10).setIm(2); liczba2.setRe(5).setIm(4); liczba3=liczba.add(liczba2); liczba3.print(); liczba3=liczba.substract(liczba2); liczba3.print(); liczba3=liczba.mulitiply(liczba2); liczba3.print(); liczba3=liczba.divide(liczba2); liczba3.print(); Console.WriteLine(liczba3.getModulus()); Console.WriteLine(liczba3.getPhase()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // The implementation for a bijection map using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { [ContractVerification(true)] public sealed class BijectiveMap<TKey, TValue> : IDictionary<TKey, TValue> { #region Object Invariant [Pure] public bool IsConsistent() { if (directMap.Count != inverseMap.Count) return false; foreach (var key in this.DirectMap.Keys) { if (!this.InverseMap.ContainsKey(this.DirectMap[key])) return false; } foreach (var key in this.InverseMap.Keys) { if (!this.DirectMap.ContainsKey(this.InverseMap[key])) return false; } return true; } [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(inverseMap != null); Contract.Invariant(directMap != null); //Contract.Invariant(this.IsConsistent()); } #endregion #region Private state private Dictionary<TKey, TValue> directMap; // The direct map private Dictionary<TValue, TKey> inverseMap; // The inverse map #endregion #region Constructors /// <summary> /// Construct a Bijective Map of default size /// </summary> public BijectiveMap() { directMap = new Dictionary<TKey, TValue>(); inverseMap = new Dictionary<TValue, TKey>(); } /// <summary> /// Construct a Bijective Map of size <code>n</code> /// </summary> public BijectiveMap(int size) { Contract.Requires(size >= 0); directMap = new Dictionary<TKey, TValue>(size); inverseMap = new Dictionary<TValue, TKey>(size); } /// <summary> /// Copy constructor /// </summary> public BijectiveMap(BijectiveMap<TKey, TValue> toClone) { Contract.Requires(toClone != null); directMap = new Dictionary<TKey, TValue>(toClone.DirectMap); inverseMap = new Dictionary<TValue, TKey>(toClone.InverseMap); } #endregion #region IBijectiveMap<TKey,TValue> Members /// <returns>The key associated with <code>value</code></returns> public TKey KeyForValue(TValue value) { return inverseMap[value]; } /// <returns> /// <code>true</code> iff the co-domain of the map contains the value <code>value</code> /// </returns> public bool ContainsValue(TValue value) { return inverseMap.ContainsKey(value); } /// <summary> /// Get the direct map /// </summary> public Dictionary<TKey, TValue> DirectMap { get { Contract.Ensures(Contract.Result<Dictionary<TKey, TValue>>() != null); return directMap; } } /// <summary> /// Get the inverse map /// </summary> public Dictionary<TValue, TKey> InverseMap { get { Contract.Ensures(Contract.Result<Dictionary<TValue, TKey>>() != null); return inverseMap; } } public BijectiveMap<TKey, TValue> Duplicate() { var result = new BijectiveMap<TKey, TValue>(); foreach (var pair in directMap) { result[pair.Key] = pair.Value; } return result; } #endregion #region IDictionary<TKey,TValue> Members /// <summary> /// Add the pair <code>(key, value)</code> to the map /// </summary> public void Add(TKey key, TValue value) { directMap.Add(key, value); if (!inverseMap.ContainsKey(value)) inverseMap.Add(value, key); } /// <returns><code>true</code> iff <code>key</code> is in the map</returns> public bool ContainsKey(TKey key) { return directMap.ContainsKey(key); } /// <summary> /// Gets the keys in this map /// </summary> public ICollection<TKey> Keys { get { return directMap.Keys; } } /// <summary> /// Remove the entry corresponding to <code>key</code> /// </summary> /// <returns>true if the element is successfully removed; otherwise, false. This method also returns false if key was not found in the IDictionary</returns> // [SuppressMessage("Microsoft.Contracts", "Ensures-31-220")] // It seems we can prove it now public bool Remove(TKey key) { Contract.Ensures(!Contract.Result<bool>() || this.Count == Contract.OldValue(this.Count) - 1); TValue valForKey = directMap[key]; bool bDirect = directMap.Remove(key); bool bInverse = inverseMap[valForKey].Equals(key) ? inverseMap.Remove(valForKey) : false; if (bInverse) { foreach (TKey otherKey in directMap.Keys) { if (directMap[otherKey].Equals(valForKey)) { inverseMap[valForKey] = otherKey; break; } } } return bDirect; } /// <summary> /// Tries to get a value corresponding to <code>key</code>. If found, the output is in value; /// </summary> /// <returns>true if the object that implements IDictionary contains an element with the specified key; otherwise, false. </returns> [SuppressMessage("Microsoft.Contracts", "Ensures-Contract.Result<bool>() == @this.ContainsKey(key)")] public bool TryGetValue(TKey key, out TValue value) { return directMap.TryGetValue(key, out value); } /// <summary> /// Get the values in this map /// </summary> public ICollection<TValue> Values { get { return directMap.Values; } } /// <summary> /// Get/Sets values in this map /// </summary> /// <param name="key"></param> /// <returns></returns> public TValue this[TKey key] { get { return directMap[key]; } set { TValue oldVal; if (directMap.TryGetValue(key, out oldVal)) { inverseMap.Remove(oldVal); } TKey oldKey; if (inverseMap.TryGetValue(value, out oldKey)) { directMap.Remove(oldKey); } directMap[key] = value; inverseMap[value] = key; } } #endregion #region ICollection<KeyValuePair<TKey,TValue>> Members /// <summary> /// Add the KeyValuePair <code>item</code> /// </summary> public void Add(KeyValuePair<TKey, TValue> item) { this[item.Key] = item.Value; } /// <summary> /// Clear the map /// </summary> public void Clear() { directMap.Clear(); inverseMap.Clear(); } /// <summary> /// Does this map contain the <code>item</code>? /// </summary> public bool Contains(KeyValuePair<TKey, TValue> item) { TValue val; if (directMap.TryGetValue(item.Key, out val) && val.Equals(item.Value)) { return true; } return false; } /// <summary> /// Copy all the elements of this collection into the <code>array</code>, starting from <code>arrayIndex</code> /// </summary> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { int i = 0; foreach (var pair in directMap) {// F: we do not know that i ranges over the elements of the collection Contract.Assume(arrayIndex + i < array.Length); array[arrayIndex + (i++)] = pair; } } /// <summary> /// The number of items in the map /// </summary> public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() == directMap.Count); return directMap.Count; } } /// <summary> /// Always <code>false</code> /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Remove the <code>item</code> from the collection /// </summary> public bool Remove(KeyValuePair<TKey, TValue> item) { var b1 = directMap.Remove(item.Key); var b2 = inverseMap.Remove(item.Value); return b1 && b2; } #endregion #region IEnumerable<KeyValuePair<TKey,TValue>> Members [Pure] public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return directMap.GetEnumerator(); } #endregion #region IEnumerable Members //^ [Pure] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return directMap.GetEnumerator(); } #endregion #region Overridden public override string ToString() { var consistent = IsConsistent() ? "Map Consistent" : "WARNING: Map inconsistent"; var direct = ToString<TKey, TValue>(directMap); var indirect = ToString<TValue, TKey>(inverseMap); return string.Format("{0}" + Environment.NewLine + "({1}, {2})", consistent, direct, indirect); } static private string ToString<A, B>(IDictionary<A, B> s) { Contract.Requires(s != null); Contract.Ensures(Contract.Result<string>() != null); var result = new StringBuilder(); foreach (var key in s.Keys) { result.Append("(" + key.ToString() + "," + s[key] + ")"); } return result.ToString(); } #endregion } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; namespace SharpDX.DXGI { /// <summary> /// Helper to use with <see cref="Format"/>. /// </summary> public static class FormatHelper { private static readonly int[] sizeOfInBits = new int[256]; private static readonly bool[] compressedFormats = new bool[256]; private static readonly bool[] srgbFormats = new bool[256]; private static readonly bool[] typelessFormats = new bool[256]; /// <summary> /// Calculates the size of a <see cref="Format"/> in bytes. Can be 0 for compressed format (as they are less than 1 byte) /// </summary> /// <param name="format">The DXGI format.</param> /// <returns>size of in bytes</returns> public static int SizeOfInBytes(this Format format) { var sizeInBits = SizeOfInBits(format); return sizeInBits >> 3; } /// <summary> /// Calculates the size of a <see cref="Format"/> in bits. /// </summary> /// <param name="format">The DXGI format.</param> /// <returns>size of in bits</returns> public static int SizeOfInBits(this Format format) { return sizeOfInBits[(int) format]; } /// <summary> /// Returns true if the <see cref="Format"/> is valid. /// </summary> /// <param name="format">A format to validate</param> /// <returns>True if the <see cref="Format"/> is valid.</returns> public static bool IsValid(this Format format) { return ( (int)(format) >= 1 && (int)(format) <= 115 ); } /// <summary> /// Returns true if the <see cref="Format"/> is a compressed format. /// </summary> /// <param name="format">The format to check for compressed.</param> /// <returns>True if the <see cref="Format"/> is a compressed format</returns> public static bool IsCompressed(this Format format) { return compressedFormats[(int) format]; } /// <summary> /// Determines whether the specified <see cref="Format"/> is packed. /// </summary> /// <param name="format">The DXGI Format.</param> /// <returns><c>true</c> if the specified <see cref="Format"/> is packed; otherwise, <c>false</c>.</returns> public static bool IsPacked(this Format format ) { return ((format == Format.R8G8_B8G8_UNorm) || (format == Format.G8R8_G8B8_UNorm)); } /// <summary> /// Determines whether the specified <see cref="Format"/> is video. /// </summary> /// <param name="format">The <see cref="Format"/>.</param> /// <returns><c>true</c> if the specified <see cref="Format"/> is video; otherwise, <c>false</c>.</returns> public static bool IsVideo(this Format format ) { switch ( format ) { case Format.AYUV: case Format.Y410: case Format.Y416: case Format.NV12: case Format.P010: case Format.P016: case Format.YUY2: case Format.Y210: case Format.Y216: case Format.NV11: // These video formats can be used with the 3D pipeline through special view mappings return true; case Format.Opaque420: case Format.AI44: case Format.IA44: case Format.P8: case Format.A8P8: // These are limited use video formats not usable in any way by the 3D pipeline return true; default: return false; } } /// <summary> /// Determines whether the specified <see cref="Format"/> is a SRGB format. /// </summary> /// <param name="format">The <see cref="Format"/>.</param> /// <returns><c>true</c> if the specified <see cref="Format"/> is a SRGB format; otherwise, <c>false</c>.</returns> public static bool IsSRgb(this Format format ) { return srgbFormats[(int) format]; } /// <summary> /// Determines whether the specified <see cref="Format"/> is typeless. /// </summary> /// <param name="format">The <see cref="Format"/>.</param> /// <returns><c>true</c> if the specified <see cref="Format"/> is typeless; otherwise, <c>false</c>.</returns> public static bool IsTypeless(this Format format ) { return typelessFormats[(int) format]; } /// <summary> /// Computes the scanline count (number of scanlines). /// </summary> /// <param name="format">The <see cref="Format"/>.</param> /// <param name="height">The height.</param> /// <returns>The scanline count.</returns> public static int ComputeScanlineCount(this Format format, int height) { switch (format) { case Format.BC1_Typeless: case Format.BC1_UNorm: case Format.BC1_UNorm_SRgb: case Format.BC2_Typeless: case Format.BC2_UNorm: case Format.BC2_UNorm_SRgb: case Format.BC3_Typeless: case Format.BC3_UNorm: case Format.BC3_UNorm_SRgb: case Format.BC4_Typeless: case Format.BC4_UNorm: case Format.BC4_SNorm: case Format.BC5_Typeless: case Format.BC5_UNorm: case Format.BC5_SNorm: case Format.BC6H_Typeless: case Format.BC6H_Uf16: case Format.BC6H_Sf16: case Format.BC7_Typeless: case Format.BC7_UNorm: case Format.BC7_UNorm_SRgb: return Math.Max(1, (height + 3) / 4); default: return height; } } /// <summary> /// Static initializer to speed up size calculation (not sure the JIT is enough "smart" for this kind of thing). /// </summary> static FormatHelper() { InitFormat(new[] { Format.R1_UNorm }, 1); InitFormat(new[] { Format.A8_UNorm, Format.R8_SInt, Format.R8_SNorm, Format.R8_Typeless, Format.R8_UInt, Format.R8_UNorm }, 8); InitFormat(new[] { Format.B5G5R5A1_UNorm, Format.B5G6R5_UNorm, Format.D16_UNorm, Format.R16_Float, Format.R16_SInt, Format.R16_SNorm, Format.R16_Typeless, Format.R16_UInt, Format.R16_UNorm, Format.R8G8_SInt, Format.R8G8_SNorm, Format.R8G8_Typeless, Format.R8G8_UInt, Format.R8G8_UNorm, Format.B4G4R4A4_UNorm, }, 16); InitFormat(new[] { Format.B8G8R8X8_Typeless, Format.B8G8R8X8_UNorm, Format.B8G8R8X8_UNorm_SRgb, Format.D24_UNorm_S8_UInt, Format.D32_Float, Format.D32_Float_S8X24_UInt, Format.G8R8_G8B8_UNorm, Format.R10G10B10_Xr_Bias_A2_UNorm, Format.R10G10B10A2_Typeless, Format.R10G10B10A2_UInt, Format.R10G10B10A2_UNorm, Format.R11G11B10_Float, Format.R16G16_Float, Format.R16G16_SInt, Format.R16G16_SNorm, Format.R16G16_Typeless, Format.R16G16_UInt, Format.R16G16_UNorm, Format.R24_UNorm_X8_Typeless, Format.R24G8_Typeless, Format.R32_Float, Format.R32_Float_X8X24_Typeless, Format.R32_SInt, Format.R32_Typeless, Format.R32_UInt, Format.R8G8_B8G8_UNorm, Format.R8G8B8A8_SInt, Format.R8G8B8A8_SNorm, Format.R8G8B8A8_Typeless, Format.R8G8B8A8_UInt, Format.R8G8B8A8_UNorm, Format.R8G8B8A8_UNorm_SRgb, Format.B8G8R8A8_Typeless, Format.B8G8R8A8_UNorm, Format.B8G8R8A8_UNorm_SRgb, Format.R9G9B9E5_Sharedexp, Format.X24_Typeless_G8_UInt, Format.X32_Typeless_G8X24_UInt, }, 32); InitFormat(new[] { Format.R16G16B16A16_Float, Format.R16G16B16A16_SInt, Format.R16G16B16A16_SNorm, Format.R16G16B16A16_Typeless, Format.R16G16B16A16_UInt, Format.R16G16B16A16_UNorm, Format.R32G32_Float, Format.R32G32_SInt, Format.R32G32_Typeless, Format.R32G32_UInt, Format.R32G8X24_Typeless, }, 64); InitFormat(new[] { Format.R32G32B32_Float, Format.R32G32B32_SInt, Format.R32G32B32_Typeless, Format.R32G32B32_UInt, }, 96); InitFormat(new[] { Format.R32G32B32A32_Float, Format.R32G32B32A32_SInt, Format.R32G32B32A32_Typeless, Format.R32G32B32A32_UInt, }, 128); InitFormat(new[] { Format.BC1_Typeless, Format.BC1_UNorm, Format.BC1_UNorm_SRgb, Format.BC4_SNorm, Format.BC4_Typeless, Format.BC4_UNorm, }, 4); InitFormat(new[] { Format.BC2_Typeless, Format.BC2_UNorm, Format.BC2_UNorm_SRgb, Format.BC3_Typeless, Format.BC3_UNorm, Format.BC3_UNorm_SRgb, Format.BC5_SNorm, Format.BC5_Typeless, Format.BC5_UNorm, Format.BC6H_Sf16, Format.BC6H_Typeless, Format.BC6H_Uf16, Format.BC7_Typeless, Format.BC7_UNorm, Format.BC7_UNorm_SRgb, }, 8); // Init compressed formats InitDefaults(new[] { Format.BC1_Typeless, Format.BC1_UNorm, Format.BC1_UNorm_SRgb, Format.BC2_Typeless, Format.BC2_UNorm, Format.BC2_UNorm_SRgb, Format.BC3_Typeless, Format.BC3_UNorm, Format.BC3_UNorm_SRgb, Format.BC4_Typeless, Format.BC4_UNorm, Format.BC4_SNorm, Format.BC5_Typeless, Format.BC5_UNorm, Format.BC5_SNorm, Format.BC6H_Typeless, Format.BC6H_Uf16, Format.BC6H_Sf16, Format.BC7_Typeless, Format.BC7_UNorm, Format.BC7_UNorm_SRgb, }, compressedFormats); // Init srgb formats InitDefaults(new[] { Format.R8G8B8A8_UNorm_SRgb, Format.BC1_UNorm_SRgb, Format.BC2_UNorm_SRgb, Format.BC3_UNorm_SRgb, Format.B8G8R8A8_UNorm_SRgb, Format.B8G8R8X8_UNorm_SRgb, Format.BC7_UNorm_SRgb, }, srgbFormats); // Init typeless formats InitDefaults(new[] { Format.R32G32B32A32_Typeless, Format.R32G32B32_Typeless, Format.R16G16B16A16_Typeless, Format.R32G32_Typeless, Format.R32G8X24_Typeless, Format.R10G10B10A2_Typeless, Format.R8G8B8A8_Typeless, Format.R16G16_Typeless, Format.R32_Typeless, Format.R24G8_Typeless, Format.R8G8_Typeless, Format.R16_Typeless, Format.R8_Typeless, Format.BC1_Typeless, Format.BC2_Typeless, Format.BC3_Typeless, Format.BC4_Typeless, Format.BC5_Typeless, Format.B8G8R8A8_Typeless, Format.B8G8R8X8_Typeless, Format.BC6H_Typeless, Format.BC7_Typeless, }, typelessFormats); } private static void InitFormat(IEnumerable<Format> formats, int bitCount) { foreach (var format in formats) sizeOfInBits[(int)format] = bitCount; } private static void InitDefaults(IEnumerable<Format> formats, bool[] outputArray) { foreach (var format in formats) outputArray[(int)format] = true; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elasticloadbalancing-2012-06-01.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.ElasticLoadBalancing; using Amazon.ElasticLoadBalancing.Model; using Amazon.ElasticLoadBalancing.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public class ElasticLoadBalancingMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("elasticloadbalancing-2012-06-01.normal.json", "elasticloadbalancing.customizations.json"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void AddTagsMarshallTest() { var operation = service_model.FindOperation("AddTags"); var request = InstantiateClassGenerator.Execute<AddTagsRequest>(); var marshaller = new AddTagsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = AddTagsResponseUnmarshaller.Instance.Unmarshall(context) as AddTagsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void ApplySecurityGroupsToLoadBalancerMarshallTest() { var operation = service_model.FindOperation("ApplySecurityGroupsToLoadBalancer"); var request = InstantiateClassGenerator.Execute<ApplySecurityGroupsToLoadBalancerRequest>(); var marshaller = new ApplySecurityGroupsToLoadBalancerRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = ApplySecurityGroupsToLoadBalancerResponseUnmarshaller.Instance.Unmarshall(context) as ApplySecurityGroupsToLoadBalancerResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void AttachLoadBalancerToSubnetsMarshallTest() { var operation = service_model.FindOperation("AttachLoadBalancerToSubnets"); var request = InstantiateClassGenerator.Execute<AttachLoadBalancerToSubnetsRequest>(); var marshaller = new AttachLoadBalancerToSubnetsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = AttachLoadBalancerToSubnetsResponseUnmarshaller.Instance.Unmarshall(context) as AttachLoadBalancerToSubnetsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void ConfigureHealthCheckMarshallTest() { var operation = service_model.FindOperation("ConfigureHealthCheck"); var request = InstantiateClassGenerator.Execute<ConfigureHealthCheckRequest>(); var marshaller = new ConfigureHealthCheckRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = ConfigureHealthCheckResponseUnmarshaller.Instance.Unmarshall(context) as ConfigureHealthCheckResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void CreateAppCookieStickinessPolicyMarshallTest() { var operation = service_model.FindOperation("CreateAppCookieStickinessPolicy"); var request = InstantiateClassGenerator.Execute<CreateAppCookieStickinessPolicyRequest>(); var marshaller = new CreateAppCookieStickinessPolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = CreateAppCookieStickinessPolicyResponseUnmarshaller.Instance.Unmarshall(context) as CreateAppCookieStickinessPolicyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void CreateLBCookieStickinessPolicyMarshallTest() { var operation = service_model.FindOperation("CreateLBCookieStickinessPolicy"); var request = InstantiateClassGenerator.Execute<CreateLBCookieStickinessPolicyRequest>(); var marshaller = new CreateLBCookieStickinessPolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = CreateLBCookieStickinessPolicyResponseUnmarshaller.Instance.Unmarshall(context) as CreateLBCookieStickinessPolicyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void CreateLoadBalancerMarshallTest() { var operation = service_model.FindOperation("CreateLoadBalancer"); var request = InstantiateClassGenerator.Execute<CreateLoadBalancerRequest>(); var marshaller = new CreateLoadBalancerRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = CreateLoadBalancerResponseUnmarshaller.Instance.Unmarshall(context) as CreateLoadBalancerResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void CreateLoadBalancerListenersMarshallTest() { var operation = service_model.FindOperation("CreateLoadBalancerListeners"); var request = InstantiateClassGenerator.Execute<CreateLoadBalancerListenersRequest>(); var marshaller = new CreateLoadBalancerListenersRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = CreateLoadBalancerListenersResponseUnmarshaller.Instance.Unmarshall(context) as CreateLoadBalancerListenersResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void CreateLoadBalancerPolicyMarshallTest() { var operation = service_model.FindOperation("CreateLoadBalancerPolicy"); var request = InstantiateClassGenerator.Execute<CreateLoadBalancerPolicyRequest>(); var marshaller = new CreateLoadBalancerPolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = CreateLoadBalancerPolicyResponseUnmarshaller.Instance.Unmarshall(context) as CreateLoadBalancerPolicyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DeleteLoadBalancerMarshallTest() { var operation = service_model.FindOperation("DeleteLoadBalancer"); var request = InstantiateClassGenerator.Execute<DeleteLoadBalancerRequest>(); var marshaller = new DeleteLoadBalancerRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DeleteLoadBalancerResponseUnmarshaller.Instance.Unmarshall(context) as DeleteLoadBalancerResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DeleteLoadBalancerListenersMarshallTest() { var operation = service_model.FindOperation("DeleteLoadBalancerListeners"); var request = InstantiateClassGenerator.Execute<DeleteLoadBalancerListenersRequest>(); var marshaller = new DeleteLoadBalancerListenersRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DeleteLoadBalancerListenersResponseUnmarshaller.Instance.Unmarshall(context) as DeleteLoadBalancerListenersResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DeleteLoadBalancerPolicyMarshallTest() { var operation = service_model.FindOperation("DeleteLoadBalancerPolicy"); var request = InstantiateClassGenerator.Execute<DeleteLoadBalancerPolicyRequest>(); var marshaller = new DeleteLoadBalancerPolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DeleteLoadBalancerPolicyResponseUnmarshaller.Instance.Unmarshall(context) as DeleteLoadBalancerPolicyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DeregisterInstancesFromLoadBalancerMarshallTest() { var operation = service_model.FindOperation("DeregisterInstancesFromLoadBalancer"); var request = InstantiateClassGenerator.Execute<DeregisterInstancesFromLoadBalancerRequest>(); var marshaller = new DeregisterInstancesFromLoadBalancerRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DeregisterInstancesFromLoadBalancerResponseUnmarshaller.Instance.Unmarshall(context) as DeregisterInstancesFromLoadBalancerResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DescribeInstanceHealthMarshallTest() { var operation = service_model.FindOperation("DescribeInstanceHealth"); var request = InstantiateClassGenerator.Execute<DescribeInstanceHealthRequest>(); var marshaller = new DescribeInstanceHealthRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeInstanceHealthResponseUnmarshaller.Instance.Unmarshall(context) as DescribeInstanceHealthResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DescribeLoadBalancerAttributesMarshallTest() { var operation = service_model.FindOperation("DescribeLoadBalancerAttributes"); var request = InstantiateClassGenerator.Execute<DescribeLoadBalancerAttributesRequest>(); var marshaller = new DescribeLoadBalancerAttributesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeLoadBalancerAttributesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLoadBalancerAttributesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DescribeLoadBalancerPoliciesMarshallTest() { var operation = service_model.FindOperation("DescribeLoadBalancerPolicies"); var request = InstantiateClassGenerator.Execute<DescribeLoadBalancerPoliciesRequest>(); var marshaller = new DescribeLoadBalancerPoliciesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeLoadBalancerPoliciesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLoadBalancerPoliciesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DescribeLoadBalancerPolicyTypesMarshallTest() { var operation = service_model.FindOperation("DescribeLoadBalancerPolicyTypes"); var request = InstantiateClassGenerator.Execute<DescribeLoadBalancerPolicyTypesRequest>(); var marshaller = new DescribeLoadBalancerPolicyTypesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeLoadBalancerPolicyTypesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLoadBalancerPolicyTypesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DescribeLoadBalancersMarshallTest() { var operation = service_model.FindOperation("DescribeLoadBalancers"); var request = InstantiateClassGenerator.Execute<DescribeLoadBalancersRequest>(); var marshaller = new DescribeLoadBalancersRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeLoadBalancersResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLoadBalancersResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DescribeTagsMarshallTest() { var operation = service_model.FindOperation("DescribeTags"); var request = InstantiateClassGenerator.Execute<DescribeTagsRequest>(); var marshaller = new DescribeTagsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeTagsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeTagsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DetachLoadBalancerFromSubnetsMarshallTest() { var operation = service_model.FindOperation("DetachLoadBalancerFromSubnets"); var request = InstantiateClassGenerator.Execute<DetachLoadBalancerFromSubnetsRequest>(); var marshaller = new DetachLoadBalancerFromSubnetsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DetachLoadBalancerFromSubnetsResponseUnmarshaller.Instance.Unmarshall(context) as DetachLoadBalancerFromSubnetsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void DisableAvailabilityZonesForLoadBalancerMarshallTest() { var operation = service_model.FindOperation("DisableAvailabilityZonesForLoadBalancer"); var request = InstantiateClassGenerator.Execute<DisableAvailabilityZonesForLoadBalancerRequest>(); var marshaller = new DisableAvailabilityZonesForLoadBalancerRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DisableAvailabilityZonesForLoadBalancerResponseUnmarshaller.Instance.Unmarshall(context) as DisableAvailabilityZonesForLoadBalancerResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void EnableAvailabilityZonesForLoadBalancerMarshallTest() { var operation = service_model.FindOperation("EnableAvailabilityZonesForLoadBalancer"); var request = InstantiateClassGenerator.Execute<EnableAvailabilityZonesForLoadBalancerRequest>(); var marshaller = new EnableAvailabilityZonesForLoadBalancerRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = EnableAvailabilityZonesForLoadBalancerResponseUnmarshaller.Instance.Unmarshall(context) as EnableAvailabilityZonesForLoadBalancerResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void ModifyLoadBalancerAttributesMarshallTest() { var operation = service_model.FindOperation("ModifyLoadBalancerAttributes"); var request = InstantiateClassGenerator.Execute<ModifyLoadBalancerAttributesRequest>(); var marshaller = new ModifyLoadBalancerAttributesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = ModifyLoadBalancerAttributesResponseUnmarshaller.Instance.Unmarshall(context) as ModifyLoadBalancerAttributesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void RegisterInstancesWithLoadBalancerMarshallTest() { var operation = service_model.FindOperation("RegisterInstancesWithLoadBalancer"); var request = InstantiateClassGenerator.Execute<RegisterInstancesWithLoadBalancerRequest>(); var marshaller = new RegisterInstancesWithLoadBalancerRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = RegisterInstancesWithLoadBalancerResponseUnmarshaller.Instance.Unmarshall(context) as RegisterInstancesWithLoadBalancerResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void RemoveTagsMarshallTest() { var operation = service_model.FindOperation("RemoveTags"); var request = InstantiateClassGenerator.Execute<RemoveTagsRequest>(); var marshaller = new RemoveTagsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = RemoveTagsResponseUnmarshaller.Instance.Unmarshall(context) as RemoveTagsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void SetLoadBalancerListenerSSLCertificateMarshallTest() { var operation = service_model.FindOperation("SetLoadBalancerListenerSSLCertificate"); var request = InstantiateClassGenerator.Execute<SetLoadBalancerListenerSSLCertificateRequest>(); var marshaller = new SetLoadBalancerListenerSSLCertificateRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = SetLoadBalancerListenerSSLCertificateResponseUnmarshaller.Instance.Unmarshall(context) as SetLoadBalancerListenerSSLCertificateResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void SetLoadBalancerPoliciesForBackendServerMarshallTest() { var operation = service_model.FindOperation("SetLoadBalancerPoliciesForBackendServer"); var request = InstantiateClassGenerator.Execute<SetLoadBalancerPoliciesForBackendServerRequest>(); var marshaller = new SetLoadBalancerPoliciesForBackendServerRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = SetLoadBalancerPoliciesForBackendServerResponseUnmarshaller.Instance.Unmarshall(context) as SetLoadBalancerPoliciesForBackendServerResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("ElasticLoadBalancing")] public void SetLoadBalancerPoliciesOfListenerMarshallTest() { var operation = service_model.FindOperation("SetLoadBalancerPoliciesOfListener"); var request = InstantiateClassGenerator.Execute<SetLoadBalancerPoliciesOfListenerRequest>(); var marshaller = new SetLoadBalancerPoliciesOfListenerRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = SetLoadBalancerPoliciesOfListenerResponseUnmarshaller.Instance.Unmarshall(context) as SetLoadBalancerPoliciesOfListenerResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } } }
// 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.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System.Collections.Generic.Internal { internal class SR { static internal string ArgumentOutOfRange_NeedNonNegNum = "ArgumentOutOfRange_NeedNonNegNum"; static internal string Arg_WrongType = "Arg_WrongType"; static internal string Arg_ArrayPlusOffTooSmall = "Arg_ArrayPlusOffTooSmall"; static internal string Arg_RankMultiDimNotSupported = "Arg_RankMultiDimNotSupported"; static internal string Arg_NonZeroLowerBound = "Arg_NonZeroLowerBound"; static internal string Argument_InvalidArrayType = "Argument_InvalidArrayType"; static internal string Argument_AddingDuplicate = "Argument_AddingDuplicate"; static internal string InvalidOperation_EnumFailedVersion = "InvalidOperation_EnumFailedVersion"; static internal string InvalidOperation_EnumOpCantHappen = "InvalidOperation_EnumOpCantHappen"; static internal string NotSupported_KeyCollectionSet = "NotSupported_KeyCollectionSet"; static internal string NotSupported_ValueCollectionSet = "NotSupported_ValueCollectionSet"; static internal string ArgumentOutOfRange_SmallCapacity = "ArgumentOutOfRange_SmallCapacity"; static internal string Argument_InvalidOffLen = "Argument_InvalidOffLen"; } internal class HashHelpers { private const Int32 HashPrime = 101; public static bool IsPrime(int candidate) { if ((candidate & 1) != 0) { for (int divisor = 3; divisor * divisor < candidate; divisor += 2) { if ((candidate % divisor) == 0) return false; } return true; } return (candidate == 2); } public static int GetPrime(int min) { if (min < 0) { throw new ArgumentException("Arg_HTCapacityOverflow"); } for (int i = (min | 1); i < Int32.MaxValue; i += 2) { if (((i - 1) % HashPrime != 0) && IsPrime(i)) { return i; } } return min; } // Returns size of hashtable to grow to. public static int ExpandPrime(int oldSize) { int newSize = 2 * oldSize; // Allow the hashtables to grow to maximum possible size (~2G elements) before encoutering capacity overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize) { Contract.Assert(MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength"); return MaxPrimeArrayLength; } return GetPrime(newSize); } // This is the maximum prime smaller than Array.MaxArrayLength public const int MaxPrimeArrayLength = 0x7FEFFFFD; } // Non-generic part of Dictionary, single copy internal class DictionaryBase { protected struct Entry { public int hashCode; // Lower 31 bits of hash code, -1 if unused public int next; // Index of next entry, -1 if last public int bucket; } protected int count; protected int version; protected int freeList; protected int freeCount; protected Entry[] entries; public int Count { get { return count - freeCount; } } /// <summary> /// Allocate entry array, clear bucket /// </summary> protected int InitializeBase(int capacity) { int size = HashHelpers.GetPrime(capacity); entries = new Entry[size]; for (int i = 0; i < entries.Length; i++) { entries[i].bucket = -1; } freeList = -1; return size; } /// <summary> /// Clear entry array, bucket, counts /// </summary> protected void ClearBase() { Array.Clear(entries, 0, count); for (int i = 0; i < entries.Length; i++) { entries[i].bucket = -1; } freeList = -1; count = 0; freeCount = 0; version++; } /// <summary> /// Resize entry array, clean bucket, but do not set entries yet /// </summary> protected Entry[] ResizeBase1(int newSize) { Entry[] newEntries = new Entry[newSize]; Array.Copy(entries, 0, newEntries, 0, count); for (int i = 0; i < newEntries.Length; i++) { newEntries[i].bucket = -1; } return newEntries; } /// <summary> /// Relink buckets, set new entry array /// </summary> protected void ResizeBase2(Entry[] newEntries, int newSize) { for (int i = 0; i < count; i++) { int bucket = newEntries[i].hashCode % newSize; newEntries[i].next = newEntries[bucket].bucket; newEntries[bucket].bucket = i; } entries = newEntries; } #if !RHTESTCL [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] #endif protected int ModLength(int hashCode) { // uint % operator is faster than int % operator return (int)((uint)hashCode % (uint)entries.Length); } /// <summary> /// Find the first entry with hashCode /// </summary> protected int FindFirstEntry(int hashCode) { if (entries != null) { hashCode = hashCode & 0x7FFFFFFF; for (int i = entries[ModLength(hashCode)].bucket; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode) { return i; } } } return -1; } /// <summary> /// Find the next entry with the same hashCode as entry /// </summary> protected int FindNextEntry(int entry) { if ((entry >= 0) && entries != null) { int hashCode = entries[entry].hashCode; for (int i = entries[entry].next; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode) { return i; } } } return -1; } } }
using System; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Collections.Generic; using SFML.Window; using SFML.System; namespace SFML { namespace Graphics { //////////////////////////////////////////////////////////// /// <summary> /// Wrapper for pixel shaders /// </summary> //////////////////////////////////////////////////////////// public class Shader : ObjectBase { //////////////////////////////////////////////////////////// /// <summary> /// Special type that can be passed to SetParameter, /// and that represents the texture of the object being drawn /// </summary> //////////////////////////////////////////////////////////// public class CurrentTextureType {} //////////////////////////////////////////////////////////// /// <summary> /// Special value that can be passed to SetParameter, /// and that represents the texture of the object being drawn /// </summary> //////////////////////////////////////////////////////////// public static readonly CurrentTextureType CurrentTexture = null; //////////////////////////////////////////////////////////// /// <summary> /// Load the vertex and fragment shaders from files /// /// This function can load both the vertex and the fragment /// shaders, or only one of them: pass NULL if you don't want to load /// either the vertex shader or the fragment shader. /// The sources must be text files containing valid shaders /// in GLSL language. GLSL is a C-like language dedicated to /// OpenGL shaders; you'll probably need to read a good documentation /// for it before writing your own shaders. /// </summary> /// <param name="vertexShaderFilename">Path of the vertex shader file to load, or null to skip this shader</param> /// <param name="fragmentShaderFilename">Path of the fragment shader file to load, or null to skip this shader</param> /// <exception cref="LoadingFailedException" /> //////////////////////////////////////////////////////////// public Shader(string vertexShaderFilename, string fragmentShaderFilename) : base(sfShader_createFromFile(vertexShaderFilename, fragmentShaderFilename)) { if (CPointer == IntPtr.Zero) throw new LoadingFailedException("shader", vertexShaderFilename + " " + fragmentShaderFilename); } //////////////////////////////////////////////////////////// /// <summary> /// Load both the vertex and fragment shaders from custom streams /// /// This function can load both the vertex and the fragment /// shaders, or only one of them: pass NULL if you don't want to load /// either the vertex shader or the fragment shader. /// The sources must be valid shaders in GLSL language. GLSL is /// a C-like language dedicated to OpenGL shaders; you'll /// probably need to read a good documentation for it before /// writing your own shaders. /// </summary> /// <param name="vertexShaderStream">Source stream to read the vertex shader from, or null to skip this shader</param> /// <param name="fragmentShaderStream">Source stream to read the fragment shader from, or null to skip this shader</param> /// <exception cref="LoadingFailedException" /> //////////////////////////////////////////////////////////// public Shader(Stream vertexShaderStream, Stream fragmentShaderStream) : base(IntPtr.Zero) { StreamAdaptor vertexAdaptor = new StreamAdaptor(vertexShaderStream); StreamAdaptor fragmentAdaptor = new StreamAdaptor(fragmentShaderStream); CPointer = sfShader_createFromStream(vertexAdaptor.InputStreamPtr, fragmentAdaptor.InputStreamPtr); vertexAdaptor.Dispose(); fragmentAdaptor.Dispose(); if (CPointer == IntPtr.Zero) throw new LoadingFailedException("shader"); } //////////////////////////////////////////////////////////// /// <summary> /// Load both the vertex and fragment shaders from source codes in memory /// /// This function can load both the vertex and the fragment /// shaders, or only one of them: pass NULL if you don't want to load /// either the vertex shader or the fragment shader. /// The sources must be valid shaders in GLSL language. GLSL is /// a C-like language dedicated to OpenGL shaders; you'll /// probably need to read a good documentation for it before /// writing your own shaders. /// </summary> /// <param name="vertexShader">String containing the source code of the vertex shader</param> /// <param name="fragmentShader">String containing the source code of the fragment shader</param> /// <returns>New shader instance</returns> /// <exception cref="LoadingFailedException" /> //////////////////////////////////////////////////////////// public static Shader FromString(string vertexShader, string fragmentShader) { IntPtr ptr = sfShader_createFromMemory(vertexShader, fragmentShader); if (ptr == IntPtr.Zero) throw new LoadingFailedException("shader"); return new Shader(ptr); } //////////////////////////////////////////////////////////// /// <summary> /// Change a float parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a float /// (float GLSL type). /// </summary> /// /// <param name="name">Name of the parameter in the shader</param> /// <param name="x">Value to assign</param> /// //////////////////////////////////////////////////////////// public void SetParameter(string name, float x) { sfShader_setFloatParameter(CPointer, name, x); } //////////////////////////////////////////////////////////// /// <summary> /// Change a 2-components vector parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 2x1 vector /// (vec2 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="x">First component of the value to assign</param> /// <param name="y">Second component of the value to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, float x, float y) { sfShader_setFloat2Parameter(CPointer, name, x, y); } //////////////////////////////////////////////////////////// /// <summary> /// Change a 3-components vector parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 3x1 vector /// (vec3 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="x">First component of the value to assign</param> /// <param name="y">Second component of the value to assign</param> /// <param name="z">Third component of the value to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, float x, float y, float z) { sfShader_setFloat3Parameter(CPointer, name, x, y, z); } //////////////////////////////////////////////////////////// /// <summary> /// Change a 4-components vector parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 4x1 vector /// (vec4 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="x">First component of the value to assign</param> /// <param name="y">Second component of the value to assign</param> /// <param name="z">Third component of the value to assign</param> /// <param name="w">Fourth component of the value to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, float x, float y, float z, float w) { sfShader_setFloat4Parameter(CPointer, name, x, y, z, w); } //////////////////////////////////////////////////////////// /// <summary> /// Change a 2-components vector parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 2x1 vector /// (vec2 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="vector">Vector to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, Vector2f vector) { SetParameter(name, vector.X, vector.Y); } //////////////////////////////////////////////////////////// /// <summary> /// Change a color parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 4x1 vector /// (vec4 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="color">Color to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, Color color) { sfShader_setColorParameter(CPointer, name, color); } //////////////////////////////////////////////////////////// /// <summary> /// Change a matrix parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 4x4 matrix /// (mat4 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="transform">Transform to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, Transform transform) { sfShader_setTransformParameter(CPointer, name, transform); } //////////////////////////////////////////////////////////// /// <summary> /// Change a texture parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 2D texture /// (sampler2D GLSL type). /// /// It is important to note that \a texture must remain alive as long /// as the shader uses it, no copy is made internally. /// /// To use the texture of the object being draw, which cannot be /// known in advance, you can pass the special value /// Shader.CurrentTexture. /// </summary> /// <param name="name">Name of the texture in the shader</param> /// <param name="texture">Texture to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, Texture texture) { myTextures[name] = texture; sfShader_setTextureParameter(CPointer, name, texture.CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Change a texture parameter of the shader /// /// This overload maps a shader texture variable to the /// texture of the object being drawn, which cannot be /// known in advance. The second argument must be /// sf::Shader::CurrentTexture. /// The corresponding parameter in the shader must be a 2D texture /// (sampler2D GLSL type). /// </summary> /// <param name="name">Name of the texture in the shader</param> /// <param name="current">Always pass the spacial value Shader.CurrentTexture</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, CurrentTextureType current) { sfShader_setCurrentTextureParameter(CPointer, name); } //////////////////////////////////////////////////////////// /// <summary> /// Bind a shader for rendering /// </summary> /// <param name="shader">Shader to bind (can be null to use no shader)</param> //////////////////////////////////////////////////////////// public static void Bind(Shader shader) { sfShader_bind(shader != null ? shader.CPointer : IntPtr.Zero); } //////////////////////////////////////////////////////////// /// <summary> /// Tell whether or not the system supports shaders. /// /// This property should always be checked before using /// the shader features. If it returns false, then /// any attempt to use Shader will fail. /// </summary> //////////////////////////////////////////////////////////// public static bool IsAvailable { get {return sfShader_isAvailable();} } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[Shader]"; } //////////////////////////////////////////////////////////// /// <summary> /// Handle the destruction of the object /// </summary> /// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param> //////////////////////////////////////////////////////////// protected override void Destroy(bool disposing) { if (!disposing) Context.Global.SetActive(true); myTextures.Clear(); sfShader_destroy(CPointer); if (!disposing) Context.Global.SetActive(false); } //////////////////////////////////////////////////////////// /// <summary> /// Construct the shader from a pointer /// </summary> /// <param name="ptr">Pointer to the shader instance</param> //////////////////////////////////////////////////////////// public Shader(IntPtr ptr) : base(ptr) { } Dictionary<string, Texture> myTextures = new Dictionary<string, Texture>(); #region Imports [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfShader_createFromFile(string vertexShaderFilename, string fragmentShaderFilename); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfShader_createFromMemory(string vertexShader, string fragmentShader); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfShader_createFromStream(IntPtr vertexShaderStream, IntPtr fragmentShaderStream); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_destroy(IntPtr shader); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setFloatParameter(IntPtr shader, string name, float x); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setFloat2Parameter(IntPtr shader, string name, float x, float y); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setFloat3Parameter(IntPtr shader, string name, float x, float y, float z); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setFloat4Parameter(IntPtr shader, string name, float x, float y, float z, float w); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setColorParameter(IntPtr shader, string name, Color color); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setTransformParameter(IntPtr shader, string name, Transform transform); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setTextureParameter(IntPtr shader, string name, IntPtr texture); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setCurrentTextureParameter(IntPtr shader, string name); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_bind(IntPtr shader); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfShader_isAvailable(); #endregion } } }
// // ThreadProgressDialog.cs // // Author: // Stephane Delcroix <stephane@delcroix.org> // Larry Ewing <lewing@src.gnome.org> // Thomas Van Machelen <thomas.vanmachelen@gmail.com> // // Copyright (C) 2004-2009 Novell, Inc. // Copyright (C) 2007-2009 Stephane Delcroix // Copyright (C) 2004-2006 Larry Ewing // Copyright (C) 2007 Thomas Van Machelen // // 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.Threading; using System.Collections.Generic; using Gtk; using FSpot.Utils; namespace FSpot.UI.Dialog { public class ThreadProgressDialog : Gtk.Dialog { DelayedOperation delay; Gtk.ProgressBar progress_bar; Gtk.Label message_label; Gtk.Button button; Gtk.Button retry_button; Gtk.Button skip_button; Gtk.ResponseType error_response; AutoResetEvent error_response_event; object syncHandle = new object (); Thread thread; // FIXME: The total parameter makes sense, but doesn't seem to ever be used? public ThreadProgressDialog (Thread thread, int total) { /* if (parent_window) this.TransientFor = parent_window; */ this.Title = thread.Name; this.thread = thread; HasSeparator = false; BorderWidth = 6; SetDefaultSize (300, -1); message_label = new Gtk.Label (String.Empty); VBox.PackStart (message_label, true, true, 12); progress_bar = new Gtk.ProgressBar (); VBox.PackStart (progress_bar, true, true, 6); retry_button = new Gtk.Button (Mono.Unix.Catalog.GetString ("Retry")); retry_button.Clicked += new EventHandler (HandleRetryClicked); skip_button = new Gtk.Button (Mono.Unix.Catalog.GetString ("Skip")); skip_button.Clicked += new EventHandler (HandleSkipClicked); ActionArea.Add (retry_button); ActionArea.Add (skip_button); button_label = Gtk.Stock.Cancel; button = (Gtk.Button) AddButton (button_label, (int)Gtk.ResponseType.Cancel); delay = new DelayedOperation (new GLib.IdleHandler (HandleUpdate)); Response += HandleResponse; Destroyed += HandleDestroy; } string progress_text; public string ProgressText { get { return progress_text; } set { lock (syncHandle) { progress_text = value; delay.Start (); } } } string button_label; public string ButtonLabel { get { return button_label; } set { lock (syncHandle) { button_label = value; delay.Start (); } } } string message; public string Message { get { return message; } set { lock (syncHandle) { message = value; delay.Start (); } } } double fraction; public double Fraction { get { return Fraction; } set { lock (syncHandle) { fraction = value; delay.Start (); } } } List<Widget> widgets; public void VBoxPackEnd (Widget w) { if (widgets == null) widgets = new List<Widget> (); lock (syncHandle) { widgets.Add (w); delay.Start (); } } internal void SetProperties (string progress_text, string button_label, string message, double fraction) { lock (syncHandle) { this.progress_text = progress_text; this.button_label = button_label; this.message = message; this.fraction = fraction; delay.Start (); } } bool retry_skip; bool RetrySkipVisible { set { retry_skip = value; delay.Start (); } } public bool PerformRetrySkip () { error_response = Gtk.ResponseType.None; RetrySkipVisible = true; error_response_event = new AutoResetEvent (false); error_response_event.WaitOne (); RetrySkipVisible = false; return (error_response == Gtk.ResponseType.Yes); } void HandleResponse (object obj, Gtk.ResponseArgs args) { this.Destroy (); } bool HandleUpdate () { message_label.Text = message; progress_bar.Text = progress_text; progress_bar.Fraction = System.Math.Min (1.0, System.Math.Max (0.0, fraction)); button.Label = button_label; retry_button.Visible = skip_button.Visible = retry_skip; if (widgets != null && widgets.Count > 0) { foreach (var w in widgets) VBox.PackEnd (w); widgets.Clear (); } return false; } void HandleDestroy (object sender, EventArgs args) { delay.Stop (); if (thread.IsAlive) { thread.Abort (); } } void HandleRetryClicked (object obj, EventArgs args) { error_response = Gtk.ResponseType.Yes; error_response_event.Set (); } void HandleSkipClicked (object obj, EventArgs args) { error_response = Gtk.ResponseType.No; error_response_event.Set (); } public void Start () { ShowAll (); RetrySkipVisible = false; thread.Start (); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Feedback.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Packaging; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using NuGet.VisualStudio; using Roslyn.Utilities; using Roslyn.VisualStudio.ProjectSystem; using VSLangProj; using VSLangProj140; using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// The Workspace for running inside Visual Studio. /// </summary> internal abstract class VisualStudioWorkspaceImpl : VisualStudioWorkspace { private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1); private const string AppCodeFolderName = "App_Code"; protected readonly IServiceProvider ServiceProvider; private readonly IVsUIShellOpenDocument _shellOpenDocument; private readonly IVsTextManager _textManager; // Not readonly because it needs to be set in the derived class' constructor. private VisualStudioProjectTracker _projectTracker; // document worker coordinator private ISolutionCrawlerRegistrationService _registrationService; private readonly ForegroundThreadAffinitizedObject _foregroundObject = new ForegroundThreadAffinitizedObject(); private PackageInstallerService _packageInstallerService; private SymbolSearchService _symbolSearchService; public VisualStudioWorkspaceImpl( SVsServiceProvider serviceProvider, WorkspaceBackgroundWork backgroundWork) : base( CreateHostServices(serviceProvider), backgroundWork) { this.ServiceProvider = serviceProvider; _textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager; _shellOpenDocument = serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); var session = serviceProvider.GetService(typeof(SVsLog)) as IVsSqmMulti; var profileService = serviceProvider.GetService(typeof(SVsFeedbackProfile)) as IVsFeedbackProfile; // We have Watson hits where this came back null, so guard against it if (profileService != null) { Sqm.LogSession(session, profileService.IsMicrosoftInternal); } } internal static HostServices CreateHostServices(SVsServiceProvider serviceProvider) { var composition = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); return MefV1HostServices.Create(composition.DefaultExportProvider); } protected void InitializeStandardVisualStudioWorkspace(SVsServiceProvider serviceProvider, SaveEventsService saveEventsService) { var projectTracker = new VisualStudioProjectTracker(serviceProvider); // Ensure the document tracking service is initialized on the UI thread var documentTrackingService = this.Services.GetService<IDocumentTrackingService>(); var documentProvider = new RoslynDocumentProvider(projectTracker, serviceProvider, documentTrackingService); projectTracker.DocumentProvider = documentProvider; projectTracker.MetadataReferenceProvider = this.Services.GetService<VisualStudioMetadataReferenceManager>(); projectTracker.RuleSetFileProvider = this.Services.GetService<VisualStudioRuleSetManager>(); this.SetProjectTracker(projectTracker); var workspaceHost = new VisualStudioWorkspaceHost(this); projectTracker.RegisterWorkspaceHost(workspaceHost); projectTracker.StartSendingEventsToWorkspaceHost(workspaceHost); saveEventsService.StartSendingSaveEvents(); // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); // Ensure the nuget package services are initialized on the UI thread. _symbolSearchService = this.Services.GetService<ISymbolSearchService>() as SymbolSearchService; _packageInstallerService = (PackageInstallerService)this.Services.GetService<IPackageInstallerService>(); _packageInstallerService.Connect(this); } /// <summary>NOTE: Call only from derived class constructor</summary> protected void SetProjectTracker(VisualStudioProjectTracker projectTracker) { _projectTracker = projectTracker; } internal VisualStudioProjectTracker ProjectTracker { get { return _projectTracker; } } internal void ClearReferenceCache() { _projectTracker.MetadataReferenceProvider.ClearCache(); } internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId) { var project = GetHostProject(documentId.ProjectId); if (project != null) { return project.GetDocumentOrAdditionalDocument(documentId); } return null; } internal IVisualStudioHostProject GetHostProject(ProjectId projectId) { return this.ProjectTracker.GetProject(projectId); } private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project) { project = GetHostProject(projectId); return project != null; } internal override bool TryApplyChanges( Microsoft.CodeAnalysis.Solution newSolution, IProgressTracker progressTracker) { // first make sure we can edit the document we will be updating (check them out from source control, etc) var changedDocs = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().SelectMany(pd => pd.GetChangedDocuments()).ToList(); if (changedDocs.Count > 0) { this.EnsureEditableDocuments(changedDocs); } return base.TryApplyChanges(newSolution, progressTracker); } public override bool CanOpenDocuments { get { return true; } } internal override bool CanChangeActiveContextDocument { get { return true; } } public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: case ApplyChangesKind.ChangeAdditionalDocument: return true; default: return false; } } private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { hierarchy = null; project = null; return this.TryGetHostProject(projectId, out hostProject) && this.TryGetHierarchy(projectId, out hierarchy) && hierarchy.TryGetProject(out project); } internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project)) { throw new ArgumentException(string.Format(ServicesVSResources.CouldNotFindProject, projectId)); } } internal EnvDTE.Project TryGetDTEProject(ProjectId projectId) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; return TryGetProjectData(projectId, out hostProject, out hierarchy, out project) ? project : null; } internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; try { GetProjectData(projectId, out hostProject, out hierarchy, out project); } catch (ArgumentException) { return false; } var vsProject = (VSProject)project.Object; try { vsProject.References.Add(assemblyName); } catch (Exception) { return false; } return true; } private string GetAnalyzerPath(AnalyzerReference analyzerReference) { return analyzerReference.FullPath; } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Add(filePath); } } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Remove(filePath); } } private string GetMetadataPath(MetadataReference metadataReference) { var fileMetadata = metadataReference as PortableExecutableReference; if (fileMetadata != null) { return fileMetadata.FilePath; } return null; } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSProject vsProject = (VSProject)project.Object; vsProject.References.Add(filePath); } } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; VSLangProj.Reference reference = vsProject.References.Find(filePath); if (reference != null) { reference.Remove(); } } } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; vsProject.References.AddProject(refProject); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; foreach (VSLangProj.Reference reference in vsProject.References) { if (reference.SourceProject == refProject) { reference.Remove(); } } } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: false); } protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: true); } private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(info.Id.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. var folders = info.Folders.AsEnumerable(); if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } folders = FilterFolderForProjectType(project, folders); if (IsWebsite(project)) { AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else if (folders.Any()) { AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else { AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } } private bool IsWebsite(EnvDTE.Project project) { return project.Kind == VsWebSite.PrjKind.prjKindVenusProject; } private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders) { foreach (var folder in folders) { var items = GetAllItems(project.ProjectItems); var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0); if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile) { yield return folder; } } } private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems) { if (projectItems == null) { return SpecializedCollections.EmptyEnumerable<ProjectItem>(); } var items = projectItems.OfType<ProjectItem>(); return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems))); } #if false protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } var name = Path.GetFileName(filePath); if (folders.Any()) { AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } else { AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } } #endif private ProjectItem AddDocumentToProject( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { string folderPath; if (!project.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToFolder( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, IEnumerable<string> folders, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { var folder = project.FindOrCreateFolder(folders); string folderPath; if (!folder.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToProjectItems( IVisualStudioHostProject hostProject, ProjectItems projectItems, DocumentId documentId, string folderPath, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText, string filePath, bool isAdditionalDocument) { if (filePath == null) { var baseName = Path.GetFileNameWithoutExtension(documentName); var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind); var uniqueName = projectItems.GetUniqueName(baseName, extension); filePath = Path.Combine(folderPath, uniqueName); } if (initialText != null) { using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8)) { initialText.Write(writer); } } using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId)) { return projectItems.AddFromFile(filePath); } } protected void RemoveDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var document = this.GetHostDocument(documentId); if (document != null) { var project = document.Project.Hierarchy as IVsProject3; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // it is no longer part of the solution return; } int result; project.RemoveItem(0, itemId, out result); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } public override void OpenDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void CloseDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public override void CloseAdditionalDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public bool TryGetInfoBarData(out IVsWindowFrame frame, out IVsInfoBarUIFactory factory) { frame = null; factory = null; var monitorSelectionService = ServiceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; object value = null; // We want to get whichever window is currently in focus (including toolbars) as we could have had an exception thrown from the error list or interactive window if (monitorSelectionService != null && ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_WindowFrame, out value))) { frame = value as IVsWindowFrame; } else { return false; } factory = ServiceProvider.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory; return frame != null && factory != null; } public void OpenDocumentCore(DocumentId documentId, bool activate = true) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (!_foregroundObject.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.ThisWorkspaceOnlySupportsOpeningDocumentsOnTheUIThread); } var document = this.GetHostDocument(documentId); if (document != null && document.Project != null) { IVsWindowFrame frame; if (TryGetFrame(document, out frame)) { if (activate) { frame.Show(); } else { frame.ShowNoActivate(); } } } } private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame) { frame = null; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // If the ItemId is Nil, then IVsProject would not be able to open the // document using its ItemId. Thus, we must use OpenDocumentViaProject, which only // depends on the file path. uint itemid; IVsUIHierarchy uiHierarchy; OLEServiceProvider oleServiceProvider; return ErrorHandler.Succeeded(_shellOpenDocument.OpenDocumentViaProject( document.FilePath, VSConstants.LOGVIEWID.TextView_guid, out oleServiceProvider, out uiHierarchy, out itemid, out frame)); } else { // If the ItemId is not Nil, then we should not call IVsUIShellDocument // .OpenDocumentViaProject here because that simply takes a file path and opens the // file within the context of the first project it finds. That would cause problems // if the document we're trying to open is actually a linked file in another // project. So, we get the project's hierarchy and open the document using its item // ID. // It's conceivable that IVsHierarchy might not implement IVsProject. However, // OpenDocumentViaProject itself relies upon this QI working, so it should be OK to // use here. var vsProject = document.Project.Hierarchy as IVsProject; return vsProject != null && ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame)); } } public void CloseDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (this.IsDocumentOpen(documentId)) { var document = this.GetHostDocument(documentId); if (document != null) { IVsUIHierarchy uiHierarchy; IVsWindowFrame frame; int isOpen; if (ErrorHandler.Succeeded(_shellOpenDocument.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out uiHierarchy, null, out frame, out isOpen))) { // TODO: do we need save argument for CloseDocument? frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } } } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind) { // No extension was provided. Pick a good one based on the type of host project. switch (hostProject.Language) { case LanguageNames.CSharp: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx"; return ".cs"; case LanguageNames.VisualBasic: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx"; return ".vb"; default: throw new InvalidOperationException(); } } public override IVsHierarchy GetHierarchy(ProjectId projectId) { var project = this.GetHostProject(projectId); if (project == null) { return null; } return project.Hierarchy; } internal override void SetDocumentContext(DocumentId documentId) { var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var hierarchy = hostDocument.Project.Hierarchy; var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { if (sharedHierarchy.SetProperty( (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK) { // The ASP.NET 5 intellisense project is now updated. return; } else { // Universal Project shared files // Change the SharedItemContextHierarchy of the project's parent hierarchy, then // hierarchy events will trigger the workspace to update. var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy); } } else { // Regular linked files // Transfer the item (open buffer) to the new hierarchy, and then hierarchy events // will trigger the workspace to update. var vsproj = hierarchy as IVsProject3; var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null); } } internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId) { // TODO: This is a very roundabout way to update the context // The sharedHierarchy passed in has a new context, but we don't know what it is. // The documentId passed in is associated with this sharedHierarchy, and this method // will be called once for each such documentId. During this process, one of these // documentIds will actually belong to the new SharedItemContextHierarchy. Once we // find that one, we can map back to the open buffer and set its active context to // the appropriate project. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); if (hostProject.Hierarchy == sharedHierarchy) { // How? return; } if (hostProject.Id != documentId.ProjectId) { // While this documentId is associated with one of the head projects for this // sharedHierarchy, it is not associated with the new context hierarchy. Another // documentId will be passed to this method and update the context. return; } // This documentId belongs to the new SharedItemContextHierarchy. Update the associated // buffer. OnDocumentContextUpdated(documentId); } /// <summary> /// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that /// is in the current context. For regular files (non-shared and non-linked) and closed /// linked files, this is always the provided <see cref="DocumentId"/>. For open linked /// files and open shared files, the active context is already tracked by the /// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the /// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/> /// is preferred. /// </summary> internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId) { // If the document is open, then the Workspace knows the current context for both // linked and shared files if (IsDocumentOpen(documentId)) { return base.GetDocumentIdInCurrentContext(documentId); } var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // An itemid is required to determine whether the file belongs to a Shared Project return base.GetDocumentIdInCurrentContext(documentId); } // If this is a regular document or a closed linked (non-shared) document, then use the // default logic for determining current context. var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy == null) { return base.GetDocumentIdInCurrentContext(documentId); } // This is a closed shared document, so we must determine the correct context. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); var matchingProject = CurrentSolution.GetProject(hostProject.Id); if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy) { return base.GetDocumentIdInCurrentContext(documentId); } if (matchingProject.ContainsDocument(documentId)) { // The provided documentId is in the current context project return documentId; } // The current context document is from another project. var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds(); var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id); return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId); } internal bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy) { hierarchy = this.GetHierarchy(projectId); return hierarchy != null; } public override string GetFilePath(DocumentId documentId) { var document = this.GetHostDocument(documentId); if (document == null) { return null; } else { return document.FilePath; } } internal void StartSolutionCrawler() { if (_registrationService == null) { lock (this) { if (_registrationService == null) { _registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } } } } internal void StopSolutionCrawler() { if (_registrationService != null) { lock (this) { if (_registrationService != null) { _registrationService.Unregister(this, blockingShutdown: true); _registrationService = null; } } } } protected override void Dispose(bool finalize) { _packageInstallerService?.Disconnect(this); _symbolSearchService?.Dispose(); // workspace is going away. unregister this workspace from work coordinator StopSolutionCrawler(); base.Dispose(finalize); } public void EnsureEditableDocuments(IEnumerable<DocumentId> documents) { var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GetService(typeof(SVsQueryEditQuerySave)); var fileNames = documents.Select(GetFilePath).ToArray(); uint editVerdict; uint editResultFlags; // TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn int result = queryEdit.QueryEditFiles( rgfQueryEdit: 0, cFiles: fileNames.Length, rgpszMkDocuments: fileNames, rgrgf: new uint[fileNames.Length], rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length], pfEditVerdict: out editVerdict, prgfMoreInfo: out editResultFlags); if (ErrorHandler.Failed(result) || editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { throw new Exception("Unable to check out the files from source control."); } if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0) { throw new Exception("A file was reloaded during the source control checkout."); } } public void EnsureEditableDocuments(params DocumentId[] documents) { this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents); } internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader); } internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader); } public TInterface GetVsService<TService, TInterface>() where TService : class where TInterface : class { return this.ServiceProvider.GetService(typeof(TService)) as TInterface; } internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) { _foregroundObject.AssertIsForeground(); IVsHierarchy referencingHierarchy; IVsHierarchy referencedHierarchy; if (!TryGetHierarchy(referencingProject, out referencingHierarchy) || !TryGetHierarchy(referencedProject, out referencedHierarchy)) { // Couldn't even get a hierarchy for this project. So we have to assume // that adding a reference is disallowed. return false; } // First we have to see if either project disallows the reference being added. const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference; uint canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; uint canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; var referencingProjectFlavor3 = referencingHierarchy as IVsProjectFlavorReferences3; if (referencingProjectFlavor3 != null) { string unused; if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } var referencedProjectFlavor3 = referencedHierarchy as IVsProjectFlavorReferences3; if (referencedProjectFlavor3 != null) { string unused; if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } // Neither project denied the reference being added. At this point, if either project // allows the reference to be added, and the other doesn't block it, then we can add // the reference. if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW || canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW) { return true; } // In both directions things are still unknown. Fallback to the reference manager // to make the determination here. var referenceManager = GetVsService<SVsReferenceManager, IVsReferenceManager>(); if (referenceManager == null) { // Couldn't get the reference manager. Have to assume it's not allowed. return false; } // As long as the reference manager does not deny things, then we allow the // reference to be added. var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy); return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY; } /// <summary> /// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just /// forwards the calls down to the underlying Workspace. /// </summary> protected sealed class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkspaceHost2, IVisualStudioWorkingFolder { private readonly VisualStudioWorkspaceImpl _workspace; private Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>(); public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace) { _workspace = workspace; } void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions) { _workspace.OnCompilationOptionsChanged(projectId, compilationOptions); _workspace.OnParseOptionsChanged(projectId, parseOptions); } void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo) { _workspace.OnDocumentAdded(documentInfo); } void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext) { // TODO: Move this out to DocumentProvider. As is, this depends on being able to // access the host document which will already be deleted in some cases, causing // a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a // Mercury shared document is closed. // UnsubscribeFromSharedHierarchyEvents(documentId); using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed")) { _workspace.OnDocumentClosed(documentId, loader, updateActiveContext); } } void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext) { SubscribeToSharedHierarchyEvents(documentId); _workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext); } private void SubscribeToSharedHierarchyEvents(DocumentId documentId) { // Todo: maybe avoid double alerts. var hostDocument = _workspace.GetHostDocument(documentId); if (hostDocument == null) { return; } var hierarchy = hostDocument.Project.Hierarchy; var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId); var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out cookie); if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId)) { _documentIdToHierarchyEventsCookieMap.Add(documentId, cookie); } } } private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId) { var hostDocument = _workspace.GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out cookie)) { var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie); _documentIdToHierarchyEventsCookieMap.Remove(documentId); } } } private void RegisterPrimarySolutionForPersistentStorage(SolutionId solutionId) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.RegisterPrimarySolution(solutionId); } private void UnregisterPrimarySolutionForPersistentStorage(SolutionId solutionId, bool synchronousShutdown) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.UnregisterPrimarySolution(solutionId, synchronousShutdown); } void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId) { _workspace.OnDocumentRemoved(documentId); } void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceAdded(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceRemoved(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project")) { _workspace.OnProjectAdded(projectInfo); } } void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceAdded(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceRemoved(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project")) { _workspace.OnProjectRemoved(projectId); } } void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo) { RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id); _workspace.OnSolutionAdded(solutionInfo); } void IVisualStudioWorkspaceHost.OnSolutionRemoved() { var solutionId = _workspace.CurrentSolution.Id; _workspace.OnSolutionRemoved(); _workspace.ClearReferenceCache(); UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false); } void IVisualStudioWorkspaceHost.ClearSolution() { _workspace.ClearSolution(); _workspace.ClearReferenceCache(); } void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName) { _workspace.OnAssemblyNameChanged(id, assemblyName); } void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath) { _workspace.OnOutputFilePathChanged(id, outputFilePath); } void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath) { _workspace.OnProjectNameChanged(projectId, name, filePath); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo additionalDocumentInfo) { _workspace.OnAdditionalDocumentAdded(additionalDocumentInfo); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId additionalDocumentId) { _workspace.OnAdditionalDocumentRemoved(additionalDocumentId); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext) { _workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader) { _workspace.OnAdditionalDocumentClosed(documentId, loader); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnAdditionalDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost2.OnHasAllInformation(ProjectId projectId, bool hasAllInformation) { _workspace.OnHasAllInformationChanged(projectId, hasAllInformation); } void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange() { UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true); } void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange() { var solutionId = _workspace.CurrentSolution.Id; _workspace.ProjectTracker.UpdateSolutionProperties(solutionId); RegisterPrimarySolutionForPersistentStorage(solutionId); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using ALinq; using ALinq.Mapping; using System.Data.SqlClient; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace ALinq.SqlClient { /// <summary> /// Contains functionality to connect to and communicate with a SQL Server 2000. /// </summary> public sealed class Sql2000Provider : SqlProvider, IProvider { private string dbName; private bool deleted; /// <summary> /// Initializes a new instance of the ALinq.SqlClient.Sql2000Provider class. /// </summary> public Sql2000Provider() : base(ProviderMode.Sql2000) { } void IProvider.Initialize(IDataServices dataServices, object connection) { DbConnection connection2; Type type; if (dataServices == null) { throw Error.ArgumentNull("dataServices"); } this.services = dataServices; DbTransaction transaction = null; var fileOrServerOrConnectionString = connection as string; if (fileOrServerOrConnectionString != null) { string connectionString = GetConnectionString(fileOrServerOrConnectionString); dbName = GetDatabaseName(connectionString); if (this.dbName.EndsWith(".sdf", StringComparison.OrdinalIgnoreCase)) { this.Mode = ProviderMode.SqlCE; } if (this.Mode == ProviderMode.SqlCE) { DbProviderFactory provider = GetProvider("System.Data.SqlServerCe.3.5"); if (provider == null) { throw Error.ProviderNotInstalled(this.dbName, "System.Data.SqlServerCe.3.5"); } connection2 = provider.CreateConnection(); } else { connection2 = new SqlConnection(); } connection2.ConnectionString = connectionString; } else { transaction = connection as SqlTransaction; if ((transaction == null) && (connection.GetType().FullName == "System.Data.SqlServerCe.SqlCeTransaction")) { transaction = connection as DbTransaction; } if (transaction != null) { connection = transaction.Connection; } connection2 = connection as DbConnection; if (connection2 == null) { throw Error.InvalidConnectionArgument("connection"); } if (connection2.GetType().FullName == "System.Data.SqlServerCe.SqlCeConnection") { this.Mode = ProviderMode.SqlCE; } this.dbName = this.GetDatabaseName(connection2.ConnectionString); } using (DbCommand command = connection2.CreateCommand()) { this.CommandTimeout = command.CommandTimeout; } int maxUsers = 1; if (connection2.ConnectionString.Contains("MultipleActiveResultSets")) { var builder = new DbConnectionStringBuilder { ConnectionString = connection2.ConnectionString }; if (string.Compare((string)builder["MultipleActiveResultSets"], "true", StringComparison.OrdinalIgnoreCase) == 0) { maxUsers = 10; } } conManager = new SqlConnectionManager(this, connection2, maxUsers); if (transaction != null) { conManager.Transaction = transaction; } if (Mode == ProviderMode.SqlCE) { type = connection2.GetType().Module.GetType("System.Data.SqlServerCe.SqlCeDataReader"); } else if (connection2 is SqlConnection) { type = typeof(SqlDataReader); } else { type = typeof(DbDataReader); } readerCompiler = new ObjectReaderCompiler(type, services); //InvokeIProviderMethod("Initialize", new[] { SourceService(conManager.Connection), connection }); } private string GetConnectionString(string fileOrServerOrConnectionString) { if (fileOrServerOrConnectionString.IndexOf('=') >= 0) { return fileOrServerOrConnectionString; } var builder = new DbConnectionStringBuilder(); if (fileOrServerOrConnectionString.EndsWith(".mdf", StringComparison.OrdinalIgnoreCase)) { builder.Add("AttachDBFileName", fileOrServerOrConnectionString); builder.Add("Server", @"localhost\sqlexpress"); builder.Add("Integrated Security", "SSPI"); builder.Add("User Instance", "true"); builder.Add("MultipleActiveResultSets", "true"); } else if (fileOrServerOrConnectionString.EndsWith(".sdf", StringComparison.OrdinalIgnoreCase)) { builder.Add("Data Source", fileOrServerOrConnectionString); } else { builder.Add("Server", fileOrServerOrConnectionString); builder.Add("Database", this.services.Model.DatabaseName); builder.Add("Integrated Security", "SSPI"); } return builder.ToString(); } private string GetDatabaseName(string constr) { var builder = new DbConnectionStringBuilder { ConnectionString = constr }; if (builder.ContainsKey("Initial Catalog")) { return (string)builder["Initial Catalog"]; } if (builder.ContainsKey("Database")) { return (string)builder["Database"]; } if (builder.ContainsKey("AttachDBFileName")) { return (string)builder["AttachDBFileName"]; } if (builder.ContainsKey("Data Source") && ((string)builder["Data Source"]).EndsWith(".sdf", StringComparison.OrdinalIgnoreCase)) { return (string)builder["Data Source"]; } return this.services.Model.DatabaseName; } private static DbProviderFactory GetProvider(string providerName) { if ( DbProviderFactories.GetFactoryClasses().Rows.OfType<DataRow>() .Select(r => (string)r["InvariantName"]) .Contains(providerName, StringComparer.OrdinalIgnoreCase)) { return DbProviderFactories.GetFactory(providerName); } return null; } bool IProvider.DatabaseExists() { this.CheckDispose(); this.CheckInitialized(); if (this.deleted) { return false; } bool flag = false; if (this.Mode == ProviderMode.SqlCE) { return File.Exists(this.dbName); } string connectionString = this.conManager.Connection.ConnectionString; try { this.conManager.UseConnection(this); this.conManager.Connection.ChangeDatabase(this.dbName); this.conManager.ReleaseConnection(this); flag = true; } catch (Exception) { } finally { if ((this.conManager.Connection.State == ConnectionState.Closed) && (string.Compare(this.conManager.Connection.ConnectionString, connectionString, StringComparison.Ordinal) != 0)) { this.conManager.Connection.ConnectionString = connectionString; } } return flag; } internal override QueryConverter CreateQueryConverter(SqlFactory sql) { return new SqlQueryConverter(services, typeProvider, translator, sql) { ConverterStrategy = ConverterStrategy.CanUseJoinOn | ConverterStrategy.CanUseRowStatus | ConverterStrategy.CanUseScopeIdentity }; } internal override DbFormatter CreateSqlFormatter() { return new MsSqlFormatter(this); } void IProvider.CreateDatabase() { var SqlBuilder = new SqlBuilder(SqlIdentifier); object obj3; this.CheckDispose(); this.CheckInitialized(); string dbName = null; string str2 = null; var builder = new DbConnectionStringBuilder(); builder.ConnectionString = this.conManager.Connection.ConnectionString; if (this.conManager.Connection.State != ConnectionState.Closed) { object obj4; if ((this.Mode == ProviderMode.SqlCE) && File.Exists(this.dbName)) { throw Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(this.dbName); } if (builder.TryGetValue("Initial Catalog", out obj4)) { dbName = obj4.ToString(); } if (builder.TryGetValue("Database", out obj4)) { dbName = obj4.ToString(); } if (builder.TryGetValue("AttachDBFileName", out obj4)) { str2 = obj4.ToString(); } goto Label_01D2; } if (this.Mode == ProviderMode.SqlCE) { if (!File.Exists(this.dbName)) { Type type = this.conManager.Connection.GetType().Module.GetType("System.Data.SqlServerCe.SqlCeEngine"); object target = Activator.CreateInstance(type, new object[] { builder.ToString() }); try { type.InvokeMember("CreateDatabase", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, target, new object[0], CultureInfo.InvariantCulture); goto Label_0153; } catch (TargetInvocationException exception) { throw exception.InnerException; } finally { IDisposable disposable = target as IDisposable; if (disposable != null) { disposable.Dispose(); } } } throw Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(this.dbName); } if (builder.TryGetValue("Initial Catalog", out obj3)) { dbName = obj3.ToString(); builder.Remove("Initial Catalog"); } if (builder.TryGetValue("Database", out obj3)) { dbName = obj3.ToString(); builder.Remove("Database"); } if (builder.TryGetValue("AttachDBFileName", out obj3)) { str2 = obj3.ToString(); builder.Remove("AttachDBFileName"); } Label_0153: this.conManager.Connection.ConnectionString = builder.ToString(); Label_01D2: if (string.IsNullOrEmpty(dbName)) { if (string.IsNullOrEmpty(str2)) { if (string.IsNullOrEmpty(this.dbName)) { throw Error.CouldNotDetermineCatalogName(); } dbName = this.dbName; } else { dbName = Path.GetFullPath(str2); } } this.conManager.UseConnection(this); this.conManager.AutoClose = false; try { if (this.services.Model.GetTables().FirstOrDefault<MetaTable>() == null) { throw Error.CreateDatabaseFailedBecauseOfContextWithNoTables(this.services.Model.DatabaseName); } this.deleted = false; if (this.Mode == ProviderMode.SqlCE) { foreach (MetaTable table in this.services.Model.GetTables()) { string createTableCommand = SqlBuilder.GetCreateTableCommand(table); if (!string.IsNullOrEmpty(createTableCommand)) { this.ExecuteCommand(createTableCommand); } } foreach (MetaTable table2 in this.services.Model.GetTables()) { foreach (string str4 in SqlBuilder.GetCreateForeignKeyCommands(table2)) { if (!string.IsNullOrEmpty(str4)) { this.ExecuteCommand(str4); } } } } else { string command = SqlBuilder.GetCreateDatabaseCommand(dbName, str2, Path.ChangeExtension(str2, ".ldf")); this.ExecuteCommand(command); this.conManager.Connection.ChangeDatabase(dbName); if (this.Mode == ProviderMode.Sql2005) { HashSet<string> set = new HashSet<string>(); foreach (MetaTable table3 in this.services.Model.GetTables()) { string createSchemaForTableCommand = SqlBuilder.GetCreateSchemaForTableCommand(table3); if (!string.IsNullOrEmpty(createSchemaForTableCommand)) { set.Add(createSchemaForTableCommand); } } foreach (string str7 in set) { this.ExecuteCommand(str7); } } StringBuilder builder2 = new StringBuilder(); foreach (MetaTable table4 in this.services.Model.GetTables()) { string str8 = SqlBuilder.GetCreateTableCommand(table4); if (!string.IsNullOrEmpty(str8)) { builder2.AppendLine(str8); } } foreach (MetaTable table5 in this.services.Model.GetTables()) { foreach (string str9 in SqlBuilder.GetCreateForeignKeyCommands(table5)) { if (!string.IsNullOrEmpty(str9)) { builder2.AppendLine(str9); } } } if (builder2.Length > 0) { builder2.Insert(0, "SET ARITHABORT ON" + Environment.NewLine); this.ExecuteCommand(builder2.ToString()); } } } finally { this.conManager.ReleaseConnection(this); if (this.conManager.Connection is SqlConnection) { SqlConnection.ClearAllPools(); } } } void IProvider.DeleteDatabase() { var SqlBuilder = new SqlBuilder(SqlIdentifier); this.CheckDispose(); this.CheckInitialized(); if (!this.deleted) { if (this.Mode == ProviderMode.SqlCE) { ((IProvider)this).ClearConnection(); File.Delete(this.dbName); this.deleted = true; } else { string connectionString = this.conManager.Connection.ConnectionString; IDbConnection connection = this.conManager.UseConnection(this); try { connection.ChangeDatabase("MASTER"); if (connection is SqlConnection) { SqlConnection.ClearAllPools(); } if (this.Log != null) { this.Log.WriteLine(Strings.LogAttemptingToDeleteDatabase(this.dbName)); } this.ExecuteCommand(SqlBuilder.GetDropDatabaseCommand(this.dbName)); this.deleted = true; } finally { this.conManager.ReleaseConnection(this); if ((this.conManager.Connection.State == ConnectionState.Closed) && (string.Compare(this.conManager.Connection.ConnectionString, connectionString, StringComparison.Ordinal) != 0)) { this.conManager.Connection.ConnectionString = connectionString; } } } } } private void ExecuteCommand(string command) { if (this.Log != null) { this.Log.WriteLine(command); this.Log.WriteLine(); } IDbCommand command2 = this.conManager.Connection.CreateCommand(); command2.CommandTimeout = this.CommandTimeout; command2.Transaction = this.conManager.Transaction; command2.CommandText = command; command2.ExecuteNonQuery(); } internal override ITypeSystemProvider CreateTypeSystemProvider() { return new SqlTypeSystem.Sql2000Provider(); } } }
using System; using System.Collections; using System.Diagnostics; using System.Threading; using BlogServer.XmlRpc; namespace BlogServer.Model { public abstract class Blog { protected ArrayList _postList = new ArrayList(); protected Hashtable _postTable = new Hashtable(); private readonly ReaderWriterLock _rwLock = new ReaderWriterLock(); protected BlogPersist GetBlogPersist() { using (Lock(false)) { return new BlogPersist((BlogPost[]) _postList.ToArray(typeof(BlogPost))); } } protected void Add(params BlogPost[] posts) { foreach (BlogPost post in posts) { if (post.Id == null) throw new ArgumentException("One or more posts had a null ID"); if (_postTable.ContainsKey(post.Id)) throw new InvalidOperationException("Duplicate post ID detected: " + post.Id); _postTable.Add(post.Id, post); _postList.Add(post); } } public BlogPost this[int index] { get { BlogPost blogPost; using (Lock(false)) blogPost = (BlogPost) _postList[index]; if (blogPost != null) blogPost = blogPost.Clone(); return blogPost; } } public BlogPost this[string postId] { get { BlogPost blogPost; using (Lock(false)) blogPost = (BlogPost) _postTable[postId]; if (blogPost != null) blogPost = blogPost.Clone(); return blogPost; } } public int Count { get { using (Lock(false)) return _postList.Count; } } public BlogPost[] GetRecentPosts(int numberOfPosts) { ArrayList results = new ArrayList(); using (Lock(false)) { numberOfPosts = Math.Min(numberOfPosts, Count); for (int i = 0; i < numberOfPosts; i++) results.Add(this[Count - i - 1].Clone()); } return (BlogPost[]) results.ToArray(typeof (BlogPost)); } public BlogPost[] GetRecentPublishedPosts(int numberOfPosts) { ArrayList results = new ArrayList(); using (Lock(false)) { for (int i = 0; i < Count && results.Count < numberOfPosts; i++) { BlogPost post = this[Count - i - 1]; if (post.Published) results.Add(post.Clone()); } } return (BlogPost[]) results.ToArray(typeof (BlogPost)); } protected abstract void Persist(); public bool Contains(string postid) { using (Lock(false)) { return _postTable.ContainsKey(postid); } } public string CreateBlogPost(BlogPost newPost) { string newId = Guid.NewGuid().ToString("d"); newPost.Id = newId; using (Lock(true)) { Add(newPost.Clone()); } return newId; } public void UpdateBlogPost(BlogPost existingPost) { using (Lock(true)) { if (!_postTable.ContainsKey(existingPost.Id)) throw new XmlRpcServerException(404, "Cannot edit a post that doesn't exist (was it deleted?)"); // pass-by-value semantics BlogPost clone = existingPost.Clone(); _postTable[existingPost.Id] = clone; for (int i = 0; i < _postList.Count; i++) { if (((BlogPost) _postList[i]).Id == clone.Id) { _postList[i] = clone; break; } } } } private IDisposable Lock(bool write) { if (write) _rwLock.AcquireWriterLock(Timeout.Infinite); else _rwLock.AcquireReaderLock(Timeout.Infinite); return new LockReleaser(this, write); } private class LockReleaser : IDisposable { private readonly Blog _blog; private readonly bool _write; public LockReleaser(Blog blog, bool write) { _blog = blog; _write = write; } public void Dispose() { if (_write) { _blog.Persist(); _blog._rwLock.ReleaseWriterLock(); } else _blog._rwLock.ReleaseReaderLock(); } } public class BlogPersist { private BlogPost[] _blogPosts; public BlogPersist() { } public BlogPersist(BlogPost[] blogPosts) { _blogPosts = blogPosts; } public BlogPost[] BlogPosts { get { return _blogPosts; } set { _blogPosts = value; } } } public bool DeleteBlogPost(string postid) { using (Lock(true)) { if (_postTable.ContainsKey(postid)) { BlogPost post = (BlogPost) _postTable[postid]; Debug.Assert(_postList.Contains(post)); _postList.Remove(post); _postTable.Remove(postid); return true; } return false; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Strings; using Umbraco.Extensions; namespace Umbraco.Cms.Core.IO { public abstract class IOHelper : IIOHelper { private readonly IHostingEnvironment _hostingEnvironment; public IOHelper(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment)); } // static compiled regex for faster performance //private static readonly Regex ResolveUrlPattern = new Regex("(=[\"\']?)(\\W?\\~(?:.(?![\"\']?\\s+(?:\\S+)=|[>\"\']))+.)[\"\']?", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); //helper to try and match the old path to a new virtual one public string FindFile(string virtualPath) { string retval = virtualPath; if (virtualPath.StartsWith("~")) retval = virtualPath.Replace("~", _hostingEnvironment.ApplicationVirtualPath); if (virtualPath.StartsWith("/") && !PathStartsWith(virtualPath, _hostingEnvironment.ApplicationVirtualPath)) retval = _hostingEnvironment.ApplicationVirtualPath + "/" + virtualPath.TrimStart(Constants.CharArrays.ForwardSlash); return retval; } // TODO: This is the same as IHostingEnvironment.ToAbsolute - marked as obsolete in IIOHelper for now public string ResolveUrl(string virtualPath) { if (string.IsNullOrWhiteSpace(virtualPath)) return virtualPath; return _hostingEnvironment.ToAbsolute(virtualPath); } public string MapPath(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); // Check if the path is already mapped - TODO: This should be switched to Path.IsPathFullyQualified once we are on Net Standard 2.1 if (IsPathFullyQualified(path)) { return path; } if (_hostingEnvironment.IsHosted) { var result = (!string.IsNullOrEmpty(path) && (path.StartsWith("~") || PathStartsWith(path, _hostingEnvironment.ApplicationVirtualPath))) ? _hostingEnvironment.MapPathWebRoot(path) : _hostingEnvironment.MapPathWebRoot("~/" + path.TrimStart(Constants.CharArrays.ForwardSlash)); if (result != null) return result; } var dirSepChar = Path.DirectorySeparatorChar; var root = Assembly.GetExecutingAssembly().GetRootDirectorySafe(); var newPath = path.TrimStart(Constants.CharArrays.TildeForwardSlash).Replace('/', dirSepChar); var retval = root + dirSepChar.ToString(CultureInfo.InvariantCulture) + newPath; return retval; } /// <summary> /// Returns true if the path has a root, and is considered fully qualified for the OS it is on /// See https://github.com/dotnet/runtime/blob/30769e8f31b20be10ca26e27ec279cd4e79412b9/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs#L281 for the .NET Standard 2.1 version of this /// </summary> /// <param name="path">The path to check</param> /// <returns>True if the path is fully qualified, false otherwise</returns> public abstract bool IsPathFullyQualified(string path); /// <summary> /// Verifies that the current filepath matches a directory where the user is allowed to edit a file. /// </summary> /// <param name="filePath">The filepath to validate.</param> /// <param name="validDir">The valid directory.</param> /// <returns>A value indicating whether the filepath is valid.</returns> public bool VerifyEditPath(string filePath, string validDir) { return VerifyEditPath(filePath, new[] { validDir }); } /// <summary> /// Verifies that the current filepath matches one of several directories where the user is allowed to edit a file. /// </summary> /// <param name="filePath">The filepath to validate.</param> /// <param name="validDirs">The valid directories.</param> /// <returns>A value indicating whether the filepath is valid.</returns> public bool VerifyEditPath(string filePath, IEnumerable<string> validDirs) { // this is called from ScriptRepository, PartialViewRepository, etc. // filePath is the fullPath (rooted, filesystem path, can be trusted) // validDirs are virtual paths (eg ~/Views) // // except that for templates, filePath actually is a virtual path // TODO: what's below is dirty, there are too many ways to get the root dir, etc. // not going to fix everything today var mappedRoot = MapPath(_hostingEnvironment.ApplicationVirtualPath); if (!PathStartsWith(filePath, mappedRoot)) { // TODO this is going to fail.. Scripts Stylesheets need to use WebRoot, PartialViews need to use ContentRoot filePath = _hostingEnvironment.MapPathWebRoot(filePath); } // yes we can (see above) //// don't trust what we get, it may contain relative segments //filePath = Path.GetFullPath(filePath); foreach (var dir in validDirs) { var validDir = dir; if (!PathStartsWith(validDir, mappedRoot)) validDir = _hostingEnvironment.MapPathWebRoot(validDir); if (PathStartsWith(filePath, validDir)) return true; } return false; } /// <summary> /// Verifies that the current filepath has one of several authorized extensions. /// </summary> /// <param name="filePath">The filepath to validate.</param> /// <param name="validFileExtensions">The valid extensions.</param> /// <returns>A value indicating whether the filepath is valid.</returns> public bool VerifyFileExtension(string filePath, IEnumerable<string> validFileExtensions) { var ext = Path.GetExtension(filePath); return ext != null && validFileExtensions.Contains(ext.TrimStart(Constants.CharArrays.Period)); } public abstract bool PathStartsWith(string path, string root, params char[] separators); public void EnsurePathExists(string path) { var absolutePath = MapPath(path); if (Directory.Exists(absolutePath) == false) Directory.CreateDirectory(absolutePath); } /// <summary> /// Get properly formatted relative path from an existing absolute or relative path /// </summary> /// <param name="path"></param> /// <returns></returns> public string GetRelativePath(string path) { if (path.IsFullPath()) { var rootDirectory = MapPath("~"); var relativePath = PathStartsWith(path, rootDirectory) ? path.Substring(rootDirectory.Length) : path; path = relativePath; } return PathUtility.EnsurePathIsApplicationRootPrefixed(path); } /// <summary> /// Retrieves array of temporary folders from the hosting environment. /// </summary> /// <returns>Array of <see cref="DirectoryInfo"/> instances.</returns> public DirectoryInfo[] GetTempFolders() { var tempFolderPaths = new[] { _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.TempFileUploads) }; foreach (var tempFolderPath in tempFolderPaths) { // Ensure it exists Directory.CreateDirectory(tempFolderPath); } return tempFolderPaths.Select(x => new DirectoryInfo(x)).ToArray(); } /// <summary> /// Cleans contents of a folder by deleting all files older that the provided age. /// If deletition of any file errors (e.g. due to a file lock) the process will continue to try to delete all that it can. /// </summary> /// <param name="folder">Folder to clean.</param> /// <param name="age">Age of files within folder to delete.</param> /// <returns>Result of operation.</returns> public CleanFolderResult CleanFolder(DirectoryInfo folder, TimeSpan age) { folder.Refresh(); // In case it's changed during runtime. if (!folder.Exists) { return CleanFolderResult.FailedAsDoesNotExist(); } var files = folder.GetFiles("*.*", SearchOption.AllDirectories); var errors = new List<CleanFolderResult.Error>(); foreach (var file in files) { if (DateTime.UtcNow - file.LastWriteTimeUtc > age) { try { file.IsReadOnly = false; file.Delete(); } catch (Exception ex) { errors.Add(new CleanFolderResult.Error(ex, file)); } } } return errors.Any() ? CleanFolderResult.FailedWithErrors(errors) : CleanFolderResult.Success(); } } }
using System; using System.Collections; using sys = System; namespace GuruComponents.CodeEditor.Library.Drawing.ImageInfo { ///<summary>This Class retrives Image Properties using Image.GetPropertyItem() method /// and gives access to some of them trough its public properties. Or to all of them /// trough its public property PropertyItems. ///</summary> public class Info { ///<summary>Wenn using this constructor the Image property must be set before accessing properties.</summary> public Info() { } ///<summary>Creates Info Class to read properties of an Image given from a file.</summary> /// <param name="imageFileName">A string specifiing image file name on a file system.</param> public Info(string imageFileName) { _image = sys.Drawing.Image.FromFile(imageFileName); } ///<summary>Creates Info Class to read properties of a given Image object.</summary> /// <param name="anImage">An Image object to analise.</param> public Info(sys.Drawing.Image anImage) { _image = anImage; } sys.Drawing.Image _image; ///<summary>Sets or returns the current Image object.</summary> public sys.Drawing.Image Image { set{_image = value;} get{return _image;} } ///<summary> /// Type is PropertyTagTypeShort or PropertyTagTypeLong ///Information specific to compressed data. When a compressed file is recorded, the valid width of the meaningful image must be recorded in this tag, whether or not there is padding data or a restart marker. This tag should not exist in an uncompressed file. /// </summary> public uint PixXDim { get { object tmpValue = PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifPixXDim)); if (tmpValue.GetType().ToString().Equals("System.UInt16")) return (uint)(ushort)tmpValue; return (uint)tmpValue; } } ///<summary> /// Type is PropertyTagTypeShort or PropertyTagTypeLong /// Information specific to compressed data. When a compressed file is recorded, the valid height of the meaningful image must be recorded in this tag whether or not there is padding data or a restart marker. This tag should not exist in an uncompressed file. Because data padding is unnecessary in the vertical direction, the number of lines recorded in this valid image height tag will be the same as that recorded in the SOF. /// </summary> public uint PixYDim { get { object tmpValue = PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifPixYDim)); if (tmpValue.GetType().ToString().Equals("System.UInt16")) return (uint)(ushort)tmpValue; return (uint)tmpValue; } } ///<summary> ///Number of pixels per unit in the image width (x) direction. The unit is specified by PropertyTagResolutionUnit ///</summary> public Fraction XResolution { get { return (Fraction) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.XResolution)); } } ///<summary> ///Number of pixels per unit in the image height (y) direction. The unit is specified by PropertyTagResolutionUnit. ///</summary> public Fraction YResolution { get { return (Fraction) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.YResolution )); } } ///<summary> ///Unit of measure for the horizontal resolution and the vertical resolution. ///2 - inch 3 - centimeter ///</summary> public ResolutionUnit ResolutionUnit { get { return (ResolutionUnit) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ResolutionUnit )); } } ///<summary> ///Brightness value. The unit is the APEX value. Ordinarily it is given in the range of -99.99 to 99.99. ///</summary> public Fraction Brightness { get { return (Fraction) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifBrightness)); } } ///<summary> /// The manufacturer of the equipment used to record the image. ///</summary> public string EquipMake { get { return (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.EquipMake)); } } ///<summary> /// The model name or model number of the equipment used to record the image. /// </summary> public string EquipModel { get { return (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.EquipModel)); } } ///<summary> ///Copyright information. ///</summary> public string Copyright { get { return (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.Copyright)); } } ///<summary> ///Date and time the image was created. ///</summary> public string DateTime { get { return (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.DateTime)); } } //The format is YYYY:MM:DD HH:MM:SS with time shown in 24-hour format and the date and time separated by one blank character (0x2000). The character string length is 20 bytes including the NULL terminator. When the field is empty, it is treated as unknown. private static DateTime ExifDTToDateTime(string exifDT) { exifDT = exifDT.Replace(' ', ':'); string[] ymdhms = exifDT.Split(':'); int years = int.Parse(ymdhms[0]); int months = int.Parse(ymdhms[1]); int days = int.Parse(ymdhms[2]); int hours = int.Parse(ymdhms[3]); int minutes = int.Parse(ymdhms[4]); int seconds = int.Parse(ymdhms[5]); return new DateTime(years, months, days, hours, minutes, seconds); } ///<summary> ///Date and time when the original image data was generated. For a DSC, the date and time when the picture was taken. ///</summary> public DateTime DTOrig { get { string tmpStr = (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifDTOrig)); return ExifDTToDateTime(tmpStr); } } ///<summary> ///Date and time when the image was stored as digital data. If, for example, an image was captured by DSC and at the same time the file was recorded, then DateTimeOriginal and DateTimeDigitized will have the same contents. ///</summary> public DateTime DTDigitized { get { string tmpStr = (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifDTDigitized)); return ExifDTToDateTime(tmpStr); } } ///<summary> ///ISO speed and ISO latitude of the camera or input device as specified in ISO 12232. ///</summary> public ushort ISOSpeed { get { return (ushort) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifISOSpeed)); } } ///<summary> ///Image orientation viewed in terms of rows and columns. ///</summary> public Orientation Orientation { get { return (Orientation) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.Orientation)); } } ///<summary> ///Actual focal length, in millimeters, of the lens. Conversion is not made to the focal length of a 35 millimeter film camera. ///</summary> public Fraction FocalLength { get { return (Fraction) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifFocalLength)); } } ///<summary> ///F number. ///</summary> public Fraction FNumber { get { return (Fraction) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifFNumber)); } } ///<summary> ///Class of the program used by the camera to set exposure when the picture is taken. ///</summary> public ExposureProg ExposureProg { get { return (ExposureProg) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifExposureProg)); } } ///<summary> ///Metering mode. ///</summary> public MeteringMode MeteringMode { get { return (MeteringMode) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifMeteringMode)); } } private Hashtable _propertyItems; ///<summary> /// Returns a Hashtable of all available Properties of a gieven Image. Keys of this Hashtable are /// Display names of the Property Tags and values are transformed (typed) data. ///</summary> /// <example> /// <code> /// if (openFileDialog.ShowDialog()==DialogResult.OK) /// { /// Info inf=new Info(Image.FromFile(openFileDialog.FileName)); /// listView.Items.Clear(); /// foreach (string propertyname in inf.PropertyItems.Keys) /// { /// ListViewItem item1 = new ListViewItem(propertyname,0); /// item1.SubItems.Add((inf.PropertyItems[propertyname]).ToString()); /// listView.Items.Add(item1); /// } /// } /// </code> ///</example> public Hashtable PropertyItems { get { if (_propertyItems==null) { _propertyItems= new Hashtable(); foreach(int id in _image.PropertyIdList) _propertyItems[((PropertyTagId)id).ToString()]=PropertyTag.getValue(_image.GetPropertyItem(id)); } return _propertyItems; } } } }
//------------------------------------------------------------------------------ // <copyright file="DataList.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Web; using System.Web.UI; using System.Web.Util; /// <devdoc> /// <para> /// Creates /// a control to display a data-bound list. /// </para> /// </devdoc> [ ControlValueProperty("SelectedValue"), Editor("System.Web.UI.Design.WebControls.DataListComponentEditor, " + AssemblyRef.SystemDesign, typeof(ComponentEditor)), Designer("System.Web.UI.Design.WebControls.DataListDesigner, " + AssemblyRef.SystemDesign) ] public class DataList : BaseDataList, INamingContainer, IRepeatInfoUser, IWizardSideBarListControl { private static readonly object EventItemCreated = new object(); private static readonly object EventItemDataBound = new object(); private static readonly object EventItemCommand = new object(); private static readonly object EventEditCommand = new object(); private static readonly object EventUpdateCommand = new object(); private static readonly object EventCancelCommand = new object(); private static readonly object EventDeleteCommand = new object(); private static readonly object EventWizardListItemDataBound = new object(); /// <devdoc> /// <para>Specifies the <see langword='Select'/> command. This field is constant.</para> /// </devdoc> public const string SelectCommandName = "Select"; /// <devdoc> /// <para>Specifies the <see langword='Edit'/> command. This field is constant</para> /// </devdoc> public const string EditCommandName = "Edit"; /// <devdoc> /// <para>Specifies the <see langword='Update'/> command. This field is constant</para> /// </devdoc> public const string UpdateCommandName = "Update"; /// <devdoc> /// <para>Specifies the <see langword='Cancel'/> command. This field is constant</para> /// </devdoc> public const string CancelCommandName = "Cancel"; /// <devdoc> /// <para>Specifies the <see langword='Delete'/> command. This field is constant</para> /// </devdoc> public const string DeleteCommandName = "Delete"; private TableItemStyle itemStyle; private TableItemStyle alternatingItemStyle; private TableItemStyle selectedItemStyle; private TableItemStyle editItemStyle; private TableItemStyle separatorStyle; private TableItemStyle headerStyle; private TableItemStyle footerStyle; private ITemplate itemTemplate; private ITemplate alternatingItemTemplate; private ITemplate selectedItemTemplate; private ITemplate editItemTemplate; private ITemplate separatorTemplate; private ITemplate headerTemplate; private ITemplate footerTemplate; private bool extractTemplateRows; private ArrayList itemsArray; private DataListItemCollection itemsCollection; private int offset; private int visibleItemCount = -1; /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Web.UI.WebControls.DataList'/> class. /// </para> /// </devdoc> public DataList() { offset = 0; visibleItemCount = -1; } /// <devdoc> /// <para>Gets the style properties for alternating items in the <see cref='System.Web.UI.WebControls.DataList'/>. This /// property is read-only. </para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), WebSysDescription(SR.DataList_AlternatingItemStyle) ] public virtual TableItemStyle AlternatingItemStyle { get { if (alternatingItemStyle == null) { alternatingItemStyle = new TableItemStyle(); if (IsTrackingViewState) ((IStateManager)alternatingItemStyle).TrackViewState(); } return alternatingItemStyle; } } /// <devdoc> /// <para>Indicates the template to use for alternating items in the <see cref='System.Web.UI.WebControls.DataList'/>.</para> /// </devdoc> [ Browsable(false), DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(DataListItem)), WebSysDescription(SR.DataList_AlternatingItemTemplate) ] public virtual ITemplate AlternatingItemTemplate { get { return alternatingItemTemplate; } set { alternatingItemTemplate = value; } } /// <devdoc> /// <para>Indicates the ordinal index of the item to be edited.</para> /// </devdoc> [ WebCategory("Default"), DefaultValue(-1), WebSysDescription(SR.DataList_EditItemIndex) ] public virtual int EditItemIndex { get { object o = ViewState["EditItemIndex"]; if (o != null) { return (int)o; } return -1; } set { if (value < -1) { throw new ArgumentOutOfRangeException("value"); } ViewState["EditItemIndex"] = value; } } /// <devdoc> /// <para>Indicates the style properties of the item to be edited.</para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), WebSysDescription(SR.DataList_EditItemStyle) ] public virtual TableItemStyle EditItemStyle { get { if (editItemStyle == null) { editItemStyle = new TableItemStyle(); if (IsTrackingViewState) ((IStateManager)editItemStyle).TrackViewState(); } return editItemStyle; } } /// <devdoc> /// <para>Indicates the template to use for an item set in edit mode within the <see cref='System.Web.UI.WebControls.DataList'/>.</para> /// </devdoc> [ Browsable(false), DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(DataListItem)), WebSysDescription(SR.DataList_EditItemTemplate) ] public virtual ITemplate EditItemTemplate { get { return editItemTemplate; } set { editItemTemplate = value; } } /// <devdoc> /// <para>Indicates whether to extract template rows.</para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(false), WebSysDescription(SR.DataList_ExtractTemplateRows) ] public virtual bool ExtractTemplateRows { get { object o = ViewState["ExtractTemplateRows"]; if (o != null) return(bool)o; return false; } set { ViewState["ExtractTemplateRows"] = value; } } /// <devdoc> /// <para>Gets the style properties of the footer item.</para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), WebSysDescription(SR.DataControls_FooterStyle) ] public virtual TableItemStyle FooterStyle { get { if (footerStyle == null) { footerStyle = new TableItemStyle(); if (IsTrackingViewState) ((IStateManager)footerStyle).TrackViewState(); } return footerStyle; } } /// <devdoc> /// <para> Indicates the template to use for the footer in the <see cref='System.Web.UI.WebControls.DataList'/>.</para> /// </devdoc> [ Browsable(false), DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(DataListItem)), WebSysDescription(SR.DataList_FooterTemplate) ] public virtual ITemplate FooterTemplate { get { return footerTemplate; } set { footerTemplate = value; } } /// <devdoc> /// <para>Indicates a value that specifies the grid line style.</para> /// </devdoc> [ DefaultValue(GridLines.None) ] public override GridLines GridLines { get { if (ControlStyleCreated == false) { return GridLines.None; } return ((TableStyle)ControlStyle).GridLines; } set { base.GridLines = value; } } /// <devdoc> /// <para>Gets the style properties of the header item.</para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), WebSysDescription(SR.DataControls_HeaderStyle) ] public virtual TableItemStyle HeaderStyle { get { if (headerStyle == null) { headerStyle = new TableItemStyle(); if (IsTrackingViewState) ((IStateManager)headerStyle).TrackViewState(); } return headerStyle; } } /// <devdoc> /// <para>Indicates the template to use for the header in the <see cref='System.Web.UI.WebControls.DataList'/>.</para> /// </devdoc> [ Browsable(false), DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(DataListItem)), WebSysDescription(SR.DataList_HeaderTemplate) ] public virtual ITemplate HeaderTemplate { get { return headerTemplate; } set { headerTemplate = value; } } /// <devdoc> /// <para>Gets a collection of <see cref='System.Web.UI.WebControls.DataListItem'/> objects representing the individual /// items within the control.</para> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), WebSysDescription(SR.DataList_Items) ] public virtual DataListItemCollection Items { get { if (itemsCollection == null) { if (itemsArray == null) { EnsureChildControls(); } if (itemsArray == null) { itemsArray = new ArrayList(); } itemsCollection = new DataListItemCollection(itemsArray); } return itemsCollection; } } /// <devdoc> /// <para>Indicates the style properties of the individual items.</para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), WebSysDescription(SR.DataList_ItemStyle) ] public virtual TableItemStyle ItemStyle { get { if (itemStyle == null) { itemStyle = new TableItemStyle(); if (IsTrackingViewState) ((IStateManager)itemStyle).TrackViewState(); } return itemStyle; } } /// <devdoc> /// <para>Indicates the template to use for an item in the <see cref='System.Web.UI.WebControls.DataList'/>.</para> /// </devdoc> [ Browsable(false), DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(DataListItem)), WebSysDescription(SR.DataList_ItemTemplate), SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces", Justification = "Interface denotes existence of property, not used for security.") ] public virtual ITemplate ItemTemplate { get { return itemTemplate; } set { itemTemplate = value; } } /// <devdoc> /// <para>Indicates the number of columns to repeat.</para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(0), WebSysDescription(SR.DataList_RepeatColumns) ] public virtual int RepeatColumns { get { object o = ViewState["RepeatColumns"]; if (o != null) return(int)o; return 0; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } ViewState["RepeatColumns"] = value; } } /// <devdoc> /// <para>Indicates whether the control is displayed vertically or horizontally.</para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(RepeatDirection.Vertical), WebSysDescription(SR.Item_RepeatDirection) ] public virtual RepeatDirection RepeatDirection { get { object o = ViewState["RepeatDirection"]; if (o != null) return(RepeatDirection)o; return RepeatDirection.Vertical; } set { if (value < RepeatDirection.Horizontal || value > RepeatDirection.Vertical) { throw new ArgumentOutOfRangeException("value"); } ViewState["RepeatDirection"] = value; } } /// <devdoc> /// <para>Gets or sets a value that indicates whether the control is displayed in table /// or flow layout.</para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(RepeatLayout.Table), WebSysDescription(SR.WebControl_RepeatLayout) ] public virtual RepeatLayout RepeatLayout { get { object o = ViewState["RepeatLayout"]; if (o != null) return(RepeatLayout)o; return RepeatLayout.Table; } set { if ((value == RepeatLayout.UnorderedList) || (value == RepeatLayout.OrderedList)) { throw new ArgumentOutOfRangeException("value", SR.GetString(SR.DataList_LayoutNotSupported, value)); } EnumerationRangeValidationUtil.ValidateRepeatLayout(value); ViewState["RepeatLayout"] = value; } } /// <devdoc> /// <para> Indicates the index of /// the currently selected item.</para> /// </devdoc> [ Bindable(true), DefaultValue(-1), WebSysDescription(SR.WebControl_SelectedIndex), SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces", Justification = "Interface denotes existence of property, not used for security.") ] public virtual int SelectedIndex { get { object o = ViewState["SelectedIndex"]; if (o != null) { return (int)o; } return -1; } set { if (value < -1) { throw new ArgumentOutOfRangeException("value"); } int oldSelectedIndex = SelectedIndex; ViewState["SelectedIndex"] = value; if (itemsArray != null) { DataListItem item; if ((oldSelectedIndex != -1) && (itemsArray.Count > oldSelectedIndex)) { item = (DataListItem)itemsArray[oldSelectedIndex]; if (item.ItemType != ListItemType.EditItem) { ListItemType itemType = ListItemType.Item; if (oldSelectedIndex % 2 != 0) itemType = ListItemType.AlternatingItem; item.SetItemType(itemType); } } if ((value != -1) && (itemsArray.Count > value)) { item = (DataListItem)itemsArray[value]; if (item.ItemType != ListItemType.EditItem) item.SetItemType(ListItemType.SelectedItem); } } } } /// <devdoc> /// <para>Gets the selected item in the <see cref='System.Web.UI.WebControls.DataGrid'/>.</para> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), WebSysDescription(SR.DataList_SelectedItem) ] public virtual DataListItem SelectedItem { get { int index = SelectedIndex; DataListItem item = null; if (index != -1) { item = Items[index]; } return item; } } /// <devdoc> /// <para>Indicates the style properties of the currently /// selected item.</para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), WebSysDescription(SR.DataList_SelectedItemStyle) ] public virtual TableItemStyle SelectedItemStyle { get { if (selectedItemStyle == null) { selectedItemStyle = new TableItemStyle(); if (IsTrackingViewState) ((IStateManager)selectedItemStyle).TrackViewState(); } return selectedItemStyle; } } /// <devdoc> /// <para>Indicates the template to use for the currently selected item in the <see cref='System.Web.UI.WebControls.DataList'/>.</para> /// </devdoc> [ Browsable(false), DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(DataListItem)), WebSysDescription(SR.DataList_SelectedItemTemplate) ] public virtual ITemplate SelectedItemTemplate { get { return selectedItemTemplate; } set { selectedItemTemplate = value; } } [ Browsable(false) ] public object SelectedValue { get { if (DataKeyField.Length == 0) { throw new InvalidOperationException(SR.GetString(SR.DataList_DataKeyFieldMustBeSpecified, ID)); } DataKeyCollection keys = DataKeys; int selectedIndex = SelectedIndex; if (keys != null && selectedIndex < keys.Count && selectedIndex > -1) { return keys[selectedIndex]; } return null; } } /// <devdoc> /// <para>Indicates the style properties of the separator between each item in the /// <see cref='System.Web.UI.WebControls.DataList'/>.</para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), WebSysDescription(SR.DataList_SeparatorStyle) ] public virtual TableItemStyle SeparatorStyle { get { if (separatorStyle == null) { separatorStyle = new TableItemStyle(); if (IsTrackingViewState) ((IStateManager)separatorStyle).TrackViewState(); } return separatorStyle; } } /// <devdoc> /// <para>Indicates the template to use for the separator in the <see cref='System.Web.UI.WebControls.DataList'/>.</para> /// </devdoc> [ Browsable(false), DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(DataListItem)), WebSysDescription(SR.DataList_SeparatorTemplate) ] public virtual ITemplate SeparatorTemplate { get { return separatorTemplate; } set { separatorTemplate = value; } } /// <devdoc> /// <para>Gets or sets a value that specifies whether the footer is displayed in the /// <see cref='System.Web.UI.WebControls.DataList'/>.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(true), WebSysDescription(SR.DataControls_ShowFooter) ] public virtual bool ShowFooter { get { object o = ViewState["ShowFooter"]; if (o != null) return(bool)o; return true; } set { ViewState["ShowFooter"] = value; } } /// <devdoc> /// <para>Gets or sets a value that specifies whether the header is displayed in the<see cref='System.Web.UI.WebControls.DataGrid'/>.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(true), WebSysDescription(SR.DataControls_ShowHeader) ] public virtual bool ShowHeader { get { object o = ViewState["ShowHeader"]; if (o != null) return(bool)o; return true; } set { ViewState["ShowHeader"] = value; } } protected override HtmlTextWriterTag TagKey { get { return RepeatLayout == RepeatLayout.Table? HtmlTextWriterTag.Table : HtmlTextWriterTag.Span; } } /// <devdoc> /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.DataList'/> with a /// <see langword='Command'/> property of <see langword='cancel'/>.</para> /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.DataList_OnCancelCommand) ] public event DataListCommandEventHandler CancelCommand { add { Events.AddHandler(EventCancelCommand, value); } remove { Events.RemoveHandler(EventCancelCommand, value); } } /// <devdoc> /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.DataList'/> with a /// <see langword='Command'/> property of <see langword='delete'/>.</para> /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.DataList_OnDeleteCommand) ] public event DataListCommandEventHandler DeleteCommand { add { Events.AddHandler(EventDeleteCommand, value); } remove { Events.RemoveHandler(EventDeleteCommand, value); } } /// <devdoc> /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.DataList'/> with a /// <see langword='Command'/> property of <see langword='edit'/>.</para> /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.DataList_OnEditCommand) ] public event DataListCommandEventHandler EditCommand { add { Events.AddHandler(EventEditCommand, value); } remove { Events.RemoveHandler(EventEditCommand, value); } } /// <devdoc> /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.DataList'/> not covered by /// <see langword='edit'/>, <see langword='cancel'/>, <see langword='delete'/> or /// <see langword='update'/>.</para> /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.DataList_OnItemCommand) ] public event DataListCommandEventHandler ItemCommand { add { Events.AddHandler(EventItemCommand, value); } remove { Events.RemoveHandler(EventItemCommand, value); } } /// <devdoc> /// <para>Occurs on the server when a control a created.</para> /// </devdoc> [ WebCategory("Behavior"), WebSysDescription(SR.DataControls_OnItemCreated) ] public event DataListItemEventHandler ItemCreated { add { Events.AddHandler(EventItemCreated, value); } remove { Events.RemoveHandler(EventItemCreated, value); } } /// <devdoc> /// <para>Occurs when an item is data bound to the control.</para> /// </devdoc> [ WebCategory("Behavior"), WebSysDescription(SR.DataControls_OnItemDataBound) ] public event DataListItemEventHandler ItemDataBound { add { Events.AddHandler(EventItemDataBound, value); } remove { Events.RemoveHandler(EventItemDataBound, value); } } /// <devdoc> /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.DataList'/> with a /// <see langword='Command'/> property of <see langword='update'/>.</para> /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.DataList_OnUpdateCommand) ] public event DataListCommandEventHandler UpdateCommand { add { Events.AddHandler(EventUpdateCommand, value); } remove { Events.RemoveHandler(EventUpdateCommand, value); } } /// <internalonly/> /// <devdoc> /// </devdoc> protected override void CreateControlHierarchy(bool useDataSource) { IEnumerable dataSource = null; int count = -1; ArrayList keysArray = DataKeysArray; // cache this, so we don't need to go to the statebag each time extractTemplateRows = this.ExtractTemplateRows; if (itemsArray != null) { itemsArray.Clear(); } else { itemsArray = new ArrayList(); } if (useDataSource == false) { // ViewState must have a non-null value for ItemCount because we check for // this in CreateChildControls count = (int)ViewState[BaseDataList.ItemCountViewStateKey]; if (count != -1) { dataSource = new DummyDataSource(count); itemsArray.Capacity = count; } } else { keysArray.Clear(); dataSource = GetData(); ICollection collection = dataSource as ICollection; if (collection != null) { keysArray.Capacity = collection.Count; itemsArray.Capacity = collection.Count; } } if (dataSource != null) { ControlCollection controls = Controls; DataListItem item; ListItemType itemType; int index = 0; bool hasSeparators = (separatorTemplate != null); int editItemIndex = EditItemIndex; int selectedItemIndex = SelectedIndex; string keyField = DataKeyField; bool storeKeys = (useDataSource && (keyField.Length != 0)); count = 0; if (headerTemplate != null) { CreateItem(-1, ListItemType.Header, useDataSource, null); } foreach (object dataItem in dataSource) { if (storeKeys) { object keyValue = DataBinder.GetPropertyValue(dataItem, keyField); keysArray.Add(keyValue); } itemType = ListItemType.Item; if (index == editItemIndex) { itemType = ListItemType.EditItem; } else if (index == selectedItemIndex) { itemType = ListItemType.SelectedItem; } else if (index % 2 != 0) { itemType = ListItemType.AlternatingItem; } item = CreateItem(index, itemType, useDataSource, dataItem); itemsArray.Add(item); if (hasSeparators) { CreateItem(index, ListItemType.Separator, useDataSource, null); } count++; index++; } if (footerTemplate != null) { CreateItem(-1, ListItemType.Footer, useDataSource, null); } } if (useDataSource) { // save the number of items contained in the DataList for use in round-trips ViewState[BaseDataList.ItemCountViewStateKey] = ((dataSource != null) ? count : -1); } } /// <internalonly/> /// <devdoc> /// </devdoc> protected override Style CreateControlStyle() { TableStyle controlStyle = new TableStyle(); // initialize defaults that are different from TableStyle controlStyle.CellSpacing = 0; return controlStyle; } /// <devdoc> /// </devdoc> private DataListItem CreateItem(int itemIndex, ListItemType itemType, bool dataBind, object dataItem) { DataListItem item = CreateItem(itemIndex, itemType); DataListItemEventArgs e = new DataListItemEventArgs(item); InitializeItem(item); if (dataBind) { item.DataItem = dataItem; } OnItemCreated(e); Controls.Add(item); if (dataBind) { item.DataBind(); OnItemDataBound(e); item.DataItem = null; } return item; } /// <devdoc> /// </devdoc> protected virtual DataListItem CreateItem(int itemIndex, ListItemType itemType) { return new DataListItem(itemIndex, itemType); } private DataListItem GetItem(ListItemType itemType, int repeatIndex) { DataListItem item = null; switch (itemType) { case ListItemType.Header: Debug.Assert(((IRepeatInfoUser)this).HasHeader); item = (DataListItem)Controls[0]; break; case ListItemType.Footer: Debug.Assert(((IRepeatInfoUser)this).HasFooter); item = (DataListItem)Controls[Controls.Count - 1]; break; case ListItemType.Separator: Debug.Assert(((IRepeatInfoUser)this).HasSeparators); { int controlIndex = repeatIndex * 2 + 1; if (headerTemplate != null) { controlIndex++; } item = (DataListItem)Controls[controlIndex]; } break; case ListItemType.Item: case ListItemType.AlternatingItem: case ListItemType.SelectedItem: case ListItemType.EditItem: item = (DataListItem)itemsArray[repeatIndex]; break; } return item; } /// <devdoc> /// </devdoc> protected virtual void InitializeItem(DataListItem item) { ITemplate contentTemplate = itemTemplate; switch (item.ItemType) { case ListItemType.Header: contentTemplate = headerTemplate; break; case ListItemType.Footer: contentTemplate = footerTemplate; break; case ListItemType.AlternatingItem: if (alternatingItemTemplate != null) { contentTemplate = alternatingItemTemplate; } break; case ListItemType.SelectedItem: if (selectedItemTemplate != null) { contentTemplate = selectedItemTemplate; } else { if (item.ItemIndex % 2 != 0) goto case ListItemType.AlternatingItem; } break; case ListItemType.EditItem: if (editItemTemplate != null) { contentTemplate = editItemTemplate; } else { if (item.ItemIndex == SelectedIndex) goto case ListItemType.SelectedItem; else if (item.ItemIndex % 2 != 0) goto case ListItemType.AlternatingItem; } break; case ListItemType.Separator: contentTemplate = separatorTemplate; break; } if (contentTemplate != null) contentTemplate.InstantiateIn(item); } /// <internalonly/> /// <devdoc> /// </devdoc> protected override void LoadViewState(object savedState) { if (savedState != null) { object[] myState = (object[])savedState; if (myState[0] != null) base.LoadViewState(myState[0]); if (myState[1] != null) ((IStateManager)ItemStyle).LoadViewState(myState[1]); if (myState[2] != null) ((IStateManager)SelectedItemStyle).LoadViewState(myState[2]); if (myState[3] != null) ((IStateManager)AlternatingItemStyle).LoadViewState(myState[3]); if (myState[4] != null) ((IStateManager)EditItemStyle).LoadViewState(myState[4]); if (myState[5] != null) ((IStateManager)SeparatorStyle).LoadViewState(myState[5]); if (myState[6] != null) ((IStateManager)HeaderStyle).LoadViewState(myState[6]); if (myState[7] != null) ((IStateManager)FooterStyle).LoadViewState(myState[7]); if (myState[8] != null) ((IStateManager)ControlStyle).LoadViewState(myState[8]); } } /// <internalonly/> /// <devdoc> /// </devdoc> protected override bool OnBubbleEvent(object source, EventArgs e) { bool handled = false; if (e is DataListCommandEventArgs) { DataListCommandEventArgs dce = (DataListCommandEventArgs)e; OnItemCommand(dce); handled = true; string command = dce.CommandName; if (StringUtil.EqualsIgnoreCase(command, DataList.SelectCommandName)) { SelectedIndex = dce.Item.ItemIndex; OnSelectedIndexChanged(EventArgs.Empty); } else if (StringUtil.EqualsIgnoreCase(command, DataList.EditCommandName)) { OnEditCommand(dce); } else if (StringUtil.EqualsIgnoreCase(command, DataList.DeleteCommandName)) { OnDeleteCommand(dce); } else if (StringUtil.EqualsIgnoreCase(command, DataList.UpdateCommandName)) { OnUpdateCommand(dce); } else if (StringUtil.EqualsIgnoreCase(command, DataList.CancelCommandName)) { OnCancelCommand(dce); } } return handled; } /// <devdoc> /// <para>Raises the <see langword='CancelCommand '/>event.</para> /// </devdoc> protected virtual void OnCancelCommand(DataListCommandEventArgs e) { DataListCommandEventHandler onCancelCommandHandler = (DataListCommandEventHandler)Events[EventCancelCommand]; if (onCancelCommandHandler != null) onCancelCommandHandler(this, e); } /// <devdoc> /// <para>Raises the <see langword='DeleteCommand '/>event.</para> /// </devdoc> protected virtual void OnDeleteCommand(DataListCommandEventArgs e) { DataListCommandEventHandler onDeleteCommandHandler = (DataListCommandEventHandler)Events[EventDeleteCommand]; if (onDeleteCommandHandler != null) onDeleteCommandHandler(this, e); } /// <devdoc> /// <para>Raises the <see langword='EditCommand '/>event.</para> /// </devdoc> protected virtual void OnEditCommand(DataListCommandEventArgs e) { DataListCommandEventHandler onEditCommandHandler = (DataListCommandEventHandler)Events[EventEditCommand]; if (onEditCommandHandler != null) onEditCommandHandler(this, e); } /// <devdoc> /// DataList initialization. /// </devdoc> protected internal override void OnInit(EventArgs e) { base.OnInit(e); if (Page != null && DataKeyField.Length > 0) { Page.RegisterRequiresViewStateEncryption(); } } /// <devdoc> /// <para>Raises the <see langword='ItemCommand '/>event.</para> /// </devdoc> protected virtual void OnItemCommand(DataListCommandEventArgs e) { DataListCommandEventHandler onItemCommandHandler = (DataListCommandEventHandler)Events[EventItemCommand]; if (onItemCommandHandler != null) onItemCommandHandler(this, e); } /// <devdoc> /// <para>Raises the <see langword='ItemCreated '/>event.</para> /// </devdoc> protected virtual void OnItemCreated(DataListItemEventArgs e) { DataListItemEventHandler onItemCreatedHandler = (DataListItemEventHandler)Events[EventItemCreated]; if (onItemCreatedHandler != null) onItemCreatedHandler(this, e); } /// <devdoc> /// <para>Raises the <see langword='ItemDataBound '/>event.</para> /// </devdoc> protected virtual void OnItemDataBound(DataListItemEventArgs e) { DataListItemEventHandler onItemDataBoundHandler = (DataListItemEventHandler)Events[EventItemDataBound]; if (onItemDataBoundHandler != null) onItemDataBoundHandler(this, e); // EventWizardListItemDataBound is a key for an internal event declared on IWizardSideBarListControl, which is // an interface that is meant to provide a facade to make ListView and DataList look the same. This handler // is meant to abstract away the differences between each controls ItemDataBound events. var onWizardListItemDataBoundHandler = (EventHandler<WizardSideBarListControlItemEventArgs>)Events[EventWizardListItemDataBound]; if (onWizardListItemDataBoundHandler != null) { var item = e.Item; var wizardListEventArgs = new WizardSideBarListControlItemEventArgs(new WizardSideBarListControlItem(item.DataItem, item.ItemType, item.ItemIndex, item)); onWizardListItemDataBoundHandler(this, wizardListEventArgs); } } /// <devdoc> /// <para>Raises the <see langword='UpdateCommand '/>event.</para> /// </devdoc> protected virtual void OnUpdateCommand(DataListCommandEventArgs e) { DataListCommandEventHandler onUpdateCommandHandler = (DataListCommandEventHandler)Events[EventUpdateCommand]; if (onUpdateCommandHandler != null) onUpdateCommandHandler(this, e); } /// <internalonly/> /// <devdoc> /// </devdoc> protected internal override void PrepareControlHierarchy() { ControlCollection controls = Controls; int controlCount = controls.Count; if (controlCount == 0) return; // the composite alternating item style, so we need to do just one // merge style on the actual item Style altItemStyle = null; if (alternatingItemStyle != null) { altItemStyle = new TableItemStyle(); altItemStyle.CopyFrom(itemStyle); altItemStyle.CopyFrom(alternatingItemStyle); } else { altItemStyle = itemStyle; } Style compositeStyle; for (int i = 0; i < controlCount; i++) { DataListItem item = (DataListItem)controls[i]; compositeStyle = null; switch (item.ItemType) { case ListItemType.Header: if (ShowHeader) compositeStyle = headerStyle; break; case ListItemType.Footer: if (ShowFooter) compositeStyle = footerStyle; break; case ListItemType.Separator: compositeStyle = separatorStyle; break; case ListItemType.Item: compositeStyle = itemStyle; break; case ListItemType.AlternatingItem: compositeStyle = altItemStyle; break; case ListItemType.SelectedItem: // When creating the control hierarchy we first check if the // item is in edit mode, so we know this item cannot be in edit // mode. The only special characteristic of this item is that // it is selected. { compositeStyle = new TableItemStyle(); if (item.ItemIndex % 2 != 0) compositeStyle.CopyFrom(altItemStyle); else compositeStyle.CopyFrom(itemStyle); compositeStyle.CopyFrom(selectedItemStyle); } break; case ListItemType.EditItem: // When creating the control hierarchy, we first check if the // item is in edit mode. So an item may be selected too, and // so both editItemStyle (more specific) and selectedItemStyle // are applied. { compositeStyle = new TableItemStyle(); if (item.ItemIndex % 2 != 0) compositeStyle.CopyFrom(altItemStyle); else compositeStyle.CopyFrom(itemStyle); if (item.ItemIndex == SelectedIndex) compositeStyle.CopyFrom(selectedItemStyle); compositeStyle.CopyFrom(editItemStyle); } break; } if (compositeStyle != null) { // use the cached value of ExtractTemplateRows as it was at the time of // control creation, so we don't do the wrong thing even if the // user happened to change the property if (extractTemplateRows == false) { item.MergeStyle(compositeStyle); } else { // apply the style on the TRs IEnumerator controlEnum = item.Controls.GetEnumerator(); while (controlEnum.MoveNext()) { Control c = (Control)controlEnum.Current; if (c is Table) { IEnumerator rowEnum = ((Table)c).Rows.GetEnumerator(); while (rowEnum.MoveNext()) { // ((TableRow)rowEnum.Current).MergeStyle(compositeStyle); } break; } } } } } } /// <internalonly/> /// <devdoc> /// </devdoc> protected internal override void RenderContents(HtmlTextWriter writer) { if (Controls.Count == 0) return; RepeatInfo repeatInfo = new RepeatInfo(); Table outerTable = null; // NOTE: This will end up creating the ControlStyle... Ideally we would // not create the style just for rendering, but turns out our default // style isn't empty, and does have an effect on rendering, and must // therefore always be created Style style = ControlStyle; if (extractTemplateRows) { // The table tags in the templates are stripped out and only the // <tr>'s and <td>'s are assumed to come from the template itself. // This is equivalent to a flow layout of <tr>'s in a single // vertical column. repeatInfo.RepeatDirection = RepeatDirection.Vertical; repeatInfo.RepeatLayout = RepeatLayout.Flow; repeatInfo.RepeatColumns = 1; repeatInfo.OuterTableImplied = true; outerTable = new Table(); // use ClientID (and not ID) since we want to render the fully qualified // ID even though the control will not be parented to the control hierarchy outerTable.ID = ClientID; outerTable.CopyBaseAttributes(this); outerTable.Caption = Caption; outerTable.CaptionAlign = CaptionAlign; outerTable.ApplyStyle(style); outerTable.RenderBeginTag(writer); } else { repeatInfo.RepeatDirection = RepeatDirection; repeatInfo.RepeatLayout = RepeatLayout; repeatInfo.RepeatColumns = RepeatColumns; if (repeatInfo.RepeatLayout == RepeatLayout.Table) { repeatInfo.Caption = Caption; repeatInfo.CaptionAlign = CaptionAlign; repeatInfo.UseAccessibleHeader = UseAccessibleHeader; } else { repeatInfo.EnableLegacyRendering = EnableLegacyRendering; } } repeatInfo.RenderRepeater(writer, (IRepeatInfoUser)this, style, this); if (outerTable != null) outerTable.RenderEndTag(writer); } /// <internalonly/> /// <devdoc> /// </devdoc> protected override object SaveViewState() { object baseState = base.SaveViewState(); object itemStyleState = (itemStyle != null) ? ((IStateManager)itemStyle).SaveViewState() : null; object selectedItemStyleState = (selectedItemStyle != null) ? ((IStateManager)selectedItemStyle).SaveViewState() : null; object alternatingItemStyleState = (alternatingItemStyle != null) ? ((IStateManager)alternatingItemStyle).SaveViewState() : null; object editItemStyleState = (editItemStyle != null) ? ((IStateManager)editItemStyle).SaveViewState() : null; object separatorStyleState = (separatorStyle != null) ? ((IStateManager)separatorStyle).SaveViewState() : null; object headerStyleState = (headerStyle != null) ? ((IStateManager)headerStyle).SaveViewState() : null; object footerStyleState = (footerStyle != null) ? ((IStateManager)footerStyle).SaveViewState() : null; object controlState = ControlStyleCreated ? ((IStateManager)ControlStyle).SaveViewState() : null; object[] myState = new object[9]; myState[0] = baseState; myState[1] = itemStyleState; myState[2] = selectedItemStyleState; myState[3] = alternatingItemStyleState; myState[4] = editItemStyleState; myState[5] = separatorStyleState; myState[6] = headerStyleState; myState[7] = footerStyleState; myState[8] = controlState; // note that we always have some state, atleast the ItemCount return myState; } /// <internalonly/> /// <devdoc> /// <para>Marks the starting point to begin tracking and saving changes to the /// control as part of the control viewstate.</para> /// </devdoc> protected override void TrackViewState() { base.TrackViewState(); if (itemStyle != null) ((IStateManager)itemStyle).TrackViewState(); if (selectedItemStyle != null) ((IStateManager)selectedItemStyle).TrackViewState(); if (alternatingItemStyle != null) ((IStateManager)alternatingItemStyle).TrackViewState(); if (editItemStyle != null) ((IStateManager)editItemStyle).TrackViewState(); if (separatorStyle != null) ((IStateManager)separatorStyle).TrackViewState(); if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState(); if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState(); if (ControlStyleCreated) ((IStateManager)ControlStyle).TrackViewState(); } /// <internalonly/> /// <devdoc> /// </devdoc> bool IRepeatInfoUser.HasFooter { get { return ShowFooter && (footerTemplate != null); } } /// <internalonly/> /// <devdoc> /// </devdoc> bool IRepeatInfoUser.HasHeader { get { return ShowHeader && (headerTemplate != null); } } /// <internalonly/> /// <devdoc> /// </devdoc> bool IRepeatInfoUser.HasSeparators { get { return (separatorTemplate != null); } } /// <internalonly/> /// <devdoc> /// </devdoc> int IRepeatInfoUser.RepeatedItemCount { get { if (visibleItemCount == -1) { return itemsArray != null ? itemsArray.Count : 0; } return visibleItemCount; } } /// <internalonly/> /// <devdoc> /// </devdoc> Style IRepeatInfoUser.GetItemStyle(ListItemType itemType, int repeatIndex) { DataListItem item = GetItem(itemType, repeatIndex); if ((item != null) && item.ControlStyleCreated) { return item.ControlStyle; } return null; } /// <internalonly/> /// <devdoc> /// </devdoc> void IRepeatInfoUser.RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer) { DataListItem item = GetItem(itemType, repeatIndex + offset); if (item != null) { item.RenderItem(writer, extractTemplateRows, repeatInfo.RepeatLayout == RepeatLayout.Table); } } #region IWizardSideBarListControl implementation IEnumerable IWizardSideBarListControl.Items { get { return Items; } } event CommandEventHandler IWizardSideBarListControl.ItemCommand { add { ItemCommand += new DataListCommandEventHandler(value); } remove { ItemCommand -= new DataListCommandEventHandler(value); } } event EventHandler<WizardSideBarListControlItemEventArgs> IWizardSideBarListControl.ItemDataBound { add { Events.AddHandler(EventWizardListItemDataBound , value); } remove { Events.RemoveHandler(EventWizardListItemDataBound, value); } } #endregion } }
#region File Description //----------------------------------------------------------------------------- // HumanPlayer.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input.Touch; using GameStateManagement; using YachtServices; #endregion namespace Yacht { /// <summary> /// A human player for the Yacht game. /// </summary> class HumanPlayer : YachtPlayer { #region Fields InputState input; Button roll; Button score; Rectangle screenBounds; GameTypes gameType; bool registeredForShakeDetection; bool shakeDetect; #endregion /// <summary> /// Initialize a new human player. /// </summary> /// <param name="name">The name of the player.</param> /// <param name="diceHandler">The <see cref="DiceHandler"/> that handles the player's dice.</param> /// <param name="gameType">The type of game the player is participating in.</param> /// <param name="input">The <see cref="InputState"/> to check for touch input.</param> /// <param name="rollButtonTexture">Texture for the roll button.</param> /// <param name="scoreButtonTexture">Texture for the score button.</param> /// <param name="graphicsDevice">The <see cref="GraphicsDevice"/> depicting the display.</param> public HumanPlayer(string name, DiceHandler diceHandler, GameTypes gameType, InputState input, Rectangle screenBounds) : base(name, diceHandler) { this.input = input; this.gameType = gameType; this.screenBounds = screenBounds; } /// <summary> /// Loads assets used by the dice handler and performs other visual initializations. /// </summary> /// <param name="contentManager">The content manager to use when loading the assets.</param> public void LoadAssets(ContentManager contentManager) { Texture2D rollButtonTexture = contentManager.Load<Texture2D>(@"Images\rollBtn"); Texture2D scoreButtonTexture = contentManager.Load<Texture2D>(@"Images\scoreBtn"); // Initialize the buttons Vector2 position = new Vector2(screenBounds.Right - rollButtonTexture.Width - 10, screenBounds.Center.Y - rollButtonTexture.Bounds.Height); roll = new Button(rollButtonTexture, position, null, null); position.X -= scoreButtonTexture.Width + 20; score = new Button(scoreButtonTexture, position, null, null); roll.Click += roll_Click; score.Click += score_Click; } #region Render /// <summary> /// Draw the player input elements. /// </summary> /// <param name="spriteBatch">The <see cref="SpriteBatch"/> to use when drawing.</param> public override void Draw(SpriteBatch spriteBatch) { roll.Draw(spriteBatch); score.Draw(spriteBatch); DrawRollCounter(spriteBatch); DrawSelectedScore(spriteBatch); } /// <summary> /// Draw the score currently selected by the player. /// </summary> /// <param name="spriteBatch">The <see cref="SpriteBatch"/> to use when drawing.</param> private void DrawSelectedScore(SpriteBatch spriteBatch) { if (GameStateHandler != null && GameStateHandler.IsScoreSelect) { Dice[] holdingDice = DiceHandler.GetHoldingDice(); if (holdingDice != null) { // Calculate the score and the position byte selectedScore = GameStateHandler.CombinationScore(GameStateHandler.SelectedScore.Value, holdingDice); string text = GameStateHandler.ScoreTypesNames[(int)GameStateHandler.SelectedScore.Value - 1].ToUpper(); Vector2 position = new Vector2(score.Position.X, roll.Position.Y); position.Y += roll.Texture.Height + 10; Vector2 measure = YachtGame.Font.MeasureString(text); position.X += score.Texture.Bounds.Center.X - measure.X / 2; spriteBatch.DrawString(YachtGame.Font, text, position, Color.White); text = selectedScore.ToString(); position.Y += measure.Y; measure = YachtGame.Font.MeasureString(text); position.X = score.Position.X; position.X += score.Texture.Bounds.Center.X - measure.X / 2; spriteBatch.DrawString(YachtGame.Font, text, position, Color.White); } } } /// <summary> /// Draw the amount of rolls available. /// </summary> /// <param name="spriteBatch">The <see cref="SpriteBatch"/> to use when drawing.</param> private void DrawRollCounter(SpriteBatch spriteBatch) { if (DiceHandler.Rolls < 3) { string text = "ROLLS"; Vector2 measure = YachtGame.Font.MeasureString(text); Vector2 position = new Vector2((int)roll.Position.X,(int)roll.Position.Y); position.Y += roll.Texture.Height + 10; position.X += roll.Texture.Bounds.Center.X - measure.X / 2; spriteBatch.DrawString(YachtGame.Font, text, position, Color.White); text = string.Format("X{0}", 3 - DiceHandler.Rolls); position.Y += measure.Y; measure = YachtGame.Font.MeasureString(text); position.X = roll.Position.X; position.X += roll.Texture.Bounds.Center.X - measure.X / 2; spriteBatch.DrawString(YachtGame.Font, text, position, Color.White); } } #endregion /// <summary> /// Handle the human player's input. /// </summary> public override void PerformPlayerLogic() { // Enable or disable buttons roll.Enabled = DiceHandler.Rolls != 3 && !DiceHandler.DiceRolling(); score.Enabled = GameStateHandler != null && GameStateHandler.IsScoreSelect; for (int i = 0; i < input.Gestures.Count; i++) { roll.HandleInput(input.Gestures[i]); score.HandleInput(input.Gestures[i]); HandleDiceHandlerInput(input.Gestures[i]); HandleSelectScoreInput(input.Gestures[i]); } HandleShakeInput(); } #region Private Methods /// <summary> /// Check if the phone was shaken and if so roll the dice. /// </summary> private void HandleShakeInput() { // Register for shake detection if (!registeredForShakeDetection) { Accelerometer.ShakeDetected += Accelerometer_ShakeDetected; registeredForShakeDetection = true; } if (shakeDetect) { DiceHandler.Roll(); if (gameType == GameTypes.Online) { NetworkManager.Instance.ResetTimeout(); } shakeDetect = false; } } /// <summary> /// Highlight the score card line that was tapped. /// </summary> /// <param name="sample">Input gesture performed.</param> private void HandleSelectScoreInput(GestureSample sample) { if (sample.GestureType == GestureType.Tap) { // Create the touch rectangle Rectangle touchRect = new Rectangle((int)sample.Position.X - 5, (int)sample.Position.Y - 5, 10, 10); for (int i = 0; i < 12; i++) { if (GameStateHandler.IntersectLine(touchRect, i)) { GameStateHandler.SelectScore((YachtCombination)(i + 1)); } } } } /// <summary> /// Move dice that are tapped. /// </summary> /// <param name="sample">Input gesture performed.</param> private void HandleDiceHandlerInput(GestureSample sample) { if (DiceHandler.Rolls < 3) { Dice[] rollingDice = DiceHandler.GetRollingDice(); Dice[] holdingDice = DiceHandler.GetHoldingDice(); if (sample.GestureType == GestureType.Tap) { // Create the touch rectangle Rectangle touchRect = new Rectangle((int)sample.Position.X - 5, (int)sample.Position.Y - 5, 10, 10); for (int i = 0; i < DiceHandler.DiceAmount; i++) { // Check for intersection between the touch rectangle and any of the dice if ((rollingDice != null && rollingDice[i] != null && !rollingDice[i].IsRolling && rollingDice[i].Intersects(touchRect)) || (holdingDice != null && holdingDice[i] != null && holdingDice[i].Intersects(touchRect))) { DiceHandler.MoveDice(i); if (DiceHandler.GetHoldingDice() == null) { GameStateHandler.SelectScore(null); } } } } } } #endregion #region Event Handlers /// <summary> /// Handle the "Score" button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void score_Click(object sender, EventArgs e) { if (GameStateHandler != null && GameStateHandler.IsScoreSelect) { GameStateHandler.FinishTurn(); AudioManager.PlaySoundRandom("Pencil", 3); DiceHandler.Reset(GameStateHandler.IsGameOver); } } /// <summary> /// Handle the "Roll" button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void roll_Click(object sender, EventArgs e) { DiceHandler.Roll(); if (gameType== GameTypes.Online) { NetworkManager.Instance.ResetTimeout(); } } /// <summary> /// Handle shake detection /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Accelerometer_ShakeDetected(object sender, EventArgs e) { shakeDetect = true; } #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !WINDOWS_UWP // When the .NET scripting backend is enabled and C# projects are built // The assembly that this file is part of is still built for the player, // even though the assembly itself is marked as a test assembly (this is not // expected because test assemblies should not be included in player builds). // Because the .NET backend is deprecated in 2018 and removed in 2019 and this // issue will likely persist for 2018, this issue is worked around by wrapping all // play mode tests in this check. using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.UI; using Microsoft.MixedReality.Toolkit.Utilities; using NUnit.Framework; using System; using System.Collections; using System.IO; using System.Linq; using System.Text; using UnityEditor; using UnityEngine; using UnityEngine.TestTools; namespace Microsoft.MixedReality.Toolkit.Tests { /// <summary> /// Tests different layout behavior of GridObjectCollection. /// You can use GridObjectLayoutControl.cs in the examples package to /// quickly generate the expected positions used in these tests. /// </summary> internal class GridObjectCollectionTests : BasePlayModeTests { public override IEnumerator Setup() { yield return base.Setup(); TestUtilities.PlayspaceToOriginLookingForward(); yield return null; } #region Tests /// <summary> /// Tests that grid lays out object correctly for all different anchor types /// </summary> [UnityTest] public IEnumerator TestGridAnchors() { // Create a grid GameObject go = new GameObject(); go.name = "grid"; var grid = go.AddComponent<GridObjectCollection>(); grid.Distance = 0.75f; grid.CellWidth = 0.15f; grid.CellHeight = 0.15f; for (int i = 0; i < 3; i++) { var child = GameObject.CreatePrimitive(PrimitiveType.Cube); child.transform.parent = go.transform; child.transform.localScale = Vector3.one * 0.1f; } grid.Layout = LayoutOrder.Horizontal; // Testing anchoring along axis grid.AnchorAlongAxis = true; int expectedIdx = 0; foreach (LayoutAnchor et in Enum.GetValues(typeof(LayoutAnchor))) { grid.Anchor = et; grid.UpdateCollection(); foreach (Transform childTransform in go.transform) { var expected = axisAnchorTestExpected[expectedIdx]; var actual = childTransform.transform.localPosition; TestUtilities.AssertAboutEqual( actual, expected, "Child object not in expected position, layout " + et, 0.01f); expectedIdx++; } yield return null; } // Testing non-axis aligned anchors grid.AnchorAlongAxis = false; expectedIdx = 0; foreach (LayoutAnchor et in Enum.GetValues(typeof(LayoutAnchor))) { grid.Anchor = et; grid.UpdateCollection(); foreach (Transform childTransform in go.transform) { var expected = freeAnchorTestExpected[expectedIdx]; var actual = childTransform.transform.localPosition; TestUtilities.AssertAboutEqual( actual, expected, "Child object not in expected position, layout " + et, 0.01f); expectedIdx++; } yield return null; } yield return null; } /// <summary> /// Tests that grid lays out object correctly for all different alignment options /// </summary> [UnityTest] public IEnumerator TestGridAlignment() { // Create a grid GameObject go = new GameObject(); go.name = "grid"; var grid = go.AddComponent<GridObjectCollection>(); grid.Distance = 0.75f; grid.CellWidth = 0.15f; grid.CellHeight = 0.15f; grid.Layout = LayoutOrder.ColumnThenRow; grid.Columns = 2; grid.Anchor = LayoutAnchor.UpperCenter; grid.AnchorAlongAxis = true; for (int i = 0; i < 3; i++) { var child = GameObject.CreatePrimitive(PrimitiveType.Cube); child.transform.parent = go.transform; child.transform.localScale = Vector3.one * 0.1f; } grid.ColumnAlignment = LayoutHorizontalAlignment.Left; grid.UpdateCollection(); int expectedIdx = 0; foreach (LayoutHorizontalAlignment alignment in Enum.GetValues(typeof(LayoutHorizontalAlignment))) { grid.ColumnAlignment = alignment; grid.UpdateCollection(); foreach (Transform childTransform in go.transform) { var expected = alignmentTestExpected[expectedIdx]; var actual = childTransform.transform.localPosition; TestUtilities.AssertAboutEqual( actual, expected, "Child object not in expected position, horizontal alignment " + alignment, 0.01f); expectedIdx++; } yield return null; } yield return null; grid.Layout = LayoutOrder.RowThenColumn; grid.Rows = 2; foreach (LayoutVerticalAlignment alignment in Enum.GetValues(typeof(LayoutVerticalAlignment))) { grid.RowAlignment = alignment; grid.UpdateCollection(); foreach (Transform childTransform in go.transform) { var expected = alignmentTestExpected[expectedIdx]; var actual = childTransform.transform.localPosition; TestUtilities.AssertAboutEqual( actual, expected, "Child object not in expected position, horizontal alignment " + alignment, 0.01f); expectedIdx++; } yield return null; } yield return null; } #region Expected Values // You can use GridObjectLayoutControl.cs in the examples package to // quickly generate the expected positions used in these tests. private Vector3[] freeAnchorTestExpected = new Vector3[] { new Vector3(0.08f, -0.08f, 0.75f), // UpperLeft index 0 new Vector3(0.23f, -0.08f, 0.75f), // UpperLeft index 1 new Vector3(0.38f, -0.08f, 0.75f), // UpperLeft index 2 new Vector3(-0.15f, -0.08f, 0.75f), // UpperCenter index 0 new Vector3(0.00f, -0.08f, 0.75f), // UpperCenter index 1 new Vector3(0.15f, -0.08f, 0.75f), // UpperCenter index 2 new Vector3(-0.38f, -0.08f, 0.75f), // UpperRight index 0 new Vector3(-0.23f, -0.08f, 0.75f), // UpperRight index 1 new Vector3(-0.08f, -0.08f, 0.75f), // UpperRight index 2 new Vector3(0.08f, 0.00f, 0.75f), // MiddleLeft index 0 new Vector3(0.23f, 0.00f, 0.75f), // MiddleLeft index 1 new Vector3(0.38f, 0.00f, 0.75f), // MiddleLeft index 2 new Vector3(-0.15f, 0.00f, 0.75f), // MiddleCenter index 0 new Vector3(0.00f, 0.00f, 0.75f), // MiddleCenter index 1 new Vector3(0.15f, 0.00f, 0.75f), // MiddleCenter index 2 new Vector3(-0.38f, 0.00f, 0.75f), // MiddleRight index 0 new Vector3(-0.23f, 0.00f, 0.75f), // MiddleRight index 1 new Vector3(-0.08f, 0.00f, 0.75f), // MiddleRight index 2 new Vector3(0.08f, 0.08f, 0.75f), // BottomLeft index 0 new Vector3(0.23f, 0.08f, 0.75f), // BottomLeft index 1 new Vector3(0.38f, 0.08f, 0.75f), // BottomLeft index 2 new Vector3(-0.15f, 0.08f, 0.75f), // BottomCenter index 0 new Vector3(0.00f, 0.08f, 0.75f), // BottomCenter index 1 new Vector3(0.15f, 0.08f, 0.75f), // BottomCenter index 2 new Vector3(-0.38f, 0.08f, 0.75f), // BottomRight index 0 new Vector3(-0.23f, 0.08f, 0.75f), // BottomRight index 1 new Vector3(-0.08f, 0.08f, 0.75f) // BottomRight index 2 }; private Vector3[] axisAnchorTestExpected = new Vector3[] { new Vector3(0.0f, -0.0f, 0.75f), // UpperLeft index 0 new Vector3(0.15f, -0.0f, 0.75f), // UpperLeft index 1 new Vector3(0.30f, -0.0f, 0.75f), // UpperLeft index 2 new Vector3(-0.15f, -0.0f, 0.75f), // UpperCenter index 0 new Vector3(0.00f, -0.0f, 0.75f), // UpperCenter index 1 new Vector3(0.15f, -0.0f, 0.75f), // UpperCenter index 2 new Vector3(-0.30f, -0.0f, 0.75f), // UpperRight index 0 new Vector3(-0.15f, -0.0f, 0.75f), // UpperRight index 1 new Vector3(-0.0f, -0.0f, 0.75f), // UpperRight index 2 new Vector3(0.0f, 0.00f, 0.75f), // MiddleLeft index 0 new Vector3(0.15f, 0.00f, 0.75f), // MiddleLeft index 1 new Vector3(0.30f, 0.00f, 0.75f), // MiddleLeft index 2 new Vector3(-0.15f, 0.00f, 0.75f), // MiddleCenter index 0 new Vector3(0.00f, 0.00f, 0.75f), // MiddleCenter index 1 new Vector3(0.15f, 0.00f, 0.75f), // MiddleCenter index 2 new Vector3(-0.30f, 0.00f, 0.75f), // MiddleRight index 0 new Vector3(-0.15f, 0.00f, 0.75f), // MiddleRight index 1 new Vector3(-0.0f, 0.00f, 0.75f), // MiddleRight index 2 new Vector3(0.0f, 0.0f, 0.75f), // BottomLeft index 0 new Vector3(0.15f, 0.0f, 0.75f), // BottomLeft index 1 new Vector3(0.30f, 0.0f, 0.75f), // BottomLeft index 2 new Vector3(-0.15f, 0.0f, 0.75f), // BottomCenter index 0 new Vector3(0.00f, 0.0f, 0.75f), // BottomCenter index 1 new Vector3(0.15f, 0.0f, 0.75f), // BottomCenter index 2 new Vector3(-0.30f, 0.0f, 0.75f), // BottomRight index 0 new Vector3(-0.15f, 0.0f, 0.75f), // BottomRight index 1 new Vector3(-0.0f, 0.0f, 0.75f) // BottomRight index 2 }; private Vector3[] alignmentTestExpected = new Vector3[] { new Vector3(-0.075f, 0.0f, 0.75f), // Left Horizontal 0 new Vector3(0.075f, 0.0f, 0.75f), // Left Horizontal 1 new Vector3(-0.075f, -0.150f, 0.75f), // Left Horizontal 2 new Vector3(-0.075f, 0.0f, 0.75f), // Center Horizontal 0 new Vector3(0.075f, 0.0f, 0.75f), // Center Horizontal 1 new Vector3(0f, -0.150f, 0.75f), // Center Horizontal 2 new Vector3(-0.075f, 0.0f, 0.75f), // Right Horizontal 0 new Vector3(0.075f, 0.0f, 0.75f), // Right Horizontal 1 new Vector3(0.075f, -0.150f, 0.75f), // Right Horizontal 2 new Vector3(-0.075f, 0.0f, 0.75f), // Top Vertical 0 new Vector3(-0.075f, -0.150f, 0.75f), // Top Vertical 1 new Vector3(0.075f, 0.0f, 0.75f), // Top Vertical 2 new Vector3(-0.075f, 0.0f, 0.75f), // Middle Vertical 0 new Vector3(-0.075f, -0.150f, 0.75f), // Middle Vertical 1 new Vector3(0.075f, -0.075f, 0.75f), // Middle Vertical 2 new Vector3(-0.075f, 0.0f, 0.75f), // Bottom Vertical 0 new Vector3(-0.075f, -0.150f, 0.75f), // Middle Vertical 1 new Vector3(0.075f, -0.150f, 0.75f), // Top Vertical 2 }; #endregion #endregion } } #endif
// 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> /// Credential Stuffing Event Store Feed ///<para>SObject Name: CredentialStuffingEventStoreFeed</para> ///<para>Custom Object: False</para> ///</summary> public class SfCredentialStuffingEventStoreFeed : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "CredentialStuffingEventStoreFeed"; } } ///<summary> /// Feed Item 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> /// Parent ID /// <para>Name: ParentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "parentId")] [Updateable(false), Createable(false)] public string ParentId { get; set; } ///<summary> /// ReferenceTo: CredentialStuffingEventStore /// <para>RelationshipName: Parent</para> ///</summary> [JsonProperty(PropertyName = "parent")] [Updateable(false), Createable(false)] public SfCredentialStuffingEventStore Parent { get; set; } ///<summary> /// Feed Item Type /// <para>Name: Type</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "type")] [Updateable(false), Createable(false)] public string Type { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// 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> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Comment Count /// <para>Name: CommentCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "commentCount")] [Updateable(false), Createable(false)] public int? CommentCount { get; set; } ///<summary> /// Like Count /// <para>Name: LikeCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "likeCount")] [Updateable(false), Createable(false)] public int? LikeCount { get; set; } ///<summary> /// Title /// <para>Name: Title</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "title")] [Updateable(false), Createable(false)] public string Title { get; set; } ///<summary> /// Body /// <para>Name: Body</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "body")] [Updateable(false), Createable(false)] public string Body { get; set; } ///<summary> /// Link Url /// <para>Name: LinkUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "linkUrl")] [Updateable(false), Createable(false)] public string LinkUrl { get; set; } ///<summary> /// Is Rich Text /// <para>Name: IsRichText</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isRichText")] [Updateable(false), Createable(false)] public bool? IsRichText { get; set; } ///<summary> /// Related Record ID /// <para>Name: RelatedRecordId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "relatedRecordId")] [Updateable(false), Createable(false)] public string RelatedRecordId { get; set; } ///<summary> /// InsertedBy ID /// <para>Name: InsertedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "insertedById")] [Updateable(false), Createable(false)] public string InsertedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: InsertedBy</para> ///</summary> [JsonProperty(PropertyName = "insertedBy")] [Updateable(false), Createable(false)] public SfUser InsertedBy { get; set; } ///<summary> /// Best Comment ID /// <para>Name: BestCommentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "bestCommentId")] [Updateable(false), Createable(false)] public string BestCommentId { get; set; } ///<summary> /// ReferenceTo: FeedComment /// <para>RelationshipName: BestComment</para> ///</summary> [JsonProperty(PropertyName = "bestComment")] [Updateable(false), Createable(false)] public SfFeedComment BestComment { 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. /*============================================================================= ** ** Class: Queue ** ** Purpose: Represents a first-in, first-out collection of objects. ** =============================================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections { // A simple Queue of objects. Internally it is implemented as a circular // buffer, so Enqueue can be O(n). Dequeue is O(1). [DebuggerTypeProxy(typeof(System.Collections.Queue.QueueDebugView))] [DebuggerDisplay("Count = {Count}")] [Serializable] public class Queue : ICollection, ICloneable { private Object[] _array; private int _head; // First valid element in the queue private int _tail; // Last valid element in the queue private int _size; // Number of elements. private int _growFactor; // 100 == 1.0, 130 == 1.3, 200 == 2.0 private int _version; [NonSerialized] private Object _syncRoot; private const int _MinimumGrow = 4; private const int _ShrinkThreshold = 32; // Creates a queue with room for capacity objects. The default initial // capacity and grow factor are used. public Queue() : this(32, (float)2.0) { } // Creates a queue with room for capacity objects. The default grow factor // is used. // public Queue(int capacity) : this(capacity, (float)2.0) { } // Creates a queue with room for capacity objects. When full, the new // capacity is set to the old capacity * growFactor. // public Queue(int capacity, float growFactor) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); if (!(growFactor >= 1.0 && growFactor <= 10.0)) throw new ArgumentOutOfRangeException(nameof(growFactor), SR.Format(SR.ArgumentOutOfRange_QueueGrowFactor, 1, 10)); Contract.EndContractBlock(); _array = new Object[capacity]; _head = 0; _tail = 0; _size = 0; _growFactor = (int)(growFactor * 100); } // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. // public Queue(ICollection col) : this((col == null ? 32 : col.Count)) { if (col == null) throw new ArgumentNullException(nameof(col)); Contract.EndContractBlock(); IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) Enqueue(en.Current); } public virtual int Count { get { return _size; } } public virtual Object Clone() { Queue q = new Queue(_size); q._size = _size; int numToCopy = _size; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, q._array, 0, firstPart); numToCopy -= firstPart; if (numToCopy > 0) Array.Copy(_array, 0, q._array, _array.Length - _head, numToCopy); q._version = _version; return q; } public virtual bool IsSynchronized { get { return false; } } public virtual Object SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all Objects from the queue. public virtual void Clear() { if (_size != 0) { if (_head < _tail) Array.Clear(_array, _head, _size); else { Array.Clear(_array, _head, _array.Length - _head); Array.Clear(_array, 0, _tail); } _size = 0; } _head = 0; _tail = 0; _version++; } // CopyTo copies a collection into an Array, starting at a particular // index into the array. // public virtual void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); int arrayLen = array.Length; if (arrayLen - index < _size) throw new ArgumentException(SR.Argument_InvalidOffLen); int numToCopy = _size; if (numToCopy == 0) return; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, array, index, firstPart); numToCopy -= firstPart; if (numToCopy > 0) Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy); } // Adds obj to the tail of the queue. // public virtual void Enqueue(Object obj) { if (_size == _array.Length) { int newcapacity = (int)((long)_array.Length * (long)_growFactor / 100); if (newcapacity < _array.Length + _MinimumGrow) { newcapacity = _array.Length + _MinimumGrow; } SetCapacity(newcapacity); } _array[_tail] = obj; _tail = (_tail + 1) % _array.Length; _size++; _version++; } // GetEnumerator returns an IEnumerator over this Queue. This // Enumerator will support removing. // public virtual IEnumerator GetEnumerator() { return new QueueEnumerator(this); } // Removes the object at the head of the queue and returns it. If the queue // is empty, this method simply returns null. public virtual Object Dequeue() { if (Count == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); Contract.EndContractBlock(); Object removed = _array[_head]; _array[_head] = null; _head = (_head + 1) % _array.Length; _size--; _version++; return removed; } // Returns the object at the head of the queue. The object remains in the // queue. If the queue is empty, this method throws an // InvalidOperationException. public virtual Object Peek() { if (Count == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); Contract.EndContractBlock(); return _array[_head]; } // Returns a synchronized Queue. Returns a synchronized wrapper // class around the queue - the caller must not use references to the // original queue. // public static Queue Synchronized(Queue queue) { if (queue == null) throw new ArgumentNullException(nameof(queue)); Contract.EndContractBlock(); return new SynchronizedQueue(queue); } // Returns true if the queue contains at least one object equal to obj. // Equality is determined using obj.Equals(). // // Exceptions: ArgumentNullException if obj == null. public virtual bool Contains(Object obj) { int index = _head; int count = _size; while (count-- > 0) { if (obj == null) { if (_array[index] == null) return true; } else if (_array[index] != null && _array[index].Equals(obj)) { return true; } index = (index + 1) % _array.Length; } return false; } internal Object GetElement(int i) { return _array[(_head + i) % _array.Length]; } // Iterates over the objects in the queue, returning an array of the // objects in the Queue, or an empty array if the queue is empty. // The order of elements in the array is first in to last in, the same // order produced by successive calls to Dequeue. public virtual Object[] ToArray() { if (_size == 0) return Array.Empty<Object>(); Object[] arr = new Object[_size]; if (_head < _tail) { Array.Copy(_array, _head, arr, 0, _size); } else { Array.Copy(_array, _head, arr, 0, _array.Length - _head); Array.Copy(_array, 0, arr, _array.Length - _head, _tail); } return arr; } // PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity // must be >= _size. private void SetCapacity(int capacity) { Object[] newarray = new Object[capacity]; if (_size > 0) { if (_head < _tail) { Array.Copy(_array, _head, newarray, 0, _size); } else { Array.Copy(_array, _head, newarray, 0, _array.Length - _head); Array.Copy(_array, 0, newarray, _array.Length - _head, _tail); } } _array = newarray; _head = 0; _tail = (_size == capacity) ? 0 : _size; _version++; } public virtual void TrimToSize() { SetCapacity(_size); } // Implements a synchronization wrapper around a queue. private class SynchronizedQueue : Queue { private Queue _q; private Object _root; internal SynchronizedQueue(Queue q) { _q = q; _root = _q.SyncRoot; } public override bool IsSynchronized { get { return true; } } public override Object SyncRoot { get { return _root; } } public override int Count { get { lock (_root) { return _q.Count; } } } public override void Clear() { lock (_root) { _q.Clear(); } } public override Object Clone() { lock (_root) { return new SynchronizedQueue((Queue)_q.Clone()); } } public override bool Contains(Object obj) { lock (_root) { return _q.Contains(obj); } } public override void CopyTo(Array array, int arrayIndex) { lock (_root) { _q.CopyTo(array, arrayIndex); } } public override void Enqueue(Object value) { lock (_root) { _q.Enqueue(value); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10. public override Object Dequeue() { lock (_root) { return _q.Dequeue(); } } public override IEnumerator GetEnumerator() { lock (_root) { return _q.GetEnumerator(); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10. public override Object Peek() { lock (_root) { return _q.Peek(); } } public override Object[] ToArray() { lock (_root) { return _q.ToArray(); } } public override void TrimToSize() { lock (_root) { _q.TrimToSize(); } } } // Implements an enumerator for a Queue. The enumerator uses the // internal version number of the list to ensure that no modifications are // made to the list while an enumeration is in progress. private class QueueEnumerator : IEnumerator, ICloneable { private Queue _q; private int _index; private int _version; private Object _currentElement; internal QueueEnumerator(Queue q) { _q = q; _version = _q._version; _index = 0; _currentElement = _q._array; if (_q._size == 0) _index = -1; } public object Clone() => MemberwiseClone(); public virtual bool MoveNext() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index < 0) { _currentElement = _q._array; return false; } _currentElement = _q.GetElement(_index); _index++; if (_index == _q._size) _index = -1; return true; } public virtual Object Current { get { if (_currentElement == _q._array) { if (_index == 0) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); else throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _currentElement; } } public virtual void Reset() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_q._size == 0) _index = -1; else _index = 0; _currentElement = _q._array; } } internal class QueueDebugView { private Queue _queue; public QueueDebugView(Queue queue) { if (queue == null) throw new ArgumentNullException(nameof(queue)); Contract.EndContractBlock(); _queue = queue; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public Object[] Items { get { return _queue.ToArray(); } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/uptime_service.proto // Original file comments: // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace Google.Cloud.Monitoring.V3 { /// <summary> /// The UptimeCheckService API is used to manage (list, create, delete, edit) /// uptime check configurations in the Stackdriver Monitoring product. An uptime /// check is a piece of configuration that determines which resources and /// services to monitor for availability. These configurations can also be /// configured interactively by navigating to the [Cloud Console] /// (http://console.cloud.google.com), selecting the appropriate project, /// clicking on "Monitoring" on the left-hand side to navigate to Stackdriver, /// and then clicking on "Uptime". /// </summary> public static partial class UptimeCheckService { static readonly string __ServiceName = "google.monitoring.v3.UptimeCheckService"; static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest> __Marshaller_ListUptimeCheckConfigsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse> __Marshaller_ListUptimeCheckConfigsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest> __Marshaller_GetUptimeCheckConfigRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> __Marshaller_UptimeCheckConfig = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest> __Marshaller_CreateUptimeCheckConfigRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest> __Marshaller_UpdateUptimeCheckConfigRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest> __Marshaller_DeleteUptimeCheckConfigRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest> __Marshaller_ListUptimeCheckIpsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse> __Marshaller_ListUptimeCheckIpsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest, global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse> __Method_ListUptimeCheckConfigs = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest, global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse>( grpc::MethodType.Unary, __ServiceName, "ListUptimeCheckConfigs", __Marshaller_ListUptimeCheckConfigsRequest, __Marshaller_ListUptimeCheckConfigsResponse); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest, global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> __Method_GetUptimeCheckConfig = new grpc::Method<global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest, global::Google.Cloud.Monitoring.V3.UptimeCheckConfig>( grpc::MethodType.Unary, __ServiceName, "GetUptimeCheckConfig", __Marshaller_GetUptimeCheckConfigRequest, __Marshaller_UptimeCheckConfig); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest, global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> __Method_CreateUptimeCheckConfig = new grpc::Method<global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest, global::Google.Cloud.Monitoring.V3.UptimeCheckConfig>( grpc::MethodType.Unary, __ServiceName, "CreateUptimeCheckConfig", __Marshaller_CreateUptimeCheckConfigRequest, __Marshaller_UptimeCheckConfig); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest, global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> __Method_UpdateUptimeCheckConfig = new grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest, global::Google.Cloud.Monitoring.V3.UptimeCheckConfig>( grpc::MethodType.Unary, __ServiceName, "UpdateUptimeCheckConfig", __Marshaller_UpdateUptimeCheckConfigRequest, __Marshaller_UptimeCheckConfig); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteUptimeCheckConfig = new grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteUptimeCheckConfig", __Marshaller_DeleteUptimeCheckConfigRequest, __Marshaller_Empty); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest, global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse> __Method_ListUptimeCheckIps = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest, global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse>( grpc::MethodType.Unary, __ServiceName, "ListUptimeCheckIps", __Marshaller_ListUptimeCheckIpsRequest, __Marshaller_ListUptimeCheckIpsResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.UptimeServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of UptimeCheckService</summary> public abstract partial class UptimeCheckServiceBase { /// <summary> /// Lists the existing valid uptime check configurations for the project, /// leaving out any invalid configurations. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse> ListUptimeCheckConfigs(global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets a single uptime check configuration. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> GetUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates a new uptime check configuration. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> CreateUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Updates an uptime check configuration. You can either replace the entire /// configuration with a new one or replace only certain fields in the current /// configuration by specifying the fields to be updated via `"updateMask"`. /// Returns the updated configuration. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> UpdateUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deletes an uptime check configuration. Note that this method will fail /// if the uptime check configuration is referenced by an alert policy or /// other dependent configs that would be rendered invalid by the deletion. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Returns the list of IPs that checkers run from /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse> ListUptimeCheckIps(global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for UptimeCheckService</summary> public partial class UptimeCheckServiceClient : grpc::ClientBase<UptimeCheckServiceClient> { /// <summary>Creates a new client for UptimeCheckService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public UptimeCheckServiceClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for UptimeCheckService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public UptimeCheckServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected UptimeCheckServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected UptimeCheckServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Lists the existing valid uptime check configurations for the project, /// leaving out any invalid configurations. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse ListUptimeCheckConfigs(global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListUptimeCheckConfigs(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the existing valid uptime check configurations for the project, /// leaving out any invalid configurations. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse ListUptimeCheckConfigs(global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListUptimeCheckConfigs, null, options, request); } /// <summary> /// Lists the existing valid uptime check configurations for the project, /// leaving out any invalid configurations. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse> ListUptimeCheckConfigsAsync(global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListUptimeCheckConfigsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the existing valid uptime check configurations for the project, /// leaving out any invalid configurations. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse> ListUptimeCheckConfigsAsync(global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListUptimeCheckConfigs, null, options, request); } /// <summary> /// Gets a single uptime check configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.UptimeCheckConfig GetUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetUptimeCheckConfig(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single uptime check configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.UptimeCheckConfig GetUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetUptimeCheckConfig, null, options, request); } /// <summary> /// Gets a single uptime check configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> GetUptimeCheckConfigAsync(global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetUptimeCheckConfigAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single uptime check configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> GetUptimeCheckConfigAsync(global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetUptimeCheckConfig, null, options, request); } /// <summary> /// Creates a new uptime check configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.UptimeCheckConfig CreateUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateUptimeCheckConfig(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new uptime check configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.UptimeCheckConfig CreateUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateUptimeCheckConfig, null, options, request); } /// <summary> /// Creates a new uptime check configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> CreateUptimeCheckConfigAsync(global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateUptimeCheckConfigAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new uptime check configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> CreateUptimeCheckConfigAsync(global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateUptimeCheckConfig, null, options, request); } /// <summary> /// Updates an uptime check configuration. You can either replace the entire /// configuration with a new one or replace only certain fields in the current /// configuration by specifying the fields to be updated via `"updateMask"`. /// Returns the updated configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.UptimeCheckConfig UpdateUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateUptimeCheckConfig(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an uptime check configuration. You can either replace the entire /// configuration with a new one or replace only certain fields in the current /// configuration by specifying the fields to be updated via `"updateMask"`. /// Returns the updated configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.UptimeCheckConfig UpdateUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateUptimeCheckConfig, null, options, request); } /// <summary> /// Updates an uptime check configuration. You can either replace the entire /// configuration with a new one or replace only certain fields in the current /// configuration by specifying the fields to be updated via `"updateMask"`. /// Returns the updated configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> UpdateUptimeCheckConfigAsync(global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateUptimeCheckConfigAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an uptime check configuration. You can either replace the entire /// configuration with a new one or replace only certain fields in the current /// configuration by specifying the fields to be updated via `"updateMask"`. /// Returns the updated configuration. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> UpdateUptimeCheckConfigAsync(global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateUptimeCheckConfig, null, options, request); } /// <summary> /// Deletes an uptime check configuration. Note that this method will fail /// if the uptime check configuration is referenced by an alert policy or /// other dependent configs that would be rendered invalid by the deletion. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteUptimeCheckConfig(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes an uptime check configuration. Note that this method will fail /// if the uptime check configuration is referenced by an alert policy or /// other dependent configs that would be rendered invalid by the deletion. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteUptimeCheckConfig(global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteUptimeCheckConfig, null, options, request); } /// <summary> /// Deletes an uptime check configuration. Note that this method will fail /// if the uptime check configuration is referenced by an alert policy or /// other dependent configs that would be rendered invalid by the deletion. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteUptimeCheckConfigAsync(global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteUptimeCheckConfigAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes an uptime check configuration. Note that this method will fail /// if the uptime check configuration is referenced by an alert policy or /// other dependent configs that would be rendered invalid by the deletion. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteUptimeCheckConfigAsync(global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteUptimeCheckConfig, null, options, request); } /// <summary> /// Returns the list of IPs that checkers run from /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse ListUptimeCheckIps(global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListUptimeCheckIps(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the list of IPs that checkers run from /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse ListUptimeCheckIps(global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListUptimeCheckIps, null, options, request); } /// <summary> /// Returns the list of IPs that checkers run from /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse> ListUptimeCheckIpsAsync(global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListUptimeCheckIpsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the list of IPs that checkers run from /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse> ListUptimeCheckIpsAsync(global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListUptimeCheckIps, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override UptimeCheckServiceClient NewInstance(ClientBaseConfiguration configuration) { return new UptimeCheckServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(UptimeCheckServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_ListUptimeCheckConfigs, serviceImpl.ListUptimeCheckConfigs) .AddMethod(__Method_GetUptimeCheckConfig, serviceImpl.GetUptimeCheckConfig) .AddMethod(__Method_CreateUptimeCheckConfig, serviceImpl.CreateUptimeCheckConfig) .AddMethod(__Method_UpdateUptimeCheckConfig, serviceImpl.UpdateUptimeCheckConfig) .AddMethod(__Method_DeleteUptimeCheckConfig, serviceImpl.DeleteUptimeCheckConfig) .AddMethod(__Method_ListUptimeCheckIps, serviceImpl.ListUptimeCheckIps).Build(); } } } #endregion
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H09Level11111ReChild (editable child object).<br/> /// This is a generated base class of <see cref="H09Level11111ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="H08Level1111"/> collection. /// </remarks> [Serializable] public partial class H09Level11111ReChild : BusinessBase<H09Level11111ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1_1_1 Child Name.</value> public string Level_1_1_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="H09Level11111ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="H09Level11111ReChild"/> object.</returns> internal static H09Level11111ReChild NewH09Level11111ReChild() { return DataPortal.CreateChild<H09Level11111ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="H09Level11111ReChild"/> object, based on given parameters. /// </summary> /// <param name="cNarentID2">The CNarentID2 parameter of the H09Level11111ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="H09Level11111ReChild"/> object.</returns> internal static H09Level11111ReChild GetH09Level11111ReChild(int cNarentID2) { return DataPortal.FetchChild<H09Level11111ReChild>(cNarentID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H09Level11111ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private H09Level11111ReChild() { // 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="H09Level11111ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="H09Level11111ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="cNarentID2">The CNarent ID2.</param> protected void Child_Fetch(int cNarentID2) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetH09Level11111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@CNarentID2", cNarentID2).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, cNarentID2); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } BusinessRules.CheckRules(); } } /// <summary> /// Loads a <see cref="H09Level11111ReChild"/> 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_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="H09Level11111ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(H08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddH09Level11111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="H09Level11111ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(H08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateH09Level11111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="H09Level11111ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(H08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteH09Level11111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_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 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Xunit; namespace System.Tests { public partial class GetEnvironmentVariable { [Fact] public void InvalidArguments_ThrowsExceptions() { Assert.Throws<ArgumentNullException>("variable", () => Environment.GetEnvironmentVariable(null)); Assert.Throws<ArgumentNullException>("variable", () => Environment.SetEnvironmentVariable(null, "test")); Assert.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable("", "test")); Assert.Throws<ArgumentException>("value", () => Environment.SetEnvironmentVariable("test", new string('s', 65 * 1024))); Assert.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable("", "test", EnvironmentVariableTarget.Machine)); Assert.Throws<ArgumentNullException>("variable", () => Environment.SetEnvironmentVariable(null, "test", EnvironmentVariableTarget.User)); Assert.Throws<ArgumentNullException>("variable", () => Environment.GetEnvironmentVariable(null, EnvironmentVariableTarget.Process)); Assert.Throws<ArgumentOutOfRangeException>("target", () => Environment.GetEnvironmentVariable("test", (EnvironmentVariableTarget)42)); Assert.Throws<ArgumentOutOfRangeException>("target", () => Environment.SetEnvironmentVariable("test", "test", (EnvironmentVariableTarget)(-1))); Assert.Throws<ArgumentOutOfRangeException>("target", () => Environment.GetEnvironmentVariables((EnvironmentVariableTarget)(3))); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable(new string('s', 256), "value", EnvironmentVariableTarget.User)); } } [Fact] public void EmptyVariableReturnsNull() { Assert.Null(Environment.GetEnvironmentVariable(String.Empty)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // GetEnvironmentVariable by design doesn't respect changes via setenv public void RandomLongVariableNameCanRoundTrip() { // NOTE: The limit of 32766 characters enforced by desktop // SetEnvironmentVariable is antiquated. I was // able to create ~1GB names and values on my Windows 8.1 box. On // desktop, GetEnvironmentVariable throws OOM during its attempt to // demand huge EnvironmentPermission well before that. Also, the old // test for long name case wasn't very good: it just checked that an // arbitrary long name > 32766 characters returned null (not found), but // that had nothing to do with the limit, the variable was simply not // found! string variable = "LongVariable_" + new string('@', 33000); const string value = "TestValue"; try { SetEnvironmentVariableWithPInvoke(variable, value); Assert.Equal(value, Environment.GetEnvironmentVariable(variable)); } finally { SetEnvironmentVariableWithPInvoke(variable, null); } } [Fact] public void RandomVariableThatDoesNotExistReturnsNull() { string variable = "TestVariable_SurelyThisDoesNotExist"; Assert.Null(Environment.GetEnvironmentVariable(variable)); } [Fact] public void VariableNamesAreCaseInsensitiveAsAppropriate() { string value = "TestValue"; try { Environment.SetEnvironmentVariable("ThisIsATestEnvironmentVariable", value); Assert.Equal(value, Environment.GetEnvironmentVariable("ThisIsATestEnvironmentVariable")); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { value = null; } Assert.Equal(value, Environment.GetEnvironmentVariable("thisisatestenvironmentvariable")); Assert.Equal(value, Environment.GetEnvironmentVariable("THISISATESTENVIRONMENTVARIABLE")); Assert.Equal(value, Environment.GetEnvironmentVariable("ThISISATeSTENVIRoNMEnTVaRIABLE")); } finally { Environment.SetEnvironmentVariable("ThisIsATestEnvironmentVariable", null); } } [Fact] public void CanGetAllVariablesIndividually() { Random r = new Random(); string envVar1 = "TestVariable_CanGetVariablesIndividually_" + r.Next().ToString(); string envVar2 = "TestVariable_CanGetVariablesIndividually_" + r.Next().ToString(); try { Environment.SetEnvironmentVariable(envVar1, envVar1); Environment.SetEnvironmentVariable(envVar2, envVar2); IDictionary envBlock = Environment.GetEnvironmentVariables(); // Make sure the environment variables we set are part of the dictionary returned. Assert.True(envBlock.Contains(envVar1)); Assert.True(envBlock.Contains(envVar1)); // Make sure the values match the expected ones. Assert.Equal(envVar1, envBlock[envVar1]); Assert.Equal(envVar2, envBlock[envVar2]); // Make sure we can read the individual variables as well Assert.Equal(envVar1, Environment.GetEnvironmentVariable(envVar1)); Assert.Equal(envVar2, Environment.GetEnvironmentVariable(envVar2)); } finally { // Clear the variables we just set Environment.SetEnvironmentVariable(envVar1, null); Environment.SetEnvironmentVariable(envVar2, null); } } [Fact] public void EnumerateYieldsDictionaryEntryFromIEnumerable() { // GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable IDictionary vars = Environment.GetEnvironmentVariables(); IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator(); if (enumerator.MoveNext()) { Assert.IsType<DictionaryEntry>(enumerator.Current); } else { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } } [Fact] public void GetEnumerator_IDictionaryEnumerator_YieldsDictionaryEntries() { // GetEnvironmentVariables has always yielded DictionaryEntry from IDictionaryEnumerator IDictionary vars = Environment.GetEnvironmentVariables(); IDictionaryEnumerator enumerator = vars.GetEnumerator(); if (enumerator.MoveNext()) { Assert.IsType<DictionaryEntry>(enumerator.Current); } else { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } } [Theory] [InlineData(null)] [InlineData(EnvironmentVariableTarget.User)] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] public void GetEnumerator_LinqOverDictionaryEntries_Success(EnvironmentVariableTarget? target) { IDictionary envVars = target != null ? Environment.GetEnvironmentVariables(target.Value) : Environment.GetEnvironmentVariables(); Assert.IsType<Hashtable>(envVars); foreach (KeyValuePair<string, string> envVar in envVars.Cast<DictionaryEntry>().Select(de => new KeyValuePair<string, string>((string)de.Key, (string)de.Value))) { Assert.NotNull(envVar.Key); } } public void EnvironmentVariablesAreHashtable() { // On NetFX, the type returned was always Hashtable Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables()); } [Theory] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] [InlineData(EnvironmentVariableTarget.User)] public void EnvironmentVariablesAreHashtable(EnvironmentVariableTarget target) { // On NetFX, the type returned was always Hashtable Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables(target)); } [Theory] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] [InlineData(EnvironmentVariableTarget.User)] public void EnumerateYieldsDictionaryEntryFromIEnumerable(EnvironmentVariableTarget target) { // GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable IDictionary vars = Environment.GetEnvironmentVariables(target); IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator(); if (enumerator.MoveNext()) { Assert.IsType<DictionaryEntry>(enumerator.Current); } else { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } } [Theory] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] [InlineData(EnvironmentVariableTarget.User)] public void EnumerateEnvironmentVariables(EnvironmentVariableTarget target) { bool lookForSetValue = (target == EnvironmentVariableTarget.Process) || PlatformDetection.IsWindowsAndElevated; const string key = "EnumerateEnvironmentVariables"; string value = Path.GetRandomFileName(); try { if (lookForSetValue) { Environment.SetEnvironmentVariable(key, value, target); Assert.Equal(value, Environment.GetEnvironmentVariable(key, target)); } IDictionary results = Environment.GetEnvironmentVariables(target); // Ensure we can walk through the results IDictionaryEnumerator enumerator = results.GetEnumerator(); while (enumerator.MoveNext()) { Assert.NotNull(enumerator.Entry); } if (lookForSetValue) { // Ensure that we got our flagged value out Assert.Equal(value, results[key]); } } finally { if (lookForSetValue) { Environment.SetEnvironmentVariable(key, null, target); Assert.Null(Environment.GetEnvironmentVariable(key, target)); } } } private static void SetEnvironmentVariableWithPInvoke(string name, string value) { bool success = #if !Unix SetEnvironmentVariable(name, value); #else (value != null ? setenv(name, value, 1) : unsetenv(name)) == 0; #endif Assert.True(success); } [DllImport("kernel32.dll", EntryPoint = "SetEnvironmentVariableW" , CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool SetEnvironmentVariable(string lpName, string lpValue); #if Unix [DllImport("libc")] private static extern int setenv(string name, string value, int overwrite); [DllImport("libc")] private static extern int unsetenv(string name); #endif } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.Rule { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Xml; using ODataValidator.RuleEngine; /// <summary> /// Class of extension rule for Metadata.Core.2010 /// </summary> [Export(typeof(ExtensionRule))] public class MetadataCore2010 : ExtensionRule { /// <summary> /// Gets Category property /// </summary> public override string Category { get { return "core"; } } /// <summary> /// Gets rule name /// </summary> public override string Name { get { return "Metadata.Core.2010"; } } /// <summary> /// Gets rule description /// </summary> public override string Description { get { return "All mapped properties MUST be mapped to distinct elements within the Atom feed."; } } /// <summary> /// Gets rule specification in OData document /// </summary> public override string SpecificationSection { get { return "2.2.3.7.2.1"; } } /// <summary> /// Gets the version. /// </summary> public override ODataVersion? Version { get { return ODataVersion.V1_V2_V3; } } /// <summary> /// Gets location of help information of the rule /// </summary> public override string HelpLink { get { return null; } } /// <summary> /// Gets the error message for validation failure /// </summary> public override string ErrorMessage { get { return this.Description; } } /// <summary> /// Gets the requirement level. /// </summary> public override RequirementLevel RequirementLevel { get { return RequirementLevel.Must; } } /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Metadata; } } /// <summary> /// Gets the flag whether the rule requires metadata document /// </summary> public override bool? RequireMetadata { get { return true; } } /// <summary> /// Gets the offline context to which the rule applies /// </summary> public override bool? IsOfflineContext { get { return false; } } /// <summary> /// Gets the payload format to which the rule applies. /// </summary> public override PayloadFormat? PayloadFormat { get { return RuleEngine.PayloadFormat.Xml; } } /// <summary> /// Verify Metadata.Core.2010 /// </summary> /// <param name="context">Service context</param> /// <param name="info">out parameter to return violation information when rule fail</param> /// <returns>true if rule passes; false otherwise</returns> public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool? passed = null; info = null; // Adding all AtomPub mappings to a list List<string> atomPubMapping = new List<string>(new string[] { "SyndicationAuthorName", "SyndicationAuthorEmail", "SyndicationAuthorUri", "SyndicationPublished", "SyndicationRights", "SyndicationTitle", "SyndicationUpdated", "SyndicationContributorName", "SyndicationContributorEmail", "SyndicationContributorUri", "SyndicationSource", "SyndicationSummary" }); // Load MetadataDocument into XMLDOM XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(context.MetadataDocument); // Find all EntityType nodes XmlNodeList xmlNodeList = xmlDoc.SelectNodes("//*/*[local-name()='EntityType']"); // Make sure that properties are be mapped to distinct elements within the Atom feed foreach (XmlNode entityTypeNode in xmlNodeList) { bool duplicate = false; HashSet<string> atomPubMappingSet = new HashSet<string>(StringComparer.Ordinal); foreach (XmlNode node in entityTypeNode.ChildNodes) { if ((node.LocalName.Equals("Property", StringComparison.Ordinal)) && (node.Attributes["m:FC_TargetPath"] != null)) { if (atomPubMapping.Exists(item => item == node.Attributes["m:FC_TargetPath"].Value)) { if (!(atomPubMappingSet.Add(node.Attributes["m:FC_TargetPath"].Value))) { duplicate = true; break; } } } } if (duplicate) { passed = false; break; } else { passed = true; } } info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload); return passed; } } }
using System; using System.Linq; using UnityEditor; using UnityEditor.AnimatedValues; using UnityEngine; using UnityWeld.Binding; using UnityWeld.Binding.Internal; namespace UnityWeld_Editor { [CustomEditor(typeof(AnimatorParameterBinding))] public class AnimatorParameterBindingEditor : BaseBindingEditor { private AnimatorParameterBinding targetScript; private AnimBool viewAdapterOptionsFade; // Whether each property in the target differs from the prefab it uses. private bool viewAdapterPrefabModified; private bool viewAdapterOptionsPrefabModified; private bool viewModelPropertyPrefabModified; private bool viewPropertyPrefabModified; private void OnEnable() { // Initialise reference to target script targetScript = (AnimatorParameterBinding)target; Type adapterType; viewAdapterOptionsFade = new AnimBool( ShouldShowAdapterOptions(targetScript.ViewAdapterTypeName, out adapterType) ); viewAdapterOptionsFade.valueChanged.AddListener(Repaint); } private void OnDisable() { viewAdapterOptionsFade.valueChanged.RemoveListener(Repaint); } public override void OnInspectorGUI() { if(CannotModifyInPlayMode()) { return; } UpdatePrefabModifiedProperties(); var defaultLabelStyle = EditorStyles.label.fontStyle; EditorStyles.label.fontStyle = viewPropertyPrefabModified ? FontStyle.Bold : defaultLabelStyle; var animatorParameters = GetAnimatorParameters(); if (animatorParameters == null || !animatorParameters.Any()) { EditorGUILayout.HelpBox("Animator has no parameters!", MessageType.Warning); return; } Type viewPropertyType; ShowAnimatorParametersMenu( new GUIContent("View property", "Property on the view to bind to"), updatedValue => { targetScript.AnimatorParameterName = updatedValue.Name; targetScript.AnimatorParameterType = updatedValue.Type; }, new AnimatorParameterTypeAndName(targetScript.AnimatorParameterName, targetScript.AnimatorParameterType), animatorParameters, out viewPropertyType ); // Don't let the user set anything else until they've chosen a view property. var guiPreviouslyEnabled = GUI.enabled; if (string.IsNullOrEmpty(targetScript.AnimatorParameterName)) { GUI.enabled = false; } var viewAdapterTypeNames = GetAdapterTypeNames( type => viewPropertyType == null || TypeResolver.IsTypeCastableTo(TypeResolver.FindAdapterAttribute(type).OutputType, viewPropertyType) ); EditorStyles.label.fontStyle = viewAdapterPrefabModified ? FontStyle.Bold : defaultLabelStyle; ShowAdapterMenu( new GUIContent("View adapter", "Adapter that converts values sent from the view-model to the view."), viewAdapterTypeNames, targetScript.ViewAdapterTypeName, newValue => { // Get rid of old adapter options if we changed the type of the adapter. if (newValue != targetScript.ViewAdapterTypeName) { Undo.RecordObject(targetScript, "Set view adapter options"); targetScript.ViewAdapterOptions = null; } UpdateProperty( updatedValue => targetScript.ViewAdapterTypeName = updatedValue, targetScript.ViewAdapterTypeName, newValue, "Set view adapter" ); } ); Type adapterType; viewAdapterOptionsFade.target = ShouldShowAdapterOptions(targetScript.ViewAdapterTypeName, out adapterType); EditorStyles.label.fontStyle = viewAdapterOptionsPrefabModified ? FontStyle.Bold : defaultLabelStyle; ShowAdapterOptionsMenu( "View adapter options", adapterType, options => targetScript.ViewAdapterOptions = options, targetScript.ViewAdapterOptions, viewAdapterOptionsFade.faded ); EditorGUILayout.Space(); EditorStyles.label.fontStyle = viewModelPropertyPrefabModified ? FontStyle.Bold : defaultLabelStyle; var adaptedViewPropertyType = AdaptTypeBackward(viewPropertyType, targetScript.ViewAdapterTypeName); ShowViewModelPropertyMenu( new GUIContent("View-model property", "Property on the view-model to bind to."), TypeResolver.FindBindableProperties(targetScript), updatedValue => targetScript.ViewModelPropertyName = updatedValue, targetScript.ViewModelPropertyName, property => TypeResolver.IsTypeCastableTo(property.PropertyType, adaptedViewPropertyType) ); GUI.enabled = guiPreviouslyEnabled; EditorStyles.label.fontStyle = defaultLabelStyle; EditorGUILayout.Space(); } private void ShowAnimatorParametersMenu( GUIContent label, Action<AnimatorParameterTypeAndName> propertyValueSetter, AnimatorParameterTypeAndName curPropertyValue, AnimatorControllerParameter[] properties, out Type selectedPropertyType ) { if(properties == null || !properties.Any()) { selectedPropertyType = null; return; } var propertyNamesAndTypes = properties .Select(m => new AnimatorParameterTypeAndName(m.name, m.type)) .ToArray(); var selectedIndex = Array.IndexOf(propertyNamesAndTypes, curPropertyValue); var content = properties.Select(prop => new GUIContent(string.Concat( prop.name, " : ", prop.type.ToString() ))) .ToArray(); var newSelectedIndex = EditorGUILayout.Popup(label, selectedIndex, content); if (newSelectedIndex != selectedIndex) { var newSelectedProperty = properties[newSelectedIndex]; UpdateProperty( propertyValueSetter, curPropertyValue, new AnimatorParameterTypeAndName(newSelectedProperty.name, newSelectedProperty.type), "Set Animator parameter" ); selectedPropertyType = AnimatorControllerParameterTypeToType(newSelectedProperty.type); } else { if (selectedIndex < 0) { selectedPropertyType = null; return; } selectedPropertyType = AnimatorControllerParameterTypeToType(properties[selectedIndex].type); } } /// <summary> /// Returns the corresponding System.Type from AnimatorControllerParameterType /// </summary> /// <param name="parameterType">The type of parameter</param> /// <returns>The System.Type corresponding to paramter type</returns> private static Type AnimatorControllerParameterTypeToType( AnimatorControllerParameterType parameterType ) { switch (parameterType) { case AnimatorControllerParameterType.Bool: return typeof(bool); case AnimatorControllerParameterType.Float: return typeof(float); case AnimatorControllerParameterType.Int: return typeof(int); case AnimatorControllerParameterType.Trigger: return typeof(AnimatorParameterTrigger); default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Gets the Animator component on the targetScript and returns it's parameters /// </summary> /// <returns>An array of the Animator components parameters as UnityEngine.AnimatorControllerParameter</returns> private AnimatorControllerParameter[] GetAnimatorParameters() { var animator = targetScript.GetComponent<Animator>(); AnimatorControllerParameter[] properties; if(animator.runtimeAnimatorController == null) { return null; } // For whatever reason, accessing Animator.parameters while the GameObject the // Animator is on is inactive causes it to return an empty array, aswell as fill // the unity console with warnings. This behaviour is undocumented, and this is just // a work around which seems to work fine if (!animator.gameObject.activeInHierarchy) { var tPos = animator.transform.position; var tScale = animator.transform.localScale; var tRotation = animator.transform.rotation; var parent = animator.transform.parent; var siblingIndex = animator.transform.GetSiblingIndex(); var isActive = animator.gameObject.activeSelf; animator.transform.SetParent(null); animator.gameObject.SetActive(true); properties = animator.parameters; animator.transform.SetParent(parent); animator.transform.SetSiblingIndex(siblingIndex); animator.gameObject.SetActive(isActive); animator.transform.position = tPos; animator.transform.localScale = tScale; animator.transform.rotation = tRotation; } else { properties = animator.parameters; //Another odd fix to refresh the parameters //When the animator is active, & you add a trigger, or modify it's triggers, the parameters property //on the animator comes back empty, toggling it unactive, then back seems to fix the list of parameters returned. if (properties == null || properties.Length == 0) { var isActive = animator.gameObject.activeSelf; animator.gameObject.SetActive(false); animator.gameObject.SetActive(true); animator.gameObject.SetActive(isActive); properties = animator.parameters; } } return properties; } /// <summary> /// Check whether each of the properties on the object have been changed from the value in the prefab. /// </summary> private void UpdatePrefabModifiedProperties() { var property = serializedObject.GetIterator(); // Need to call Next(true) to get the first child. Once we have it, Next(false) // will iterate through the properties. property.Next(true); do { switch (property.name) { case "viewAdapterTypeName": viewAdapterPrefabModified = property.prefabOverride; break; case "viewAdapterOptions": viewAdapterOptionsPrefabModified = property.prefabOverride; break; case "viewModelPropertyName": viewModelPropertyPrefabModified = property.prefabOverride; break; case "animatorParameterType": case "animatorParameterName": viewPropertyPrefabModified = property.prefabOverride; break; } } while (property.Next(false)); } private class AnimatorParameterTypeAndName : IEquatable<AnimatorParameterTypeAndName> { public string Name { get; private set; } public AnimatorControllerParameterType Type { get; private set; } public AnimatorParameterTypeAndName(string name, AnimatorControllerParameterType type) { Name = name; Type = type; } public override int GetHashCode() { return new { Name, Type }.GetHashCode(); } public override bool Equals(object obj) { var objAsThis = obj as AnimatorParameterTypeAndName; if (objAsThis != null) { return Equals(objAsThis); } return false; } public bool Equals(AnimatorParameterTypeAndName other) { return other != null && other.Name == Name && other.Type == Type; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class SerialStream_BeginWrite : PortsTest { // The string size used for large byte array testing private const int LARGE_BUFFER_SIZE = 2048; // When we test Write and do not care about actually writing anything we must still // create an byte array to pass into the method the following is the size of the // byte array used in this situation private const int DEFAULT_BUFFER_SIZE = 1; private const int DEFAULT_BUFFER_OFFSET = 0; private const int DEFAULT_BUFFER_COUNT = 1; // The maximum buffer size when an exception occurs private const int MAX_BUFFER_SIZE_FOR_EXCEPTION = 255; // The maximum buffer size when an exception is not expected private const int MAX_BUFFER_SIZE = 8; // The default number of times the write method is called when verifying write private const int DEFAULT_NUM_WRITES = 3; // The default number of bytes to write private const int DEFAULT_NUM_BYTES_TO_WRITE = 128; // Maximum time to wait for processing the read command to complete private const int MAX_WAIT_WRITE_COMPLETE = 1000; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void Buffer_Null() { VerifyWriteException(null, 0, 1, typeof(ArgumentNullException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEG1() { VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], -1, DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEGRND() { Random rndGen = new Random(-55); VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], rndGen.Next(int.MinValue, 0), DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_MinInt() { VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], int.MinValue, DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEG1() { VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, -1, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEGRND() { Random rndGen = new Random(-55); VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_MinInt() { VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, int.MinValue, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void OffsetCount_EQ_Length_Plus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(0, bufferLength); int count = bufferLength + 1 - offset; Type expectedException = typeof(ArgumentException); VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasOneSerialPort))] public void OffsetCount_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(0, bufferLength); int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue); Type expectedException = typeof(ArgumentException); VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(bufferLength, int.MaxValue); int count = DEFAULT_BUFFER_COUNT; Type expectedException = typeof(ArgumentException); VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = DEFAULT_BUFFER_OFFSET; int count = rndGen.Next(bufferLength + 1, int.MaxValue); Type expectedException = typeof(ArgumentException); VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasNullModem))] public void OffsetCount_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = bufferLength - offset; VerifyWrite(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void Offset_EQ_Length_Minus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = bufferLength - 1; int count = 1; VerifyWrite(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void Count_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = 0; int count = bufferLength; VerifyWrite(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void ASCIIEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new byte[bufferLength], offset, count, new ASCIIEncoding()); } [ConditionalFact(nameof(HasNullModem))] public void UTF8Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new byte[bufferLength], offset, count, new UTF8Encoding()); } [ConditionalFact(nameof(HasNullModem))] public void UTF32Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new byte[bufferLength], offset, count, new UTF32Encoding()); } [ConditionalFact(nameof(HasNullModem))] public void UnicodeEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new byte[bufferLength], offset, count, new UnicodeEncoding()); } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void LargeBuffer() { int bufferLength = LARGE_BUFFER_SIZE; int offset = 0; int count = bufferLength; VerifyWrite(new byte[bufferLength], offset, count, 1); } [ConditionalFact(nameof(HasNullModem))] public void Callback() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { CallbackHandler callbackHandler = new CallbackHandler(); Debug.WriteLine("Verifying BeginWrite with a callback specified"); com1.Handshake = Handshake.RequestToSend; com2.ReadTimeout = 300; com1.Open(); com2.Open(); // RTS allows us to control when driver sends the data but does not // guarantee that data will not be consumed by driver // we can check if data was received on the other side though Action read = () => { com2.BaseStream.Read(new byte[DEFAULT_NUM_BYTES_TO_WRITE], 0, DEFAULT_NUM_BYTES_TO_WRITE); }; IAsyncResult writeAsyncResult = com1.BaseStream.BeginWrite(new byte[DEFAULT_NUM_BYTES_TO_WRITE], 0, DEFAULT_NUM_BYTES_TO_WRITE, callbackHandler.Callback, this); callbackHandler.BeginWriteAysncResult = writeAsyncResult; Assert.Equal(this, writeAsyncResult.AsyncState); Thread.Sleep(100); Assert.Throws<TimeoutException>(read); com2.RtsEnable = true; read(); // callbackHandler.WriteAysncResult guarantees that the callback has been called however it does not gauarentee that // the code calling the callback has finished it's processing IAsyncResult callbackWriteAsyncResult = callbackHandler.WriteAysncResult; // No we have to wait for the callbackHandler to complete int elapsedTime = 0; while (!callbackWriteAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_WRITE_COMPLETE) { Thread.Sleep(10); elapsedTime += 10; } Assert.Equal(this, callbackWriteAsyncResult.AsyncState); Assert.False(callbackWriteAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)"); Assert.True(callbackWriteAsyncResult.IsCompleted, "Should have completed (cback)"); Assert.Equal(this, writeAsyncResult.AsyncState); Assert.False(writeAsyncResult.CompletedSynchronously, "Should not have completed sync (write)"); Assert.True(writeAsyncResult.IsCompleted, "Should have completed (write)"); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Callback_State() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { CallbackHandler callbackHandler = new CallbackHandler(); Debug.WriteLine("Verifying BeginWrite with a callback and state specified"); com1.Open(); com2.Open(); Action read = () => { com2.BaseStream.Read(new byte[DEFAULT_NUM_BYTES_TO_WRITE], 0, DEFAULT_NUM_BYTES_TO_WRITE); }; IAsyncResult writeAsyncResult = com1.BaseStream.BeginWrite(new byte[DEFAULT_NUM_BYTES_TO_WRITE], 0, DEFAULT_NUM_BYTES_TO_WRITE, callbackHandler.Callback, this); callbackHandler.BeginWriteAysncResult = writeAsyncResult; Assert.Throws<TimeoutException>(read); com2.RtsEnable = true; read(); // callbackHandler.WriteAysncResult guarantees that the callback has been called however it does not gauarentee that // the code calling the callback has finished it's processing IAsyncResult callbackWriteAsyncResult = callbackHandler.WriteAysncResult; // No we have to wait for the callbackHandler to complete int elapsedTime = 0; while (!callbackWriteAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_WRITE_COMPLETE) { Thread.Sleep(10); elapsedTime += 10; } Assert.Equal(this, callbackWriteAsyncResult.AsyncState); Assert.False(writeAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)"); Assert.True(callbackWriteAsyncResult.IsCompleted, "Should have completed (cback)"); Assert.Equal(this, writeAsyncResult.AsyncState); Assert.False(writeAsyncResult.CompletedSynchronously, "Should not have completed sync (write)"); Assert.True(writeAsyncResult.IsCompleted, "Should have completed (write)"); } } [ConditionalFact(nameof(HasOneSerialPort))] public void InBreak() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying BeginWrite throws InvalidOperationException while in a Break"); com1.Open(); com1.BreakState = true; Assert.Throws<InvalidOperationException>(() => com1.BaseStream.BeginWrite(new byte[8], 0, 8, null, null)); } } #endregion #region Verification for Test Cases private void VerifyWriteException(byte[] buffer, int offset, int count, Type expectedException) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { int bufferLength = null == buffer ? 0 : buffer.Length; Debug.WriteLine("Verifying write method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); com.Open(); Assert.Throws(expectedException, () => com.BaseStream.BeginWrite(buffer, offset, count, null, null)); } } private void VerifyWrite(byte[] buffer, int offset, int count) { VerifyWrite(buffer, offset, count, new ASCIIEncoding()); } private void VerifyWrite(byte[] buffer, int offset, int count, int numWrites) { VerifyWrite(buffer, offset, count, new ASCIIEncoding(), numWrites); } private void VerifyWrite(byte[] buffer, int offset, int count, Encoding encoding) { VerifyWrite(buffer, offset, count, encoding, DEFAULT_NUM_WRITES); } private void VerifyWrite(byte[] buffer, int offset, int count, Encoding encoding, int numWrites) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); Debug.WriteLine("Verifying write method buffer.Lenght={0}, offset={1}, count={2}, endocing={3}", buffer.Length, offset, count, encoding.EncodingName); com1.Encoding = encoding; com2.Encoding = encoding; com1.Open(); com2.Open(); for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)rndGen.Next(0, 256); } VerifyWriteByteArray(buffer, offset, count, com1, com2, numWrites); } } private void VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPort com1, SerialPort com2, int numWrites) { int index = 0; CallbackHandler callbackHandler = new CallbackHandler(); var oldBuffer = (byte[])buffer.Clone(); var expectedBytes = new byte[count]; var actualBytes = new byte[expectedBytes.Length * numWrites]; for (int i = 0; i < count; i++) { expectedBytes[i] = buffer[i + offset]; } for (int i = 0; i < numWrites; i++) { IAsyncResult writeAsyncResult = com1.BaseStream.BeginWrite(buffer, offset, count, callbackHandler.Callback, this); com1.BaseStream.EndWrite(writeAsyncResult); callbackHandler.BeginWriteAysncResult = writeAsyncResult; IAsyncResult callbackWriteAsyncResult = callbackHandler.WriteAysncResult; Assert.Equal(this, callbackWriteAsyncResult.AsyncState); Assert.False(callbackWriteAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)"); Assert.True(callbackWriteAsyncResult.IsCompleted, "Should have completed (cback)"); Assert.Equal(this, writeAsyncResult.AsyncState); Assert.False(writeAsyncResult.CompletedSynchronously, "Should not have completed sync (write)"); Assert.True(writeAsyncResult.IsCompleted, "Should have completed (write)"); } com2.ReadTimeout = 500; Thread.Sleep((int)(((expectedBytes.Length * numWrites * 10.0) / com1.BaudRate) * 1000) + 250); // Make sure buffer was not altered during the write call for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != oldBuffer[i]) { Fail("ERROR!!!: The contents of the buffer were changed from {0} to {1} at {2}", oldBuffer[i], buffer[i], i); } } while (true) { int byteRead; try { byteRead = com2.ReadByte(); } catch (TimeoutException) { break; } if (actualBytes.Length <= index) { // If we have read in more bytes then we expect Fail("ERROR!!!: We have received more bytes then were sent"); break; } actualBytes[index] = (byte)byteRead; index++; if (actualBytes.Length - index != com2.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); } } // Compare the bytes that were read with the ones we expected to read for (int j = 0; j < numWrites; j++) { for (int i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != actualBytes[i + expectedBytes.Length * j]) { Fail("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], (int)actualBytes[i + expectedBytes.Length * j], i); } } } } private class CallbackHandler { private IAsyncResult _writeAysncResult; private IAsyncResult _beginWriteAysncResult; private readonly SerialPort _com; public CallbackHandler() : this(null) { } private CallbackHandler(SerialPort com) { _com = com; } public void Callback(IAsyncResult writeAysncResult) { Debug.WriteLine("About to enter callback lock (already entered {0})", Monitor.IsEntered(this)); lock (this) { Debug.WriteLine("Inside callback lock"); _writeAysncResult = writeAysncResult; if (!writeAysncResult.IsCompleted) { throw new Exception("Err_23984afaea Expected IAsyncResult passed into callback to not be completed"); } while (null == _beginWriteAysncResult) { Assert.True(Monitor.Wait(this, 5000), "Monitor.Wait in Callback"); } if (null != _beginWriteAysncResult && !_beginWriteAysncResult.IsCompleted) { throw new Exception("Err_7907azpu Expected IAsyncResult returned from begin write to not be completed"); } if (null != _com) { _com.BaseStream.EndWrite(_beginWriteAysncResult); if (!_beginWriteAysncResult.IsCompleted) { throw new Exception("Err_6498afead Expected IAsyncResult returned from begin write to not be completed"); } if (!writeAysncResult.IsCompleted) { throw new Exception("Err_1398ehpo Expected IAsyncResult passed into callback to not be completed"); } } Monitor.Pulse(this); } } public IAsyncResult WriteAysncResult { get { lock (this) { while (null == _writeAysncResult) { Monitor.Wait(this); } return _writeAysncResult; } } } public IAsyncResult BeginWriteAysncResult { get { return _beginWriteAysncResult; } set { lock (this) { _beginWriteAysncResult = value; Monitor.Pulse(this); } } } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; #if !NET461 using System.Runtime.Loader; #endif namespace BaselineTypeDiscovery { internal static class BaselineAssemblyContext { #if NET461 public static readonly IBaselineAssemblyLoadContext Loader = new CustomAssemblyLoadContext(); #else public static readonly IBaselineAssemblyLoadContext Loader = new AssemblyLoadContextWrapper(System.Runtime.Loader.AssemblyLoadContext.Default); #endif } /// <summary> /// Utility to discover and load assemblies installed in your application for extensibility or plugin schems /// </summary> public static class AssemblyFinder { /// <summary> /// Find assemblies in the application's binary path /// </summary> /// <param name="logFailure">Take an action when an assembly file could not be loaded</param> /// <param name="includeExeFiles">Optionally include *.exe files</param> /// <returns></returns> public static IEnumerable<Assembly> FindAssemblies(Action<string> logFailure, Func<Assembly, bool> filter, bool includeExeFiles) { string path; try { path = AppContext.BaseDirectory; } catch (Exception) { path = System.IO.Directory.GetCurrentDirectory(); } return FindAssemblies(filter, path, logFailure, includeExeFiles); } /// <summary> /// Find assemblies in the given path /// </summary> /// <param name="assemblyPath">The path to probe for assembly files</param> /// <param name="logFailure">Take an action when an assembly file could not be loaded</param> /// <param name="includeExeFiles">Optionally include *.exe files</param> /// <returns></returns> public static IEnumerable<Assembly> FindAssemblies(Func<Assembly, bool> filter, string assemblyPath, Action<string> logFailure, bool includeExeFiles) { var assemblies = findAssemblies(assemblyPath, logFailure, includeExeFiles) .Where(filter) .OrderBy(x => x.GetName().Name) .ToArray(); Assembly[] FindDependencies(Assembly a) => assemblies.Where(x => a.GetReferencedAssemblies().Any(_ => _.Name == x.GetName().Name)).ToArray(); return assemblies.TopologicalSort((Func<Assembly, Assembly[]>) FindDependencies, throwOnCycle:false); } private static IEnumerable<Assembly> findAssemblies(string assemblyPath, Action<string> logFailure, bool includeExeFiles) { var dllFiles = Directory.EnumerateFiles(assemblyPath, "*.dll", SearchOption.AllDirectories); var files = dllFiles; if (includeExeFiles) { var exeFiles = Directory.EnumerateFiles(assemblyPath, "*.exe", SearchOption.AllDirectories); files = dllFiles.Concat(exeFiles); } foreach (var file in files) { var name = Path.GetFileNameWithoutExtension(file); Assembly assembly = null; try { assembly = BaselineAssemblyContext.Loader.LoadFromAssemblyName(new AssemblyName(name)); } catch (Exception) { try { assembly = BaselineAssemblyContext.Loader.LoadFromAssemblyPath(file); } catch (Exception) { logFailure(file); } } if (assembly != null) { yield return assembly; } } } /// <summary> /// Find assembly files matching a given filter /// </summary> /// <param name="filter"></param> /// <param name="onDirectoryFound"></param> /// <param name="includeExeFiles"></param> /// <returns></returns> public static IEnumerable<Assembly> FindAssemblies(Func<Assembly, bool> filter, Action<string> onDirectoryFound = null, bool includeExeFiles=false) { if (filter == null) { filter = a => true; } if (onDirectoryFound == null) { onDirectoryFound = dir => { }; } return FindAssemblies(file => { }, filter, includeExeFiles: includeExeFiles); } } internal interface IBaselineAssemblyLoadContext { Assembly LoadFromStream(Stream assembly); Assembly LoadFromAssemblyName(AssemblyName assemblyName); Assembly LoadFromAssemblyPath(string assemblyName); } #if !NET461 public sealed class CustomAssemblyLoadContext : AssemblyLoadContext, IBaselineAssemblyLoadContext { protected override Assembly Load(AssemblyName assemblyName) { return Assembly.Load(assemblyName); } Assembly IBaselineAssemblyLoadContext.LoadFromAssemblyName(AssemblyName assemblyName) { return Load(assemblyName); } } public sealed class AssemblyLoadContextWrapper : IBaselineAssemblyLoadContext { private readonly AssemblyLoadContext ctx; public AssemblyLoadContextWrapper(AssemblyLoadContext ctx) { this.ctx = ctx; } public Assembly LoadFromStream(Stream assembly) { return ctx.LoadFromStream(assembly); } public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { return ctx.LoadFromAssemblyName(assemblyName); } public Assembly LoadFromAssemblyPath(string assemblyName) { return ctx.LoadFromAssemblyPath(assemblyName); } } #else public class CustomAssemblyLoadContext : IBaselineAssemblyLoadContext { public Assembly LoadFromStream(Stream assembly) { if (assembly is MemoryStream memStream) { return Assembly.Load(memStream.ToArray()); } using (var stream = new MemoryStream()) { assembly.CopyTo(stream); return Assembly.Load(stream.ToArray()); } } Assembly IBaselineAssemblyLoadContext.LoadFromAssemblyName(AssemblyName assemblyName) { return Assembly.Load(assemblyName); } public Assembly LoadFromAssemblyPath(string assemblyName) { return Assembly.LoadFrom(assemblyName); } public Assembly LoadFromAssemblyName(string assemblyName) { return Assembly.Load(assemblyName); } } #endif internal static class TopologicalSortExtensions { /// <summary> /// Performs a topological sort on the enumeration based on dependencies /// </summary> /// <param name="source"></param> /// <param name="dependencies"></param> /// <param name="throwOnCycle"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IEnumerable<T> TopologicalSort<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> dependencies, bool throwOnCycle = true) { var sorted = new List<T>(); var visited = new HashSet<T>(); foreach (var item in source) { Visit(item, visited, sorted, dependencies, throwOnCycle); } return sorted; } private static void Visit<T>(T item, ISet<T> visited, ICollection<T> sorted, Func<T, IEnumerable<T>> dependencies, bool throwOnCycle) { if (visited.Contains(item)) { if (throwOnCycle && !sorted.Contains(item)) { throw new Exception("Cyclic dependency found"); } } else { visited.Add(item); foreach (var dep in dependencies(item)) { Visit(dep, visited, sorted, dependencies, throwOnCycle); } sorted.Add(item); } } } }
/* * Vericred API * * Vericred's API allows you to search for Health Plans that a specific doctor accepts. ## Getting Started Visit our [Developer Portal](https://developers.vericred.com) to create an account. Once you have created an account, you can create one Application for Production and another for our Sandbox (select the appropriate Plan when you create the Application). ## SDKs Our API follows standard REST conventions, so you can use any HTTP client to integrate with us. You will likely find it easier to use one of our [autogenerated SDKs](https://github.com/vericred/?query=vericred-), which we make available for several common programming languages. ## Authentication To authenticate, pass the API Key you created in the Developer Portal as a `Vericred-Api-Key` header. `curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Versioning Vericred's API default to the latest version. However, if you need a specific version, you can request it with an `Accept-Version` header. The current version is `v3`. Previous versions are `v1` and `v2`. `curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Pagination Endpoints that accept `page` and `per_page` parameters are paginated. They expose four additional fields that contain data about your position in the response, namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988). For example, to display 5 results per page and view the second page of a `GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`. ## Sideloading When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s we sideload the associated data. In this example, we would provide an Array of `State`s and a `state_id` for each provider. This is done primarily to reduce the payload size since many of the `Provider`s will share a `State` ``` { providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }], states: [{ id: 1, code: 'NY' }] } ``` If you need the second level of the object graph, you can just match the corresponding id. ## Selecting specific data All endpoints allow you to specify which fields you would like to return. This allows you to limit the response to contain only the data you need. For example, let's take a request that returns the following JSON by default ``` { provider: { id: 1, name: 'John', phone: '1234567890', field_we_dont_care_about: 'value_we_dont_care_about' }, states: [{ id: 1, name: 'New York', code: 'NY', field_we_dont_care_about: 'value_we_dont_care_about' }] } ``` To limit our results to only return the fields we care about, we specify the `select` query string parameter for the corresponding fields in the JSON document. In this case, we want to select `name` and `phone` from the `provider` key, so we would add the parameters `select=provider.name,provider.phone`. We also want the `name` and `code` from the `states` key, so we would add the parameters `select=states.name,staes.code`. The id field of each document is always returned whether or not it is requested. Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code` The response would be ``` { provider: { id: 1, name: 'John', phone: '1234567890' }, states: [{ id: 1, name: 'New York', code: 'NY' }] } ``` ## Benefits summary format Benefit cost-share strings are formatted to capture: * Network tiers * Compound or conditional cost-share * Limits on the cost-share * Benefit-specific maximum out-of-pocket costs **Example #1** As an example, we would represent [this Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as: * **Hospital stay facility fees**: - Network Provider: `$400 copay/admit plus 20% coinsurance` - Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance` - Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible` * **Rehabilitation services:** - Network Provider: `20% coinsurance` - Out-of-Network Provider: `50% coinsurance` - Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.` - Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period` **Example #2** In [this other Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies. * **Specialty drugs:** - Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply` - Out-of-Network Provider `Not covered` - Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%` **BNF** Here's a description of the benefits summary string, represented as a context-free grammar: ``` <cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit> <tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:" <opt-num-prefix> ::= "first" <num> <unit> | "" <unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)" <value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable" <compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible> <copay> ::= "$" <num> <coinsurace> ::= <num> "%" <ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited" <opt-per-unit> ::= "per day" | "per visit" | "per stay" | "" <deductible> ::= "before deductible" | "after deductible" | "" <tier-limit> ::= ", " <limit> | "" <benefit-limit> ::= <limit> | "" ``` * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IO.Vericred.Model { /// <summary> /// DrugCoverageResponse /// </summary> [DataContract] public partial class DrugCoverageResponse : IEquatable<DrugCoverageResponse> { /// <summary> /// Initializes a new instance of the <see cref="DrugCoverageResponse" /> class. /// </summary> /// <param name="Meta">Meta-data.</param> /// <param name="DrugCoverages">DrugCoverage search results.</param> /// <param name="Drugs">Drug.</param> /// <param name="DrugPackages">Drug Packages.</param> public DrugCoverageResponse(Meta Meta = null, List<DrugCoverage> DrugCoverages = null, List<Drug> Drugs = null, List<DrugPackage> DrugPackages = null) { this.Meta = Meta; this.DrugCoverages = DrugCoverages; this.Drugs = Drugs; this.DrugPackages = DrugPackages; } /// <summary> /// Meta-data /// </summary> /// <value>Meta-data</value> [DataMember(Name="meta", EmitDefaultValue=false)] public Meta Meta { get; set; } /// <summary> /// DrugCoverage search results /// </summary> /// <value>DrugCoverage search results</value> [DataMember(Name="drug_coverages", EmitDefaultValue=false)] public List<DrugCoverage> DrugCoverages { get; set; } /// <summary> /// Drug /// </summary> /// <value>Drug</value> [DataMember(Name="drugs", EmitDefaultValue=false)] public List<Drug> Drugs { get; set; } /// <summary> /// Drug Packages /// </summary> /// <value>Drug Packages</value> [DataMember(Name="drug_packages", EmitDefaultValue=false)] public List<DrugPackage> DrugPackages { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DrugCoverageResponse {\n"); sb.Append(" Meta: ").Append(Meta).Append("\n"); sb.Append(" DrugCoverages: ").Append(DrugCoverages).Append("\n"); sb.Append(" Drugs: ").Append(Drugs).Append("\n"); sb.Append(" DrugPackages: ").Append(DrugPackages).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as DrugCoverageResponse); } /// <summary> /// Returns true if DrugCoverageResponse instances are equal /// </summary> /// <param name="other">Instance of DrugCoverageResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(DrugCoverageResponse other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Meta == other.Meta || this.Meta != null && this.Meta.Equals(other.Meta) ) && ( this.DrugCoverages == other.DrugCoverages || this.DrugCoverages != null && this.DrugCoverages.SequenceEqual(other.DrugCoverages) ) && ( this.Drugs == other.Drugs || this.Drugs != null && this.Drugs.SequenceEqual(other.Drugs) ) && ( this.DrugPackages == other.DrugPackages || this.DrugPackages != null && this.DrugPackages.SequenceEqual(other.DrugPackages) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Meta != null) hash = hash * 59 + this.Meta.GetHashCode(); if (this.DrugCoverages != null) hash = hash * 59 + this.DrugCoverages.GetHashCode(); if (this.Drugs != null) hash = hash * 59 + this.Drugs.GetHashCode(); if (this.DrugPackages != null) hash = hash * 59 + this.DrugPackages.GetHashCode(); return hash; } } } }
using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGenerator.SyntaxGeneration; using static Orleans.CodeGenerator.SerializerGenerator; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Orleans.CodeGenerator { internal static class FSharpUtilities { private const int SourceConstructFlagsSumTypeValue = 1; private const int SourceConstructFlagsRecordTypeValue = 2; public static bool IsUnionCase(LibraryTypes libraryTypes, INamedTypeSymbol symbol, out INamedTypeSymbol sumType) { sumType = default; var compilationAttributeType = libraryTypes.FSharpCompilationMappingAttributeOrDefault; var sourceConstructFlagsType = libraryTypes.FSharpSourceConstructFlagsOrDefault; var baseType = symbol.BaseType; if (compilationAttributeType is null || sourceConstructFlagsType is null || baseType is null) { return false; } if (!baseType.GetAttributes(compilationAttributeType, out var compilationAttributes) || compilationAttributes.Length == 0) { return false; } var compilationAttribute = compilationAttributes[0]; var foundArg = false; TypedConstant sourceConstructFlagsArgument = default; foreach (var arg in compilationAttribute.ConstructorArguments) { if (SymbolEqualityComparer.Default.Equals(arg.Type, sourceConstructFlagsType)) { sourceConstructFlagsArgument = arg; foundArg = true; break; } } if (!foundArg) { return false; } if ((int)sourceConstructFlagsArgument.Value != SourceConstructFlagsSumTypeValue) { return false; } sumType = baseType; return true; } public static bool IsRecord(LibraryTypes libraryTypes, INamedTypeSymbol symbol) { var compilationAttributeType = libraryTypes.FSharpCompilationMappingAttributeOrDefault; var sourceConstructFlagsType = libraryTypes.FSharpSourceConstructFlagsOrDefault; if (compilationAttributeType is null || sourceConstructFlagsType is null) { return false; } if (!symbol.GetAttributes(compilationAttributeType, out var compilationAttributes) || compilationAttributes.Length == 0) { return false; } var compilationAttribute = compilationAttributes[0]; var foundArg = false; TypedConstant sourceConstructFlagsArgument = default; foreach (var arg in compilationAttribute.ConstructorArguments) { if (SymbolEqualityComparer.Default.Equals(arg.Type, sourceConstructFlagsType)) { sourceConstructFlagsArgument = arg; foundArg = true; break; } } if (!foundArg) { return false; } if ((int)sourceConstructFlagsArgument.Value != SourceConstructFlagsRecordTypeValue) { return false; } return true; } public class FSharpUnionCaseTypeDescription : SerializableTypeDescription { public FSharpUnionCaseTypeDescription(SemanticModel semanticModel, INamedTypeSymbol type, LibraryTypes libraryTypes) : base(semanticModel, type, GetUnionCaseDataMembers(libraryTypes, type), libraryTypes) { } private static IEnumerable<IMemberDescription> GetUnionCaseDataMembers(LibraryTypes libraryTypes, INamedTypeSymbol symbol) { List<IPropertySymbol> dataMembers = new(); foreach (var property in symbol.GetDeclaredInstanceMembers<IPropertySymbol>()) { if (!property.Name.StartsWith("Item", System.StringComparison.Ordinal)) { continue; } dataMembers.Add(property); } dataMembers.Sort(FSharpUnionCasePropertyNameComparer.Default); ushort id = 0; foreach (var field in dataMembers) { yield return new FSharpUnionCaseFieldDescription(libraryTypes, field, id); id++; } } private class FSharpUnionCasePropertyNameComparer : IComparer<IPropertySymbol> { public static FSharpUnionCasePropertyNameComparer Default { get; } = new FSharpUnionCasePropertyNameComparer(); public int Compare(IPropertySymbol x, IPropertySymbol y) { var xName = x.Name; var yName = y.Name; if (xName.Length > yName.Length) { return 1; } if (xName.Length < yName.Length) { return -1; } return string.CompareOrdinal(xName, yName); } } private class FSharpUnionCaseFieldDescription : IMemberDescription, ISerializableMember { private readonly LibraryTypes _libraryTypes; private readonly IPropertySymbol _property; public FSharpUnionCaseFieldDescription(LibraryTypes libraryTypes, IPropertySymbol property, ushort ordinal) { _libraryTypes = libraryTypes; FieldId = ordinal; _property = property; } public ushort FieldId { get; } public bool IsShallowCopyable => _libraryTypes.IsShallowCopyable(Type) || _property.HasAnyAttribute(_libraryTypes.ImmutableAttributes); public bool IsValueType => Type.IsValueType; public IMemberDescription Member => this; public ITypeSymbol Type => _property.Type; public INamedTypeSymbol ContainingType => _property.ContainingType; public ISymbol Symbol => _property; public string FieldName => _property.Name.ToLowerInvariant(); /// <summary> /// Gets the name of the setter field. /// </summary> private string SetterFieldName => "setField" + FieldId; /// <summary> /// Gets syntax representing the type of this field. /// </summary> public TypeSyntax TypeSyntax => Type.TypeKind == TypeKind.Dynamic ? PredefinedType(Token(SyntaxKind.ObjectKeyword)) : GetTypeSyntax(Type); /// <summary> /// Gets the <see cref="Property"/> which this field is the backing property for, or /// <see langword="null" /> if this is not the backing field of an auto-property. /// </summary> private IPropertySymbol Property => _property; public string AssemblyName => Type.ContainingAssembly.ToDisplayName(); public string TypeName => Type.ToDisplayName(); public string TypeNameIdentifier => Type.GetValidIdentifier(); public TypeSyntax GetTypeSyntax(ITypeSymbol typeSymbol) => typeSymbol.ToTypeSyntax(); /// <summary> /// Returns syntax for retrieving the value of this field, deep copying it if necessary. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <returns>Syntax for retrieving the value of this field.</returns> public ExpressionSyntax GetGetter(ExpressionSyntax instance) => instance.Member(Property.Name); /// <summary> /// Returns syntax for setting the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="value">Syntax for the new value.</param> /// <returns>Syntax for setting the value of this field.</returns> public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value) { var instanceArg = Argument(instance); if (ContainingType != null && ContainingType.IsValueType) { instanceArg = instanceArg.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)); } return InvocationExpression(IdentifierName(SetterFieldName)) .AddArgumentListArguments(instanceArg, Argument(value)); } public GetterFieldDescription GetGetterFieldDescription() => null; public SetterFieldDescription GetSetterFieldDescription() { TypeSyntax fieldType; if (ContainingType != null && ContainingType.IsValueType) { fieldType = _libraryTypes.ValueTypeSetter_2.ToTypeSyntax(GetTypeSyntax(ContainingType), TypeSyntax); } else { fieldType = _libraryTypes.Action_2.ToTypeSyntax(GetTypeSyntax(ContainingType), TypeSyntax); } // Generate syntax to initialize the field in the constructor var fieldAccessorUtility = AliasQualifiedName("global", IdentifierName("Orleans.Serialization")).Member("Utilities").Member("FieldAccessor"); var fieldInfo = SerializableMember.GetGetFieldInfoExpression(ContainingType, FieldName); var isContainedByValueType = ContainingType != null && ContainingType.IsValueType; var accessorMethod = isContainedByValueType ? "GetValueSetter" : "GetReferenceSetter"; var accessorInvoke = CastExpression( fieldType, InvocationExpression(fieldAccessorUtility.Member(accessorMethod)) .AddArgumentListArguments(Argument(fieldInfo))); var initializationSyntax = ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(SetterFieldName), accessorInvoke)); return new SetterFieldDescription(fieldType, SetterFieldName, initializationSyntax); } } } public class FSharpRecordTypeDescription : SerializableTypeDescription { public FSharpRecordTypeDescription(SemanticModel semanticModel, INamedTypeSymbol type, LibraryTypes libraryTypes) : base(semanticModel, type, GetRecordDataMembers(libraryTypes, type), libraryTypes) { } private static IEnumerable<IMemberDescription> GetRecordDataMembers(LibraryTypes libraryTypes, INamedTypeSymbol symbol) { List<(IPropertySymbol, ushort)> dataMembers = new(); foreach (var property in symbol.GetDeclaredInstanceMembers<IPropertySymbol>()) { var id = CodeGenerator.GetId(libraryTypes, property); if (!id.HasValue) { continue; } dataMembers.Add((property, id.Value)); } foreach (var (property, id) in dataMembers) { yield return new FSharpRecordPropertyDescription(libraryTypes, property, id); } } private class FSharpRecordPropertyDescription : IMemberDescription, ISerializableMember { private readonly LibraryTypes _libraryTypes; private readonly IPropertySymbol _property; public FSharpRecordPropertyDescription(LibraryTypes libraryTypes, IPropertySymbol property, ushort ordinal) { _libraryTypes = libraryTypes; FieldId = ordinal; _property = property; } public ushort FieldId { get; } public bool IsShallowCopyable => _libraryTypes.IsShallowCopyable(Type) || _property.HasAnyAttribute(_libraryTypes.ImmutableAttributes); public bool IsValueType => Type.IsValueType; public IMemberDescription Member => this; public ITypeSymbol Type => _property.Type; public ISymbol Symbol => _property; public INamedTypeSymbol ContainingType => _property.ContainingType; public string FieldName => _property.Name + "@"; /// <summary> /// Gets the name of the setter field. /// </summary> private string SetterFieldName => "setField" + FieldId; /// <summary> /// Gets syntax representing the type of this field. /// </summary> public TypeSyntax TypeSyntax => Type.TypeKind == TypeKind.Dynamic ? PredefinedType(Token(SyntaxKind.ObjectKeyword)) : GetTypeSyntax(Type); /// <summary> /// Gets the <see cref="Property"/> which this field is the backing property for, or /// <see langword="null" /> if this is not the backing field of an auto-property. /// </summary> private IPropertySymbol Property => _property; public string AssemblyName => Type.ContainingAssembly.ToDisplayName(); public string TypeName => Type.ToDisplayName(); public string TypeNameIdentifier => Type.GetValidIdentifier(); public TypeSyntax GetTypeSyntax(ITypeSymbol typeSymbol) => typeSymbol.ToTypeSyntax(); /// <summary> /// Returns syntax for retrieving the value of this field, deep copying it if necessary. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <returns>Syntax for retrieving the value of this field.</returns> public ExpressionSyntax GetGetter(ExpressionSyntax instance) => instance.Member(Property.Name); /// <summary> /// Returns syntax for setting the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="value">Syntax for the new value.</param> /// <returns>Syntax for setting the value of this field.</returns> public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value) { var instanceArg = Argument(instance); if (ContainingType != null && ContainingType.IsValueType) { instanceArg = instanceArg.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)); } return InvocationExpression(IdentifierName(SetterFieldName)) .AddArgumentListArguments(instanceArg, Argument(value)); } public GetterFieldDescription GetGetterFieldDescription() => null; public SetterFieldDescription GetSetterFieldDescription() { TypeSyntax fieldType; if (ContainingType != null && ContainingType.IsValueType) { fieldType = _libraryTypes.ValueTypeSetter_2.ToTypeSyntax(GetTypeSyntax(ContainingType), TypeSyntax); } else { fieldType = _libraryTypes.Action_2.ToTypeSyntax(GetTypeSyntax(ContainingType), TypeSyntax); } // Generate syntax to initialize the field in the constructor var fieldAccessorUtility = AliasQualifiedName("global", IdentifierName("Orleans.Serialization")).Member("Utilities").Member("FieldAccessor"); var fieldInfo = SerializableMember.GetGetFieldInfoExpression(ContainingType, FieldName); var isContainedByValueType = ContainingType != null && ContainingType.IsValueType; var accessorMethod = isContainedByValueType ? "GetValueSetter" : "GetReferenceSetter"; var accessorInvoke = CastExpression( fieldType, InvocationExpression(fieldAccessorUtility.Member(accessorMethod)) .AddArgumentListArguments(Argument(fieldInfo))); var initializationSyntax = ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(SetterFieldName), accessorInvoke)); return new SetterFieldDescription(fieldType, SetterFieldName, initializationSyntax); } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; namespace Microsoft.AzureStack.Management { public static partial class CloudOperationsExtensions { /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.ICloudOperations. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static CloudCreateOrUpdateResult CreateOrUpdate(this ICloudOperations operations, CloudCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ICloudOperations)s).CreateOrUpdateAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.ICloudOperations. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<CloudCreateOrUpdateResult> CreateOrUpdateAsync(this ICloudOperations operations, CloudCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(parameters, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.ICloudOperations. /// </param> /// <param name='cloudId'> /// Required. Your documentation here. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this ICloudOperations operations, string cloudId) { return Task.Factory.StartNew((object s) => { return ((ICloudOperations)s).DeleteAsync(cloudId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.ICloudOperations. /// </param> /// <param name='cloudId'> /// Required. Your documentation here. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this ICloudOperations operations, string cloudId) { return operations.DeleteAsync(cloudId, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.ICloudOperations. /// </param> /// <param name='cloudId'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static CloudGetResult Get(this ICloudOperations operations, string cloudId) { return Task.Factory.StartNew((object s) => { return ((ICloudOperations)s).GetAsync(cloudId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.ICloudOperations. /// </param> /// <param name='cloudId'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<CloudGetResult> GetAsync(this ICloudOperations operations, string cloudId) { return operations.GetAsync(cloudId, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.ICloudOperations. /// </param> /// <returns> /// Your documentation here. /// </returns> public static CloudListResult List(this ICloudOperations operations) { return Task.Factory.StartNew((object s) => { return ((ICloudOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.ICloudOperations. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<CloudListResult> ListAsync(this ICloudOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.ICloudOperations. /// </param> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static CloudListResult ListNext(this ICloudOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((ICloudOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.ICloudOperations. /// </param> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<CloudListResult> ListNextAsync(this ICloudOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } } }
// Copyright 2009-2013 Nikita Govorov // 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.Data; using System.Diagnostics.CodeAnalysis; using Taijutsu.Annotation; using Taijutsu.Data.Internal; using Taijutsu.Domain; using Taijutsu.Domain.Query; namespace Taijutsu.Data { [PublicApi] public class UnitOfWork : IUnitOfWork, IDisposable, IWrapper { private readonly IDataContext dataContext; private bool disposed; private bool? completed; public UnitOfWork([NotNull] string source = "", IsolationLevel? isolation = null, Require require = Require.None) : this(new UnitOfWorkConfig(source, isolation ?? IsolationLevel.Unspecified, require)) { } public UnitOfWork(IsolationLevel? isolation = null) : this(new UnitOfWorkConfig(string.Empty, isolation ?? IsolationLevel.Unspecified, Require.None)) { } public UnitOfWork(Require require) : this(new UnitOfWorkConfig(string.Empty, IsolationLevel.Unspecified, require)) { } public UnitOfWork([NotNull] string source) : this(new UnitOfWorkConfig(source, IsolationLevel.Unspecified, Require.None)) { } public UnitOfWork([NotNull] string source = "", Require require = Require.None) : this(new UnitOfWorkConfig(source, IsolationLevel.Unspecified, require)) { } public UnitOfWork([NotNull] string source = "", IsolationLevel? isolation = null) : this(new UnitOfWorkConfig(source, isolation ?? IsolationLevel.Unspecified, Require.None)) { } public UnitOfWork() : this(new UnitOfWorkConfig(string.Empty, IsolationLevel.Unspecified, Require.None)) { } public UnitOfWork([NotNull] UnitOfWorkConfig unitOfWorkConfig) { if (unitOfWorkConfig == null) { throw new ArgumentNullException("unitOfWorkConfig"); } dataContext = InternalEnvironment.DataContextSupervisor.Register(unitOfWorkConfig); } object IWrapper.WrappedObject { get { return WrappedObject; } } protected virtual object WrappedObject { get { AssertNotDisposed(); return dataContext.Session.WrappedObject; } } [SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "Reviewed. The method is supposed to be used only by using block.")] void IDisposable.Dispose() { Dispose(true); } public virtual void Complete() { AssertNotDisposed(); if (completed.HasValue) { if (!completed.Value) { throw new Exception(string.Format("Unit of work has already been completed without success.")); } return; } try { dataContext.Complete(); completed = true; } catch { completed = false; throw; } } public virtual T Complete<T>([NotNull] Func<IUnitOfWork, T> toReturn) { AssertNotDisposed(); var result = toReturn(this); Complete(); return result; } public virtual T Complete<T>([NotNull] Func<T> toReturn) { AssertNotDisposed(); var result = toReturn(); Complete(); return result; } public virtual T Complete<T>(T toReturn) { AssertNotDisposed(); Complete(); return toReturn; } public virtual object MarkAsCreated<TEntity>(TEntity entity, object options = null) where TEntity : IAggregateRoot { AssertNotCompleted(); return dataContext.Session.MarkAsCreated(entity, options); } public virtual object MarkAsCreated<TEntity>(Func<TEntity> entityFactory, object options = null) where TEntity : IAggregateRoot { AssertNotCompleted(); return dataContext.Session.MarkAsCreated(entityFactory, options); } public virtual void MarkAsDeleted<TEntity>(TEntity entity, object options = null) where TEntity : IDeletableEntity { AssertNotCompleted(); dataContext.Session.MarkAsDeleted(entity, options); } public virtual IEntitiesQuery<TEntity> All<TEntity>(object options = null) where TEntity : class, IQueryableEntity { AssertNotDisposed(); return dataContext.Session.All<TEntity>(options); } public virtual IUniqueEntityQuery<TEntity> Unique<TEntity>(object id, object options = null) where TEntity : class, IQueryableEntity { AssertNotDisposed(); return dataContext.Session.Unique<TEntity>(id, options); } protected virtual void Dispose(bool disposing) { if (disposed || !disposing) { return; } try { try { if (!completed.HasValue) { completed = false; } dataContext.Dispose(); } finally { InternalEnvironment.CheckDataContextSupervisorForRelease(); } } finally { disposed = true; } } protected virtual void AssertNotCompleted() { if (completed.HasValue) { throw new Exception(string.Format("Unit of work has already been completed(with success - '{0}'), so it is not usable for write anymore.", completed)); } } protected virtual void AssertNotDisposed() { if (disposed) { throw new Exception(string.Format("Unit of work has already been disposed(with success - '{0}'), so it is not usable anymore.", completed)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Http.Headers; using System.Text; namespace System.Net.Http { public class HttpResponseMessage : IDisposable { private const HttpStatusCode defaultStatusCode = HttpStatusCode.OK; private HttpStatusCode _statusCode; private HttpResponseHeaders _headers; private HttpResponseHeaders _trailingHeaders; private string _reasonPhrase; private HttpRequestMessage _requestMessage; private Version _version; private HttpContent _content; private bool _disposed; public Version Version { get { return _version; } set { #if !PHONE if (value == null) { throw new ArgumentNullException(nameof(value)); } #endif CheckDisposed(); _version = value; } } internal void SetVersionWithoutValidation(Version value) => _version = value; public HttpContent Content { get { return _content; } set { CheckDisposed(); if (NetEventSource.IsEnabled) { if (value == null) { NetEventSource.ContentNull(this); } else { NetEventSource.Associate(this, value); } } _content = value; } } public HttpStatusCode StatusCode { get { return _statusCode; } set { if (((int)value < 0) || ((int)value > 999)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposed(); _statusCode = value; } } internal void SetStatusCodeWithoutValidation(HttpStatusCode value) => _statusCode = value; public string ReasonPhrase { get { if (_reasonPhrase != null) { return _reasonPhrase; } // Provide a default if one was not set. return HttpStatusDescription.Get(StatusCode); } set { if ((value != null) && ContainsNewLineCharacter(value)) { throw new FormatException(SR.net_http_reasonphrase_format_error); } CheckDisposed(); _reasonPhrase = value; // It's OK to have a 'null' reason phrase. } } internal void SetReasonPhraseWithoutValidation(string value) => _reasonPhrase = value; public HttpResponseHeaders Headers { get { if (_headers == null) { _headers = new HttpResponseHeaders(); } return _headers; } } public HttpResponseHeaders TrailingHeaders { get { if (_trailingHeaders == null) { _trailingHeaders = new HttpResponseHeaders(); } return _trailingHeaders; } } public HttpRequestMessage RequestMessage { get { return _requestMessage; } set { CheckDisposed(); if (value != null) NetEventSource.Associate(this, value); _requestMessage = value; } } public bool IsSuccessStatusCode { get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); } } public HttpResponseMessage() : this(defaultStatusCode) { } public HttpResponseMessage(HttpStatusCode statusCode) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, statusCode); if (((int)statusCode < 0) || ((int)statusCode > 999)) { throw new ArgumentOutOfRangeException(nameof(statusCode)); } _statusCode = statusCode; _version = HttpUtilities.DefaultResponseVersion; if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } public HttpResponseMessage EnsureSuccessStatusCode() { if (!IsSuccessStatusCode) { throw new HttpRequestException(SR.Format( System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)_statusCode, ReasonPhrase)); } return this; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("StatusCode: "); sb.Append((int)_statusCode); sb.Append(", ReasonPhrase: '"); sb.Append(ReasonPhrase ?? "<null>"); sb.Append("', Version: "); sb.Append(_version); sb.Append(", Content: "); sb.Append(_content == null ? "<null>" : _content.GetType().ToString()); sb.AppendLine(", Headers:"); HeaderUtilities.DumpHeaders(sb, _headers, _content?.Headers); if (_trailingHeaders != null) { sb.AppendLine(", Trailing Headers:"); HeaderUtilities.DumpHeaders(sb, _trailingHeaders); } return sb.ToString(); } private bool ContainsNewLineCharacter(string value) { foreach (char character in value) { if ((character == HttpRuleParser.CR) || (character == HttpRuleParser.LF)) { return true; } } return false; } #region IDisposable Members protected virtual void Dispose(bool disposing) { // The reason for this type to implement IDisposable is that it contains instances of types that implement // IDisposable (content). if (disposing && !_disposed) { _disposed = true; if (_content != null) { _content.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } } }
namespace CRUD.Migrations { using CRUD.Models; using CRUD.DLA; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<SchoolContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(SchoolContext context) { var students = new List<Student> { new Student { FirstMidName = "Carson", LastName = "Alexander", EnrollmentDate = DateTime.Parse("2010-09-01") }, new Student { FirstMidName = "Meredith", LastName = "Alonso", EnrollmentDate = DateTime.Parse("2012-09-01") }, new Student { FirstMidName = "Arturo", LastName = "Anand", EnrollmentDate = DateTime.Parse("2013-09-01") }, new Student { FirstMidName = "Gytis", LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2012-09-01") }, new Student { FirstMidName = "Yan", LastName = "Li", EnrollmentDate = DateTime.Parse("2012-09-01") }, new Student { FirstMidName = "Peggy", LastName = "Justice", EnrollmentDate = DateTime.Parse("2011-09-01") }, new Student { FirstMidName = "Laura", LastName = "Norman", EnrollmentDate = DateTime.Parse("2013-09-01") }, new Student { FirstMidName = "Nino", LastName = "Olivetto", EnrollmentDate = DateTime.Parse("2005-09-01") } }; students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s)); context.SaveChanges(); var instructors = new List<Instructor> { new Instructor { FirstMidName = "Kim", LastName = "Abercrombie", HireDate = DateTime.Parse("1995-03-11") }, new Instructor { FirstMidName = "Fadi", LastName = "Fakhouri", HireDate = DateTime.Parse("2002-07-06") }, new Instructor { FirstMidName = "Roger", LastName = "Harui", HireDate = DateTime.Parse("1998-07-01") }, new Instructor { FirstMidName = "Candace", LastName = "Kapoor", HireDate = DateTime.Parse("2001-01-15") }, new Instructor { FirstMidName = "Roger", LastName = "Zheng", HireDate = DateTime.Parse("2004-02-12") } }; instructors.ForEach(s => context.Instructors.AddOrUpdate(p => p.LastName, s)); context.SaveChanges(); var departments = new List<Department> { new Department { Name = "English", Budget = 350000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single( i => i.LastName == "Abercrombie").ID }, new Department { Name = "Mathematics", Budget = 100000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID }, new Department { Name = "Engineering", Budget = 350000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single( i => i.LastName == "Harui").ID }, new Department { Name = "Economics", Budget = 100000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID } }; departments.ForEach(s => context.Departments.AddOrUpdate(p => p.Name, s)); context.SaveChanges(); var courses = new List<Course> { new Course {CourseID = 1050, Title = "Chemistry", Credits = 3, DepartmentID = departments.Single( s => s.Name == "Engineering").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3, DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3, DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 1045, Title = "Calculus", Credits = 4, DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 3141, Title = "Trigonometry", Credits = 4, DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 2021, Title = "Composition", Credits = 3, DepartmentID = departments.Single( s => s.Name == "English").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 2042, Title = "Literature", Credits = 4, DepartmentID = departments.Single( s => s.Name == "English").DepartmentID, Instructors = new List<Instructor>() }, }; courses.ForEach(s => context.Courses.AddOrUpdate(p => p.CourseID, s)); context.SaveChanges(); var officeAssignments = new List<OfficeAssignment> { new OfficeAssignment { InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID, Location = "Smith 17" }, new OfficeAssignment { InstructorID = instructors.Single( i => i.LastName == "Harui").ID, Location = "Gowan 27" }, new OfficeAssignment { InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID, Location = "Thompson 304" }, }; officeAssignments.ForEach(s => context.OfficeAssignments.AddOrUpdate(p => p.InstructorID, s)); context.SaveChanges(); AddOrUpdateInstructor(context, "Chemistry", "Kapoor"); AddOrUpdateInstructor(context, "Chemistry", "Harui"); AddOrUpdateInstructor(context, "Microeconomics", "Zheng"); AddOrUpdateInstructor(context, "Macroeconomics", "Zheng"); AddOrUpdateInstructor(context, "Calculus", "Fakhouri"); AddOrUpdateInstructor(context, "Trigonometry", "Harui"); AddOrUpdateInstructor(context, "Composition", "Abercrombie"); AddOrUpdateInstructor(context, "Literature", "Abercrombie"); context.SaveChanges(); var enrollments = new List<Enrollment> { new Enrollment { StudentID = students.Single(s => s.LastName == "Alexander").ID, CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID, Grade = Grade.A }, new Enrollment { StudentID = students.Single(s => s.LastName == "Alexander").ID, CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID, Grade = Grade.C }, new Enrollment { StudentID = students.Single(s => s.LastName == "Alexander").ID, CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Alonso").ID, CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Alonso").ID, CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Alonso").ID, CourseID = courses.Single(c => c.Title == "Composition" ).CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Anand").ID, CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID }, new Enrollment { StudentID = students.Single(s => s.LastName == "Anand").ID, CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Barzdukas").ID, CourseID = courses.Single(c => c.Title == "Chemistry").CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Li").ID, CourseID = courses.Single(c => c.Title == "Composition").CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Justice").ID, CourseID = courses.Single(c => c.Title == "Literature").CourseID, Grade = Grade.B } }; foreach (Enrollment e in enrollments) { var enrollmentInDataBase = context.Enrollments.Where( s => s.Student.ID == e.StudentID && s.Course.CourseID == e.CourseID).SingleOrDefault(); if (enrollmentInDataBase == null) { context.Enrollments.Add(e); } } context.SaveChanges(); } void AddOrUpdateInstructor(SchoolContext context, string courseTitle, string instructorName) { var crs = context.Courses.SingleOrDefault(c => c.Title == courseTitle); var inst = crs.Instructors.SingleOrDefault(i => i.LastName == instructorName); if (inst == null) crs.Instructors.Add(context.Instructors.Single(i => i.LastName == instructorName)); } } }
using System; using System.Collections.Generic; using System.Globalization; using Google.ProtocolBuffers.Descriptors; //Disable CS3011: only CLS-compliant members can be abstract #pragma warning disable 3011 namespace Google.ProtocolBuffers.Serialization { /// <summary> /// Provides a base-class that provides some basic functionality for handling type dispatching /// </summary> public abstract class AbstractReader : ICodedInputStream { private const int DefaultMaxDepth = 64; private int _depth; /// <summary> Constructs a new reader </summary> protected AbstractReader() { MaxDepth = DefaultMaxDepth; } /// <summary> Gets or sets the maximum recursion depth allowed </summary> public int MaxDepth { get; set; } /// <summary> /// Merges the contents of stream into the provided message builder /// </summary> public TBuilder Merge<TBuilder>(TBuilder builder) where TBuilder : IBuilderLite { return Merge(builder, ExtensionRegistry.Empty); } /// <summary> /// Merges the contents of stream into the provided message builder /// </summary> public abstract TBuilder Merge<TBuilder>(TBuilder builder, ExtensionRegistry registry) where TBuilder : IBuilderLite; /// <summary> /// Peeks at the next field in the input stream and returns what information is available. /// </summary> /// <remarks> /// This may be called multiple times without actually reading the field. Only after the field /// is either read, or skipped, should PeekNext return a different value. /// </remarks> protected abstract bool PeekNext(out string field); /// <summary> /// Causes the reader to skip past this field /// </summary> protected abstract void Skip(); /// <summary> /// Returns true if it was able to read a Boolean from the input /// </summary> protected abstract bool Read(ref bool value); /// <summary> /// Returns true if it was able to read a Int32 from the input /// </summary> protected abstract bool Read(ref int value); /// <summary> /// Returns true if it was able to read a UInt32 from the input /// </summary> [CLSCompliant(false)] protected abstract bool Read(ref uint value); /// <summary> /// Returns true if it was able to read a Int64 from the input /// </summary> protected abstract bool Read(ref long value); /// <summary> /// Returns true if it was able to read a UInt64 from the input /// </summary> [CLSCompliant(false)] protected abstract bool Read(ref ulong value); /// <summary> /// Returns true if it was able to read a Single from the input /// </summary> protected abstract bool Read(ref float value); /// <summary> /// Returns true if it was able to read a Double from the input /// </summary> protected abstract bool Read(ref double value); /// <summary> /// Returns true if it was able to read a String from the input /// </summary> protected abstract bool Read(ref string value); /// <summary> /// Returns true if it was able to read a ByteString from the input /// </summary> protected abstract bool Read(ref ByteString value); /// <summary> /// returns true if it was able to read a single value into the value reference. The value /// stored may be of type System.String, System.Int32, or an IEnumLite from the IEnumLiteMap. /// </summary> protected abstract bool ReadEnum(ref object value); /// <summary> /// Merges the input stream into the provided IBuilderLite /// </summary> protected abstract bool ReadMessage(IBuilderLite builder, ExtensionRegistry registry); /// <summary> /// Reads the root-message preamble specific to this formatter /// </summary> public abstract void ReadMessageStart(); /// <summary> /// Reads the root-message close specific to this formatter /// </summary> public abstract void ReadMessageEnd(); /// <summary> /// Merges the input stream into the provided IBuilderLite /// </summary> public virtual bool ReadGroup(IBuilderLite value, ExtensionRegistry registry) { return ReadMessage(value, registry); } /// <summary> /// Cursors through the array elements and stops at the end of the array /// </summary> protected virtual IEnumerable<string> ForeachArrayItem(string field) { string next = field; while (true) { yield return next; if (!PeekNext(out next) || next != field) { break; } } } /// <summary> /// Reads an array of T messages /// </summary> public virtual bool ReadMessageArray<T>(string field, ICollection<T> items, IMessageLite messageType, ExtensionRegistry registry) { bool success = false; foreach (string next in ForeachArrayItem(field)) { IBuilderLite builder = messageType.WeakCreateBuilderForType(); if (ReadMessage(builder, registry)) { items.Add((T) builder.WeakBuild()); success |= true; } } return success; } /// <summary> /// Reads an array of T messages as a proto-buffer group /// </summary> public virtual bool ReadGroupArray<T>(string field, ICollection<T> items, IMessageLite messageType, ExtensionRegistry registry) { bool success = false; foreach (string next in ForeachArrayItem(field)) { IBuilderLite builder = messageType.WeakCreateBuilderForType(); if (ReadGroup(builder, registry)) { items.Add((T) builder.WeakBuild()); success |= true; } } return success; } /// <summary> /// Reads an array of System.Enum type T and adds them to the collection /// </summary> public virtual bool ReadEnumArray(string field, ICollection<object> items) { bool success = false; foreach (string next in ForeachArrayItem(field)) { object temp = null; if (ReadEnum(ref temp)) { items.Add(temp); success |= true; } } return success; } /// <summary> /// Reads an array of T, where T is a primitive type defined by FieldType /// </summary> public virtual bool ReadArray<T>(FieldType type, string field, ICollection<T> items) { bool success = false; foreach (string next in ForeachArrayItem(field)) { object temp = null; if (ReadField(type, ref temp)) { items.Add((T) temp); success |= true; } } return success; } /// <summary> /// returns true if it was able to read a single primitive value of FieldType into the value reference /// </summary> public virtual bool ReadField(FieldType type, ref object value) { switch (type) { case FieldType.Bool: { bool temp = false; if (Read(ref temp)) { value = temp; } else { return false; } break; } case FieldType.Int64: case FieldType.SInt64: case FieldType.SFixed64: { long temp = 0; if (Read(ref temp)) { value = temp; } else { return false; } break; } case FieldType.UInt64: case FieldType.Fixed64: { ulong temp = 0; if (Read(ref temp)) { value = temp; } else { return false; } break; } case FieldType.Int32: case FieldType.SInt32: case FieldType.SFixed32: { int temp = 0; if (Read(ref temp)) { value = temp; } else { return false; } break; } case FieldType.UInt32: case FieldType.Fixed32: { uint temp = 0; if (Read(ref temp)) { value = temp; } else { return false; } break; } case FieldType.Float: { float temp = float.NaN; if (Read(ref temp)) { value = temp; } else { return false; } break; } case FieldType.Double: { double temp = float.NaN; if (Read(ref temp)) { value = temp; } else { return false; } break; } case FieldType.String: { string temp = null; if (Read(ref temp)) { value = temp; } else { return false; } break; } case FieldType.Bytes: { ByteString temp = null; if (Read(ref temp)) { value = temp; } else { return false; } break; } default: throw InvalidProtocolBufferException.InvalidTag(); } return true; } #region ICodedInputStream Members bool ICodedInputStream.ReadTag(out uint fieldTag, out string fieldName) { fieldTag = 0; if (PeekNext(out fieldName)) { return true; } return false; } bool ICodedInputStream.ReadDouble(ref double value) { return Read(ref value); } bool ICodedInputStream.ReadFloat(ref float value) { return Read(ref value); } bool ICodedInputStream.ReadUInt64(ref ulong value) { return Read(ref value); } bool ICodedInputStream.ReadInt64(ref long value) { return Read(ref value); } bool ICodedInputStream.ReadInt32(ref int value) { return Read(ref value); } bool ICodedInputStream.ReadFixed64(ref ulong value) { return Read(ref value); } bool ICodedInputStream.ReadFixed32(ref uint value) { return Read(ref value); } bool ICodedInputStream.ReadBool(ref bool value) { return Read(ref value); } bool ICodedInputStream.ReadString(ref string value) { return Read(ref value); } void ICodedInputStream.ReadGroup(int fieldNumber, IBuilderLite builder, ExtensionRegistry extensionRegistry) { if (_depth++ > MaxDepth) { throw new RecursionLimitExceededException(); } ReadGroup(builder, extensionRegistry); _depth--; } void ICodedInputStream.ReadUnknownGroup(int fieldNumber, IBuilderLite builder) { throw new NotSupportedException(); } void ICodedInputStream.ReadMessage(IBuilderLite builder, ExtensionRegistry extensionRegistry) { if (_depth++ > MaxDepth) { throw new RecursionLimitExceededException(); } ReadMessage(builder, extensionRegistry); _depth--; } bool ICodedInputStream.ReadBytes(ref ByteString value) { return Read(ref value); } bool ICodedInputStream.ReadUInt32(ref uint value) { return Read(ref value); } bool ICodedInputStream.ReadEnum(ref IEnumLite value, out object unknown, IEnumLiteMap mapping) { value = null; unknown = null; if (ReadEnum(ref unknown)) { if (unknown is int) { value = mapping.FindValueByNumber((int) unknown); } else if (unknown is string) { value = mapping.FindValueByName((string) unknown); } return value != null; } return false; } bool ICodedInputStream.ReadEnum<T>(ref T value, out object rawValue) { rawValue = null; if (ReadEnum(ref rawValue)) { if (!EnumParser<T>.TryConvert(rawValue, ref value)) { value = default(T); return false; } return true; } return false; } bool ICodedInputStream.ReadSFixed32(ref int value) { return Read(ref value); } bool ICodedInputStream.ReadSFixed64(ref long value) { return Read(ref value); } bool ICodedInputStream.ReadSInt32(ref int value) { return Read(ref value); } bool ICodedInputStream.ReadSInt64(ref long value) { return Read(ref value); } void ICodedInputStream.ReadPrimitiveArray(FieldType fieldType, uint fieldTag, string fieldName, ICollection<object> list) { ReadArray(fieldType, fieldName, list); } void ICodedInputStream.ReadEnumArray(uint fieldTag, string fieldName, ICollection<IEnumLite> list, out ICollection<object> unknown, IEnumLiteMap mapping) { unknown = null; List<object> array = new List<object>(); if (ReadEnumArray(fieldName, array)) { foreach (object rawValue in array) { IEnumLite item = null; if (rawValue is int) { item = mapping.FindValueByNumber((int) rawValue); } else if (rawValue is string) { item = mapping.FindValueByName((string) rawValue); } if (item != null) { list.Add(item); } else { if (unknown == null) { unknown = new List<object>(); } unknown.Add(rawValue); } } } } void ICodedInputStream.ReadEnumArray<T>(uint fieldTag, string fieldName, ICollection<T> list, out ICollection<object> unknown) { unknown = null; List<object> array = new List<object>(); if (ReadEnumArray(fieldName, array)) { foreach (object rawValue in array) { T val = default(T); if (EnumParser<T>.TryConvert(rawValue, ref val)) { list.Add(val); } else { if (unknown == null) { unknown = new List<object>(); } unknown.Add(rawValue); } } } } void ICodedInputStream.ReadMessageArray<T>(uint fieldTag, string fieldName, ICollection<T> list, T messageType, ExtensionRegistry registry) { if (_depth++ > MaxDepth) { throw new RecursionLimitExceededException(); } ReadMessageArray(fieldName, list, messageType, registry); _depth--; } void ICodedInputStream.ReadGroupArray<T>(uint fieldTag, string fieldName, ICollection<T> list, T messageType, ExtensionRegistry registry) { if (_depth++ > MaxDepth) { throw new RecursionLimitExceededException(); } ReadGroupArray(fieldName, list, messageType, registry); _depth--; } bool ICodedInputStream.ReadPrimitiveField(FieldType fieldType, ref object value) { return ReadField(fieldType, ref value); } bool ICodedInputStream.IsAtEnd { get { string next; return PeekNext(out next) == false; } } bool ICodedInputStream.SkipField() { Skip(); return true; } void ICodedInputStream.ReadStringArray(uint fieldTag, string fieldName, ICollection<string> list) { ReadArray(FieldType.String, fieldName, list); } void ICodedInputStream.ReadBytesArray(uint fieldTag, string fieldName, ICollection<ByteString> list) { ReadArray(FieldType.Bytes, fieldName, list); } void ICodedInputStream.ReadBoolArray(uint fieldTag, string fieldName, ICollection<bool> list) { ReadArray(FieldType.Bool, fieldName, list); } void ICodedInputStream.ReadInt32Array(uint fieldTag, string fieldName, ICollection<int> list) { ReadArray(FieldType.Int32, fieldName, list); } void ICodedInputStream.ReadSInt32Array(uint fieldTag, string fieldName, ICollection<int> list) { ReadArray(FieldType.SInt32, fieldName, list); } void ICodedInputStream.ReadUInt32Array(uint fieldTag, string fieldName, ICollection<uint> list) { ReadArray(FieldType.UInt32, fieldName, list); } void ICodedInputStream.ReadFixed32Array(uint fieldTag, string fieldName, ICollection<uint> list) { ReadArray(FieldType.Fixed32, fieldName, list); } void ICodedInputStream.ReadSFixed32Array(uint fieldTag, string fieldName, ICollection<int> list) { ReadArray(FieldType.SFixed32, fieldName, list); } void ICodedInputStream.ReadInt64Array(uint fieldTag, string fieldName, ICollection<long> list) { ReadArray(FieldType.Int64, fieldName, list); } void ICodedInputStream.ReadSInt64Array(uint fieldTag, string fieldName, ICollection<long> list) { ReadArray(FieldType.SInt64, fieldName, list); } void ICodedInputStream.ReadUInt64Array(uint fieldTag, string fieldName, ICollection<ulong> list) { ReadArray(FieldType.UInt64, fieldName, list); } void ICodedInputStream.ReadFixed64Array(uint fieldTag, string fieldName, ICollection<ulong> list) { ReadArray(FieldType.Fixed64, fieldName, list); } void ICodedInputStream.ReadSFixed64Array(uint fieldTag, string fieldName, ICollection<long> list) { ReadArray(FieldType.SFixed64, fieldName, list); } void ICodedInputStream.ReadDoubleArray(uint fieldTag, string fieldName, ICollection<double> list) { ReadArray(FieldType.Double, fieldName, list); } void ICodedInputStream.ReadFloatArray(uint fieldTag, string fieldName, ICollection<float> list) { ReadArray(FieldType.Float, fieldName, list); } #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 System.Runtime; using System.Runtime.Serialization; using System.Security; using System.Reflection; using System.Xml; namespace System.Runtime.Serialization.Json { internal class JsonDataContract { [SecurityCritical] private JsonDataContractCriticalHelper _helper; [SecuritySafeCritical] protected JsonDataContract(DataContract traditionalDataContract) { _helper = new JsonDataContractCriticalHelper(traditionalDataContract); } [SecuritySafeCritical] protected JsonDataContract(JsonDataContractCriticalHelper helper) { _helper = helper; } internal virtual string TypeName { get { return null; } } protected JsonDataContractCriticalHelper Helper { [SecurityCritical] get { return _helper; } } protected DataContract TraditionalDataContract { [SecuritySafeCritical] get { return _helper.TraditionalDataContract; } } private Dictionary<XmlQualifiedName, DataContract> KnownDataContracts { [SecuritySafeCritical] get { return _helper.KnownDataContracts; } } public static JsonReadWriteDelegates GetGeneratedReadWriteDelegates(DataContract c) { // this method used to be rewritten by an IL transform // with the restructuring for multi-file, this is no longer true - instead // this has become a normal method JsonReadWriteDelegates result; #if NET_NATIVE // The c passed in could be a clone which is different from the original key, // We'll need to get the original key data contract from generated assembly. DataContract keyDc = DataContract.GetDataContractFromGeneratedAssembly(c.UnderlyingType); return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(keyDc, out result) ? result : null; #else return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null; #endif } internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c); if (result == null) { throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType.ToString())); } else { return result; } } [SecuritySafeCritical] public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract); } public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { PushKnownDataContracts(context); object deserializedObject = ReadJsonValueCore(jsonReader, context); PopKnownDataContracts(context); return deserializedObject; } public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { return TraditionalDataContract.ReadXmlValue(jsonReader, context); } public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { PushKnownDataContracts(context); WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle); PopKnownDataContracts(context); } public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context); } protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { while (reader.MoveToAttribute(JsonGlobals.typeString) && (reader.Value == JsonGlobals.nullString)) { reader.Skip(); reader.MoveToElement(); return true; } reader.MoveToElement(); return false; } protected void PopKnownDataContracts(XmlObjectSerializerContext context) { if (KnownDataContracts != null) { context.scopedKnownTypes.Pop(); } } protected void PushKnownDataContracts(XmlObjectSerializerContext context) { if (KnownDataContracts != null) { context.scopedKnownTypes.Push(KnownDataContracts); } } internal class JsonDataContractCriticalHelper { private static object s_cacheLock = new object(); private static object s_createDataContractLock = new object(); private static JsonDataContract[] s_dataContractCache = new JsonDataContract[32]; private static int s_dataContractID = 0; private static TypeHandleRef s_typeHandleRef = new TypeHandleRef(); private static Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer()); private Dictionary<XmlQualifiedName, DataContract> _knownDataContracts; private DataContract _traditionalDataContract; private string _typeName; internal JsonDataContractCriticalHelper(DataContract traditionalDataContract) { _traditionalDataContract = traditionalDataContract; AddCollectionItemContractsToKnownDataContracts(); _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value)); } internal Dictionary<XmlQualifiedName, DataContract> KnownDataContracts { get { return _knownDataContracts; } } internal DataContract TraditionalDataContract { get { return _traditionalDataContract; } } internal virtual string TypeName { get { return _typeName; } } public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle); JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { dataContract = CreateJsonDataContract(id, traditionalDataContract); s_dataContractCache[id] = dataContract; } return dataContract; } internal static int GetId(RuntimeTypeHandle typeHandle) { lock (s_cacheLock) { IntRef id; s_typeHandleRef.Value = typeHandle; if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id)) { int value = s_dataContractID++; if (value >= s_dataContractCache.Length) { int newSize = (value < Int32.MaxValue / 2) ? value * 2 : Int32.MaxValue; if (newSize <= value) { Fx.Assert("DataContract cache overflow"); throw new SerializationException(SR.DataContractCacheOverflow); } Array.Resize<JsonDataContract>(ref s_dataContractCache, newSize); } id = new IntRef(value); try { s_typeToIDCache.Add(new TypeHandleRef(typeHandle), id); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } return id.Value; } } private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract) { lock (s_createDataContractLock) { JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { Type traditionalDataContractType = traditionalDataContract.GetType(); if (traditionalDataContractType == typeof(ObjectDataContract)) { dataContract = new JsonObjectDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(StringDataContract)) { dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(UriDataContract)) { dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(QNameDataContract)) { dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(ByteArrayDataContract)) { dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract); } else if (traditionalDataContract.IsPrimitive || traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(ClassDataContract)) { dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(EnumDataContract)) { dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract); } else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) || (traditionalDataContractType == typeof(SpecialTypeDataContract))) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(CollectionDataContract)) { dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(XmlDataContract)) { dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract); } else { throw new ArgumentException(SR.Format(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType), "traditionalDataContract"); } } return dataContract; } } private void AddCollectionItemContractsToKnownDataContracts() { if (_traditionalDataContract.KnownDataContracts != null) { foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in _traditionalDataContract.KnownDataContracts) { if (!object.ReferenceEquals(knownDataContract, null)) { CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract; while (collectionDataContract != null) { DataContract itemContract = collectionDataContract.ItemContract; if (_knownDataContracts == null) { _knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>(); } if (!_knownDataContracts.ContainsKey(itemContract.StableName)) { _knownDataContracts.Add(itemContract.StableName, itemContract); } if (collectionDataContract.ItemType.GetTypeInfo().IsGenericType && collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>)) { DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetTypeInfo().GenericTypeArguments)); if (!_knownDataContracts.ContainsKey(itemDataContract.StableName)) { _knownDataContracts.Add(itemDataContract.StableName, itemDataContract); } } if (!(itemContract is CollectionDataContract)) { break; } collectionDataContract = itemContract as CollectionDataContract; } } } } } } } #if NET_NATIVE public class JsonReadWriteDelegates #else internal class JsonReadWriteDelegates #endif { // this is the global dictionary for JSON delegates introduced for multi-file private static Dictionary<DataContract, JsonReadWriteDelegates> s_jsonDelegates = new Dictionary<DataContract, JsonReadWriteDelegates>(); public static Dictionary<DataContract, JsonReadWriteDelegates> GetJsonDelegates() { return s_jsonDelegates; } public JsonFormatClassWriterDelegate ClassWriterDelegate { get; set; } public JsonFormatClassReaderDelegate ClassReaderDelegate { get; set; } public JsonFormatCollectionWriterDelegate CollectionWriterDelegate { get; set; } public JsonFormatCollectionReaderDelegate CollectionReaderDelegate { get; set; } public JsonFormatGetOnlyCollectionReaderDelegate GetOnlyCollectionReaderDelegate { get; set; } } }
#region License // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.IO; using System.Text; using FluentMigrator.Console; using NUnit.Framework; using NUnit.Should; namespace FluentMigrator.Tests.Unit.Runners { [TestFixture] public class MigratorConsoleTests { private string database = "Sqlite"; private string connection = "Data Source=:memory:;Version=3;New=True;"; private string target = "FluentMigrator.Tests.dll"; [Test] [Category("NotWorkingOnMono")] public void CanInitMigratorConsoleWithValidArguments() { var console = new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/namespace", "FluentMigrator.Tests.Integration.Migrations", "/nested", "/task", "migrate:up", "/version", "1"); console.Connection.ShouldBe(connection); console.Namespace.ShouldBe("FluentMigrator.Tests.Integration.Migrations"); console.NestedNamespaces.ShouldBeTrue(); console.Task.ShouldBe("migrate:up"); console.Version.ShouldBe(1); } [Test] [Category("NotWorkingOnMono")] public void ConsoleAnnouncerHasMoreOutputWhenVerbose() { var sbNonVerbose = new StringBuilder(); var stringWriterNonVerbose = new StringWriter(sbNonVerbose); System.Console.SetOut(stringWriterNonVerbose); new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/namespace", "FluentMigrator.Tests.Integration.Migrations", "/task", "migrate:up", "/version", "1"); var sbVerbose = new StringBuilder(); var stringWriterVerbose = new StringWriter(sbVerbose); System.Console.SetOut(stringWriterVerbose); new MigratorConsole( "/db", database, "/connection", connection, "/verbose", "1", "/target", target, "/namespace", "FluentMigrator.Tests.Integration.Migrations", "/task", "migrate:up", "/version", "1"); Assert.Greater(sbVerbose.ToString().Length, sbNonVerbose.ToString().Length); } [Test] public void ConsoleAnnouncerHasOutput() { var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); System.Console.SetOut(stringWriter); new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations", "/task", "migrate:up", "/version", "0"); var output = sb.ToString(); Assert.AreNotEqual(0, output.Length); } [Test] [Category("NotWorkingOnMono")] public void ConsoleAnnouncerHasOutputEvenIfMarkedAsPreviewOnly() { var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); System.Console.SetOut(stringWriter); new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations", "/verbose", "/task", "migrate:up", "/preview"); var output = sb.ToString(); Assert.That(output.Contains("PREVIEW-ONLY MODE")); Assert.AreNotEqual(0, output.Length); } [Test] public void FileAnnouncerHasOutputToDefaultOutputFile() { var outputFileName = target + ".sql"; if (File.Exists(outputFileName)) File.Delete(outputFileName); Assert.IsFalse(File.Exists(outputFileName)); new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/output", "/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations", "/task", "migrate:up", "/version", "0"); Assert.IsTrue(File.Exists(outputFileName)); File.Delete(outputFileName); } [Test] public void FileAnnouncerHasOutputToSpecifiedOutputFile() { var outputFileName = "output.sql"; if (File.Exists(outputFileName)) File.Delete(outputFileName); Assert.IsFalse(File.Exists(outputFileName)); new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/output", "/outputFilename", outputFileName, "/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations", "/task", "migrate:up", "/version", "0"); Assert.IsTrue(File.Exists(outputFileName)); File.Delete(outputFileName); } [Test] public void MustInitializeConsoleWithConnectionArgument() { new MigratorConsole("/db", database); Assert.That(Environment.ExitCode == 1); } [Test] public void MustInitializeConsoleWithDatabaseArgument() { new MigratorConsole("/connection", connection); Assert.That(Environment.ExitCode == 1); } [Test, Ignore("implement this test")] public void OrderOfConsoleArgumentsShouldNotMatter() { } [Test] public void TagsPassedToRunnerContextOnExecuteMigrations() { var migratorConsole = new MigratorConsole( "/db", database, "/connection", connection, "/verbose", "1", "/target", target, "/namespace", "FluentMigrator.Tests.Integration.Migrations", "/task", "migrate:up", "/version", "1", "/tag", "uk", "/tag", "production"); var expectedTags = new string[] { "uk", "production" }; CollectionAssert.AreEquivalent(expectedTags, migratorConsole.RunnerContext.Tags); } [Test] public void TransactionPerSessionShouldBeSetOnRunnerContextWithShortSwitch() { var console = new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/task", "migrate:up", "/tps"); console.TransactionPerSession.ShouldBeTrue(); console.RunnerContext.TransactionPerSession.ShouldBeTrue(); } [Test] public void TransactionPerSessionShouldBeSetOnRunnerContextWithLongSwitch() { var console = new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/task", "migrate:up", "/transaction-per-session"); console.TransactionPerSession.ShouldBeTrue(); console.RunnerContext.TransactionPerSession.ShouldBeTrue(); } [Test] public void ProviderSwitchesPassedToRunnerContextOnExecuteMigrations() { var migratorConsole = new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/output", "/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations", "/task", "migrate:up", "/version", "0", "/providerswitches", "QuotedIdentifiers=true"); const string ExpectedProviderSwitces = "QuotedIdentifiers=true"; CollectionAssert.AreEquivalent(ExpectedProviderSwitces, migratorConsole.RunnerContext.ProviderSwitches); } } }
// Copyright (c) 2013 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // ------------------------------------------------------------------------------- // SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet // published with the following license: // ------------------------------------------------------------------------------- // // Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry // // 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.Text; using SharpYaml; using SharpYaml.Events; namespace SharpYaml.Serialization { /// <summary> /// Represents a mapping node in the YAML document. /// </summary> public class YamlMappingNode : YamlNode, IEnumerable<KeyValuePair<YamlNode, YamlNode>> { private readonly IDictionary<YamlNode, YamlNode> children = new Dictionary<YamlNode, YamlNode>(); /// <summary> /// Gets the children of the current node. /// </summary> /// <value>The children.</value> public IDictionary<YamlNode, YamlNode> Children { get { return children; } } /// <summary> /// Gets or sets the style of the node. /// </summary> /// <value>The style.</value> public YamlStyle Style { get; set; } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="events">The events.</param> /// <param name="state">The state.</param> internal YamlMappingNode(EventReader events, DocumentLoadingState state) { MappingStart mapping = events.Expect<MappingStart>(); Load(mapping, state); bool hasUnresolvedAliases = false; while (!events.Accept<MappingEnd>()) { YamlNode key = ParseNode(events, state); YamlNode value = ParseNode(events, state); try { children.Add(key, value); } catch (ArgumentException err) { throw new YamlException(key.Start, key.End, "Duplicate key", err); } hasUnresolvedAliases |= key is YamlAliasNode || value is YamlAliasNode; } if (hasUnresolvedAliases) { state.AddNodeWithUnresolvedAliases(this); } #if DEBUG else { foreach (var child in children) { if (child.Key is YamlAliasNode) { throw new InvalidOperationException("Error in alias resolution."); } if (child.Value is YamlAliasNode) { throw new InvalidOperationException("Error in alias resolution."); } } } #endif events.Expect<MappingEnd>(); } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode() { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode(params KeyValuePair<YamlNode, YamlNode>[] children) : this((IEnumerable<KeyValuePair<YamlNode, YamlNode>>)children) { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode(IEnumerable<KeyValuePair<YamlNode, YamlNode>> children) { foreach (var child in children) { this.children.Add(child); } } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param> public YamlMappingNode(params YamlNode[] children) : this((IEnumerable<YamlNode>)children) { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param> public YamlMappingNode(IEnumerable<YamlNode> children) { using (var enumerator = children.GetEnumerator()) { while (enumerator.MoveNext()) { var key = enumerator.Current; if (!enumerator.MoveNext()) { throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even."); } Add(key, enumerator.Current); } } } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(YamlNode key, YamlNode value) { children.Add(key, value); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(string key, YamlNode value) { children.Add(new YamlScalarNode(key), value); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(YamlNode key, string value) { children.Add(key, new YamlScalarNode(value)); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(string key, string value) { children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); } /// <summary> /// Resolves the aliases that could not be resolved when the node was created. /// </summary> /// <param name="state">The state of the document.</param> internal override void ResolveAliases(DocumentLoadingState state) { Dictionary<YamlNode, YamlNode> keysToUpdate = null; Dictionary<YamlNode, YamlNode> valuesToUpdate = null; foreach (var entry in children) { if (entry.Key is YamlAliasNode) { if (keysToUpdate == null) { keysToUpdate = new Dictionary<YamlNode, YamlNode>(); } keysToUpdate.Add(entry.Key, state.GetNode(entry.Key.Anchor, true, entry.Key.Start, entry.Key.End)); } if (entry.Value is YamlAliasNode) { if (valuesToUpdate == null) { valuesToUpdate = new Dictionary<YamlNode, YamlNode>(); } valuesToUpdate.Add(entry.Key, state.GetNode(entry.Value.Anchor, true, entry.Value.Start, entry.Value.End)); } } if (valuesToUpdate != null) { foreach (var entry in valuesToUpdate) { children[entry.Key] = entry.Value; } } if (keysToUpdate != null) { foreach (var entry in keysToUpdate) { YamlNode value = children[entry.Key]; children.Remove(entry.Key); children.Add(entry.Value, value); } } } /// <summary> /// Saves the current node to the specified emitter. /// </summary> /// <param name="emitter">The emitter where the node is to be saved.</param> /// <param name="state">The state.</param> internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new MappingStart(Anchor, Tag, true, Style)); foreach (var entry in children) { entry.Key.Save(emitter, state); entry.Value.Save(emitter, state); } emitter.Emit(new MappingEnd()); } /// <summary> /// Accepts the specified visitor by calling the appropriate Visit method on it. /// </summary> /// <param name="visitor"> /// A <see cref="IYamlVisitor"/>. /// </param> public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } /// <summary /> public override bool Equals(object other) { var obj = other as YamlMappingNode; if (obj == null || !Equals(obj) || children.Count != obj.children.Count) { return false; } foreach (var entry in children) { YamlNode otherNode; if (!obj.children.TryGetValue(entry.Key, out otherNode) || !SafeEquals(entry.Value, otherNode)) { return false; } } return true; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { var hashCode = base.GetHashCode(); foreach (var entry in children) { hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Key)); hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Value)); } return hashCode; } /// <summary> /// Gets all nodes from the document, starting on the current node. /// </summary> public override IEnumerable<YamlNode> AllNodes { get { yield return this; foreach (var child in children) { foreach (var node in child.Key.AllNodes) { yield return node; } foreach (var node in child.Value.AllNodes) { yield return node; } } } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { var text = new StringBuilder("{ "); foreach (var child in children) { if (text.Length > 2) { text.Append(", "); } text.Append("{ ").Append(child.Key).Append(", ").Append(child.Value).Append(" }"); } text.Append(" }"); return text.ToString(); } #region IEnumerable<KeyValuePair<YamlNode,YamlNode>> Members /// <summary /> public IEnumerator<KeyValuePair<YamlNode, YamlNode>> GetEnumerator() { return children.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Workflow.Activities { using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Diagnostics.CodeAnalysis; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.ComponentModel.Serialization; using System.Xml; [DesignerSerializer(typeof(DependencyObjectCodeDomSerializer), typeof(CodeDomSerializer))] [TypeConverter(typeof(ChannelTokenTypeConverter))] [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class ChannelToken : DependencyObject, IPropertyValueProvider { [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] internal static readonly DependencyProperty EndpointNameProperty = DependencyProperty.Register("EndpointName", typeof(string), typeof(ChannelToken), new PropertyMetadata(null)); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] internal static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(ChannelToken), new PropertyMetadata(null, DependencyPropertyOptions.Metadata, new Attribute[] { new BrowsableAttribute(false) })); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] internal static readonly DependencyProperty OwnerActivityNameProperty = DependencyProperty.Register("OwnerActivityName", typeof(string), typeof(ChannelToken), new PropertyMetadata(null, DependencyPropertyOptions.Metadata, new Attribute[] { new TypeConverterAttribute(typeof(PropertyValueProviderTypeConverter)) })); public ChannelToken() { } internal ChannelToken(string name) { this.Name = name; } [DefaultValue(null)] [SR2Description(SR2DescriptionAttribute.ChannelToken_EndpointName_Description)] public string EndpointName { get { return (string) GetValue(EndpointNameProperty); } set { SetValue(EndpointNameProperty, value); } } [Browsable(false)] [DefaultValue(null)] [SR2Description(SR2DescriptionAttribute.ChannelToken_Name_Description)] public string Name { get { return (string) GetValue(NameProperty); } set { SetValue(NameProperty, value); } } [DefaultValue(null)] [TypeConverter(typeof(PropertyValueProviderTypeConverter))] [SR2Description(SR2DescriptionAttribute.ChannelToken_OwnerActivityName_Description)] public string OwnerActivityName { get { return (string) GetValue(OwnerActivityNameProperty); } set { SetValue(OwnerActivityNameProperty, value); } } ICollection IPropertyValueProvider.GetPropertyValues(ITypeDescriptorContext context) { StringCollection names = new StringCollection(); if (string.Equals(context.PropertyDescriptor.Name, "OwnerActivityName", StringComparison.Ordinal)) { ISelectionService selectionService = context.GetService(typeof(ISelectionService)) as ISelectionService; if (selectionService != null && selectionService.SelectionCount == 1 && selectionService.PrimarySelection is Activity) { // add empty string as an option // names.Add(string.Empty); Activity currentActivity = selectionService.PrimarySelection as Activity; foreach (Activity activity in GetEnclosingCompositeActivities(currentActivity)) { string activityId = activity.QualifiedName; if (!names.Contains(activityId)) { names.Add(activityId); } } } } return names; } internal static LogicalChannel GetLogicalChannel(Activity activity, ChannelToken endpoint, Type contractType) { if (activity == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity"); } if (endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint"); } if (contractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType"); } return GetLogicalChannel(activity, endpoint.Name, endpoint.OwnerActivityName, contractType); } internal static LogicalChannel GetLogicalChannel(Activity activity, string name, string ownerActivityName, Type contractType) { if (activity == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity"); } if (string.IsNullOrEmpty(name)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("name", SR2.GetString(SR2.Error_ArgumentValueNullOrEmptyString)); } if (contractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType"); } Activity contextActivity = activity.ContextActivity; Activity owner = null; if (contextActivity == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR2.GetString(SR2.Error_ContextOwnerActivityMissing))); } if (string.IsNullOrEmpty(ownerActivityName)) { owner = contextActivity.RootActivity; } else { while (contextActivity != null) { owner = contextActivity.GetActivityByName(ownerActivityName, true); if (owner != null) { break; } contextActivity = contextActivity.Parent; if (contextActivity != null) { contextActivity = contextActivity.ContextActivity; } } } if (owner == null && !string.IsNullOrEmpty(ownerActivityName)) { owner = Helpers.ParseActivityForBind(activity, ownerActivityName); } if (owner == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR2.GetString(SR2.Error_ContextOwnerActivityMissing))); } LogicalChannel logicalChannel = null; LogicalChannelCollection collection = owner.GetValue(LogicalChannelCollection.LogicalChannelCollectionProperty) as LogicalChannelCollection; if (collection == null) { collection = new LogicalChannelCollection(); owner.SetValue(LogicalChannelCollection.LogicalChannelCollectionProperty, collection); logicalChannel = new LogicalChannel(name, contractType); collection.Add(logicalChannel); } else if (!collection.Contains(name)) { logicalChannel = new LogicalChannel(name, contractType); collection.Add(logicalChannel); } else { logicalChannel = collection[name]; } if (logicalChannel.ContractType != contractType) { logicalChannel = null; } return logicalChannel; } internal static LogicalChannel Register(Activity activity, ChannelToken endpoint, Type contractType) { if (activity == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity"); } if (endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint"); } if (contractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType"); } LogicalChannel logicalChannel = GetLogicalChannel(activity, endpoint, contractType); if (logicalChannel == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR2.GetString(SR2.Error_FailedToRegisterChannel, endpoint.Name))); } return logicalChannel; } private static IEnumerable GetEnclosingCompositeActivities(Activity startActivity) { Activity currentActivity = null; Stack<Activity> activityStack = new Stack<Activity>(); activityStack.Push(startActivity); while ((currentActivity = activityStack.Pop()) != null) { if (currentActivity.Enabled) { yield return currentActivity; } activityStack.Push(currentActivity.Parent); } yield break; } } }
// 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 Xunit; namespace System.Tests { public class ConvertToStringTests { [Fact] public static void FromBoxedObject() { object[] testValues = { // Boolean true, false, // Byte byte.MinValue, (byte)100, byte.MaxValue, // Decimal decimal.Zero, decimal.One, decimal.MinusOne, decimal.MaxValue, decimal.MinValue, 1.234567890123456789012345678m, 1234.56m, -1234.56m, // Double -12.2364, -1.7753E-83, +12.345e+234, +12e+1, double.NegativeInfinity, double.PositiveInfinity, double.NaN, // Int16 short.MinValue, 0, short.MaxValue, // Int32 int.MinValue, 0, int.MaxValue, // Int64 long.MinValue, (long)0, long.MaxValue, // SByte sbyte.MinValue, (sbyte)0, sbyte.MaxValue, // Single -12.2364f, (float)+12.345e+234, +12e+1f, float.NegativeInfinity, float.PositiveInfinity, float.NaN, // TimeSpan TimeSpan.Zero, TimeSpan.Parse("1999.9:09:09"), TimeSpan.Parse("-1111.1:11:11"), TimeSpan.Parse("1:23:45"), TimeSpan.Parse("-2:34:56"), // UInt16 ushort.MinValue, (ushort)100, ushort.MaxValue, // UInt32 uint.MinValue, (uint)100, uint.MaxValue, // UInt64 ulong.MinValue, (ulong)100, ulong.MaxValue }; string[] expectedValues = { // Boolean "True", "False", // Byte "0", "100", "255", // Decimal "0", "1", "-1", "79228162514264337593543950335", "-79228162514264337593543950335", "1.234567890123456789012345678", "1234.56", "-1234.56", // Double "-12.2364", "-1.7753E-83", "1.2345E+235", "120", "-Infinity", "Infinity", "NaN", // Int16 "-32768", "0", "32767", // Int32 "-2147483648", "0", "2147483647", // Int64 "-9223372036854775808", "0", "9223372036854775807", // SByte "-128", "0", "127", // Single "-12.2364", "Infinity", "120", "-Infinity", "Infinity", "NaN", // TimeSpan "00:00:00", "1999.09:09:09", "-1111.01:11:11", "01:23:45", "-02:34:56", // UInt16 "0", "100", "65535", // UInt32 "0", "100", "4294967295", // UInt64 "0", "100", "18446744073709551615", }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], NumberFormatInfo.InvariantInfo)); } } [Fact] public static void FromBoxedObject_NotNetFramework() { object[] testValues = { // Double -12.236465923406483, // Single -1.7753e-83f, -12.2364659234064826243f, }; string[] expectedValues = { // Double "-12.236465923406483", // Single "-0", "-12.236465", }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], NumberFormatInfo.InvariantInfo)); } } [Fact] public static void FromObject() { Assert.Equal("System.Tests.ConvertToStringTests", Convert.ToString(new ConvertToStringTests())); } [Fact] public static void FromDateTime() { DateTime[] testValues = { new DateTime(2000, 8, 15, 16, 59, 59), new DateTime(1, 1, 1, 1, 1, 1) }; string[] expectedValues = { "08/15/2000 16:59:59", "01/01/0001 01:01:01" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(testValues[i].ToString(), Convert.ToString(testValues[i])); Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], DateTimeFormatInfo.InvariantInfo)); } } [Fact] public static void FromChar() { char[] testValues = { 'a', 'A', '@', '\n' }; string[] expectedValues = { "a", "A", "@", "\n" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i])); Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], CultureInfo.InvariantCulture)); } } private static void Verify<TInput>(Func<TInput, string> convert, Func<TInput, IFormatProvider, string> convertWithFormatProvider, TInput[] testValues, string[] expectedValues, IFormatProvider formatProvider = null) { Assert.Equal(expectedValues.Length, testValues.Length); if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture; } for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], convert(testValues[i])); Assert.Equal(expectedValues[i], convertWithFormatProvider(testValues[i], formatProvider)); } } [Fact] public static void FromByteBase2() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "1100100", "11111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromByteBase8() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "144", "377" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromByteBase10() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "100", "255" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromByteBase16() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "64", "ff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromByteInvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(byte.MaxValue, 13)); } [Fact] public static void FromInt16Base2() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "1000000000000000", "0", "111111111111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromInt16Base8() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "100000", "0", "77777" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromInt16Base10() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "-32768", "0", "32767" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromInt16Base16() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "8000", "0", "7fff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromInt16InvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(short.MaxValue, 0)); } [Fact] public static void FromInt32Base2() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "10000000000000000000000000000000", "0", "1111111111111111111111111111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromInt32Base8() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "20000000000", "0", "17777777777" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromInt32Base10() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "-2147483648", "0", "2147483647" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromInt32Base16() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "80000000", "0", "7fffffff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromInt32InvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(int.MaxValue, 9)); } [Fact] public static void FromInt64Base2() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "1000000000000000000000000000000000000000000000000000000000000000", "0", "111111111111111111111111111111111111111111111111111111111111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromInt64Base8() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "1000000000000000000000", "0", "777777777777777777777" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromInt64Base10() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "-9223372036854775808", "0", "9223372036854775807" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromInt64Base16() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "8000000000000000", "0", "7fffffffffffffff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromInt64InvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(long.MaxValue, 1)); } [Fact] public static void FromBoolean() { bool[] testValues = new[] { true, false }; for (int i = 0; i < testValues.Length; i++) { string expected = testValues[i].ToString(); string actual = Convert.ToString(testValues[i]); Assert.Equal(expected, actual); actual = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(expected, actual); } } [Fact] public static void FromSByte() { sbyte[] testValues = new sbyte[] { sbyte.MinValue, -1, 0, 1, sbyte.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromByte() { byte[] testValues = new byte[] { byte.MinValue, 0, 1, 100, byte.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromInt16Array() { short[] testValues = new short[] { short.MinValue, -1000, -1, 0, 1, 1000, short.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromUInt16Array() { ushort[] testValues = new ushort[] { ushort.MinValue, 0, 1, 1000, ushort.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromInt32Array() { int[] testValues = new int[] { int.MinValue, -1000, -1, 0, 1, 1000, int.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromUInt32Array() { uint[] testValues = new uint[] { uint.MinValue, 0, 1, 1000, uint.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromInt64Array() { long[] testValues = new long[] { long.MinValue, -1000, -1, 0, 1, 1000, long.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromUInt64Array() { ulong[] testValues = new ulong[] { ulong.MinValue, 0, 1, 1000, ulong.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromSingleArray() { float[] testValues = new float[] { float.MinValue, 0.0f, 1.0f, 1000.0f, float.MaxValue, float.NegativeInfinity, float.PositiveInfinity, float.Epsilon, float.NaN }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromDoubleArray() { double[] testValues = new double[] { double.MinValue, 0.0, 1.0, 1000.0, double.MaxValue, double.NegativeInfinity, double.PositiveInfinity, double.Epsilon, double.NaN }; // Vanilla Test Cases for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromDecimalArray() { decimal[] testValues = new decimal[] { decimal.MinValue, decimal.Parse("-1.234567890123456789012345678", NumberFormatInfo.InvariantInfo), (decimal)0.0, (decimal)1.0, (decimal)1000.0, decimal.MaxValue, decimal.One, decimal.Zero, decimal.MinusOne }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromDateTimeArray() { DateTime[] testValues = new DateTime[] { DateTime.Parse("08/15/2000 16:59:59", DateTimeFormatInfo.InvariantInfo), DateTime.Parse("01/01/0001 01:01:01", DateTimeFormatInfo.InvariantInfo) }; IFormatProvider formatProvider = DateTimeFormatInfo.GetInstance(new CultureInfo("en-US")); for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], formatProvider); string expected = testValues[i].ToString(formatProvider); Assert.Equal(expected, result); } } [Fact] public static void FromString() { string[] testValues = new string[] { "Hello", " ", "", "\0" }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(), result); } } [Fact] public static void FromIFormattable() { FooFormattable foo = new FooFormattable(3); string result = Convert.ToString(foo); Assert.Equal("FooFormattable: 3", result); result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("System.Globalization.NumberFormatInfo: 3", result); foo = null; result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("", result); } [Fact] public static void FromNonIConvertible() { Foo foo = new Foo(3); string result = Convert.ToString(foo); Assert.Equal("System.Tests.ConvertToStringTests+Foo", result); result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("System.Tests.ConvertToStringTests+Foo", result); foo = null; result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("", result); } private class FooFormattable : IFormattable { private int _value; public FooFormattable(int value) { _value = value; } public string ToString(string format, IFormatProvider formatProvider) { if (formatProvider != null) { return string.Format("{0}: {1}", formatProvider, _value); } else { return string.Format("FooFormattable: {0}", (_value)); } } } private class Foo { private int _value; public Foo(int value) { _value = value; } public string ToString(IFormatProvider provider) { if (provider != null) { return string.Format("{0}: {1}", provider, _value); } else { return string.Format("Foo: {0}", _value); } } } } }
namespace XenAdmin.ConsoleView { partial class VNCTabView { /// <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) { Program.AssertOnEventThread(); UnregisterEventListeners(); if (disposing && (components != null)) { components.Dispose(); } if (disposing && vncScreen != null && !vncScreen.IsDisposed) { vncScreen.GpuStatusChanged -= ShowGpuWarningIfRequired; vncScreen.Dispose(); } if (this.fullscreenForm != null) { fullscreenForm.Hide(); fullscreenForm.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VNCTabView)); this.sendCAD = new System.Windows.Forms.Button(); this.contentPanel = new System.Windows.Forms.Panel(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.labelGeneralInformationMessage = new System.Windows.Forms.Label(); this.pictureBoxGeneralInformationMessage = new System.Windows.Forms.PictureBox(); this.scaleCheckBox = new System.Windows.Forms.CheckBox(); this.fullscreenButton = new System.Windows.Forms.Button(); this.dockButton = new System.Windows.Forms.Button(); this.tip = new System.Windows.Forms.ToolTip(this.components); this.LifeCycleMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.powerStateLabel = new System.Windows.Forms.Label(); this.dedicatedGpuWarning = new System.Windows.Forms.Label(); this.gradientPanel1 = new XenAdmin.Controls.GradientPanel.HorizontalGradientPanel(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.HostLabel = new System.Windows.Forms.Label(); this.buttonSSH = new System.Windows.Forms.Button(); this.toggleConsoleButton = new System.Windows.Forms.Button(); this.multipleDvdIsoList1 = new XenAdmin.Controls.MultipleDvdIsoList(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxGeneralInformationMessage)).BeginInit(); this.gradientPanel1.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // sendCAD // resources.ApplyResources(this.sendCAD, "sendCAD"); this.sendCAD.Name = "sendCAD"; this.sendCAD.UseVisualStyleBackColor = true; this.sendCAD.Click += new System.EventHandler(this.sendCAD_Click); // // contentPanel // resources.ApplyResources(this.contentPanel, "contentPanel"); this.contentPanel.Name = "contentPanel"; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.labelGeneralInformationMessage, 0, 0); this.tableLayoutPanel1.Controls.Add(this.pictureBoxGeneralInformationMessage, 0, 0); this.tableLayoutPanel1.Controls.Add(this.sendCAD, 0, 0); this.tableLayoutPanel1.Controls.Add(this.scaleCheckBox, 3, 0); this.tableLayoutPanel1.Controls.Add(this.fullscreenButton, 5, 0); this.tableLayoutPanel1.Controls.Add(this.dockButton, 4, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // labelGeneralInformationMessage // resources.ApplyResources(this.labelGeneralInformationMessage, "labelGeneralInformationMessage"); this.labelGeneralInformationMessage.AutoEllipsis = true; this.labelGeneralInformationMessage.Name = "labelGeneralInformationMessage"; // // pictureBoxGeneralInformationMessage // resources.ApplyResources(this.pictureBoxGeneralInformationMessage, "pictureBoxGeneralInformationMessage"); this.pictureBoxGeneralInformationMessage.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16; this.pictureBoxGeneralInformationMessage.Name = "pictureBoxGeneralInformationMessage"; this.pictureBoxGeneralInformationMessage.TabStop = false; // // scaleCheckBox // resources.ApplyResources(this.scaleCheckBox, "scaleCheckBox"); this.scaleCheckBox.Name = "scaleCheckBox"; this.scaleCheckBox.UseVisualStyleBackColor = true; this.scaleCheckBox.CheckedChanged += new System.EventHandler(this.scaleCheckBox_CheckedChanged); // // fullscreenButton // resources.ApplyResources(this.fullscreenButton, "fullscreenButton"); this.fullscreenButton.Name = "fullscreenButton"; this.fullscreenButton.UseVisualStyleBackColor = true; this.fullscreenButton.Click += new System.EventHandler(this.fullscreenButton_Click); // // dockButton // resources.ApplyResources(this.dockButton, "dockButton"); this.dockButton.Image = global::XenAdmin.Properties.Resources.detach_24; this.dockButton.Name = "dockButton"; this.dockButton.UseVisualStyleBackColor = true; this.dockButton.Click += new System.EventHandler(this.dockButton_Click); // // tip // this.tip.ShowAlways = true; // // LifeCycleMenuStrip // this.LifeCycleMenuStrip.ImageScalingSize = new System.Drawing.Size(20, 20); this.LifeCycleMenuStrip.Name = "LifeCycleMenuStrip"; resources.ApplyResources(this.LifeCycleMenuStrip, "LifeCycleMenuStrip"); this.LifeCycleMenuStrip.Closing += new System.Windows.Forms.ToolStripDropDownClosingEventHandler(this.LifeCycleMenuStrip_Closing); this.LifeCycleMenuStrip.Opened += new System.EventHandler(this.LifeCycleMenuStrip_Opened); // // powerStateLabel // this.powerStateLabel.AutoEllipsis = true; this.powerStateLabel.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.powerStateLabel, "powerStateLabel"); this.powerStateLabel.ForeColor = System.Drawing.SystemColors.ControlText; this.powerStateLabel.Name = "powerStateLabel"; this.powerStateLabel.Click += new System.EventHandler(this.powerStateLabel_Click); // // dedicatedGpuWarning // this.dedicatedGpuWarning.AutoEllipsis = true; this.dedicatedGpuWarning.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.dedicatedGpuWarning, "dedicatedGpuWarning"); this.dedicatedGpuWarning.ForeColor = System.Drawing.SystemColors.ControlText; this.dedicatedGpuWarning.Name = "dedicatedGpuWarning"; // // gradientPanel1 // this.gradientPanel1.Controls.Add(this.tableLayoutPanel2); resources.ApplyResources(this.gradientPanel1, "gradientPanel1"); this.gradientPanel1.Name = "gradientPanel1"; // // tableLayoutPanel2 // this.tableLayoutPanel2.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2"); this.tableLayoutPanel2.Controls.Add(this.HostLabel, 0, 0); this.tableLayoutPanel2.Controls.Add(this.buttonSSH, 3, 0); this.tableLayoutPanel2.Controls.Add(this.toggleConsoleButton, 5, 0); this.tableLayoutPanel2.Controls.Add(this.multipleDvdIsoList1, 2, 0); this.tableLayoutPanel2.Controls.Add(this.pictureBox1, 1, 0); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; // // HostLabel // this.HostLabel.AutoEllipsis = true; resources.ApplyResources(this.HostLabel, "HostLabel"); this.HostLabel.ForeColor = System.Drawing.Color.White; this.HostLabel.Name = "HostLabel"; // // buttonSSH // resources.ApplyResources(this.buttonSSH, "buttonSSH"); this.buttonSSH.Name = "buttonSSH"; this.buttonSSH.UseVisualStyleBackColor = true; this.buttonSSH.Click += new System.EventHandler(this.buttonSSH_Click); // // toggleConsoleButton // resources.ApplyResources(this.toggleConsoleButton, "toggleConsoleButton"); this.toggleConsoleButton.Name = "toggleConsoleButton"; this.tip.SetToolTip(this.toggleConsoleButton, resources.GetString("toggleConsoleButton.ToolTip")); this.toggleConsoleButton.UseVisualStyleBackColor = true; this.toggleConsoleButton.Click += new System.EventHandler(this.toggleConsoleButton_Click); // // multipleDvdIsoList1 // resources.ApplyResources(this.multipleDvdIsoList1, "multipleDvdIsoList1"); this.multipleDvdIsoList1.LabelNewCdForeColor = System.Drawing.SystemColors.HotTrack; this.multipleDvdIsoList1.LabelSingleDvdForeColor = System.Drawing.SystemColors.ControlText; this.multipleDvdIsoList1.LinkLabelLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(255))))); this.multipleDvdIsoList1.Name = "multipleDvdIsoList1"; this.multipleDvdIsoList1.VM = null; // // pictureBox1 // resources.ApplyResources(this.pictureBox1, "pictureBox1"); this.pictureBox1.Image = global::XenAdmin.Properties.Resources._001_LifeCycle_h32bit_24; this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.TabStop = false; this.pictureBox1.Click += new System.EventHandler(this.LifeCycleButton_MouseClick); this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown); this.pictureBox1.MouseEnter += new System.EventHandler(this.pictureBox1_MouseEnter); this.pictureBox1.MouseLeave += new System.EventHandler(this.pictureBox1_MouseLeave); this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp); // // VNCTabView // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.Controls.Add(this.contentPanel); this.Controls.Add(this.dedicatedGpuWarning); this.Controls.Add(this.powerStateLabel); this.Controls.Add(this.gradientPanel1); this.Controls.Add(this.tableLayoutPanel1); this.Name = "VNCTabView"; this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxGeneralInformationMessage)).EndInit(); this.gradientPanel1.ResumeLayout(false); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button dockButton; private System.Windows.Forms.Button sendCAD; private System.Windows.Forms.Panel contentPanel; private System.Windows.Forms.CheckBox scaleCheckBox; private System.Windows.Forms.Button fullscreenButton; private System.Windows.Forms.ToolTip tip; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.ContextMenuStrip LifeCycleMenuStrip; private System.Windows.Forms.PictureBox pictureBox1; private XenAdmin.Controls.GradientPanel.GradientPanel gradientPanel1; private System.Windows.Forms.Label HostLabel; private System.Windows.Forms.Button toggleConsoleButton; private XenAdmin.Controls.MultipleDvdIsoList multipleDvdIsoList1; private System.Windows.Forms.Label powerStateLabel; private System.Windows.Forms.Label dedicatedGpuWarning; private System.Windows.Forms.Button buttonSSH; private System.Windows.Forms.PictureBox pictureBoxGeneralInformationMessage; private System.Windows.Forms.Label labelGeneralInformationMessage; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmClrValue : DkmDataContainer { internal DkmClrValue( object value, object hostObjectValue, DkmClrType type, string alias, IDkmClrFormatter formatter, DkmEvaluationResultFlags evalFlags, DkmClrValueFlags valueFlags, DkmInspectionContext inspectionContext) { Debug.Assert(!type.GetLmrType().IsTypeVariables() || (valueFlags == DkmClrValueFlags.Synthetic)); Debug.Assert((alias == null) || evalFlags.Includes(DkmEvaluationResultFlags.HasObjectId)); // The "real" DkmClrValue will always have a value of zero for null pointers. Debug.Assert(!type.GetLmrType().IsPointer || (value != null)); _rawValue = value; this.HostObjectValue = hostObjectValue; this.Type = type; _formatter = formatter; this.Alias = alias; this.EvalFlags = evalFlags; this.ValueFlags = valueFlags; this.InspectionContext = inspectionContext ?? new DkmInspectionContext(formatter, DkmEvaluationFlags.None, 10); } public readonly DkmEvaluationResultFlags EvalFlags; public readonly DkmClrValueFlags ValueFlags; public readonly DkmClrType Type; public DkmClrType DeclaredType { get { throw new NotImplementedException(); } } public readonly DkmInspectionContext InspectionContext; public readonly DkmStackWalkFrame StackFrame; public readonly DkmEvaluationResultCategory Category; public readonly DkmEvaluationResultAccessType Access; public readonly DkmEvaluationResultStorageType StorageType; public readonly DkmEvaluationResultTypeModifierFlags TypeModifierFlags; public readonly DkmDataAddress Address; public readonly object HostObjectValue; public readonly string Alias; private readonly IDkmClrFormatter _formatter; private readonly object _rawValue; internal DkmClrValue WithInspectionContext(DkmInspectionContext inspectionContext) { return new DkmClrValue( _rawValue, this.HostObjectValue, this.Type, this.Alias, _formatter, this.EvalFlags, this.ValueFlags, inspectionContext); } public DkmClrValue Dereference() { if (_rawValue == null) { throw new InvalidOperationException("Cannot dereference invalid value"); } var elementType = this.Type.GetLmrType().GetElementType(); var evalFlags = DkmEvaluationResultFlags.None; var valueFlags = DkmClrValueFlags.None; object value; try { var intPtr = Environment.Is64BitProcess ? new IntPtr((long)_rawValue) : new IntPtr((int)_rawValue); value = Dereference(intPtr, elementType); } catch (Exception e) { value = e; evalFlags |= DkmEvaluationResultFlags.ExceptionThrown; } var valueType = new DkmClrType(this.Type.RuntimeInstance, (value == null) ? elementType : (TypeImpl)value.GetType()); return new DkmClrValue( value, value, valueType, alias: null, formatter: _formatter, evalFlags: evalFlags, valueFlags: valueFlags, inspectionContext: this.InspectionContext); } public bool IsNull { get { if (this.IsError()) { // Should not be checking value for Error. (Throw rather than // assert since the property may be called during debugging.) throw new InvalidOperationException(); } var lmrType = Type.GetLmrType(); return ((_rawValue == null) && !lmrType.IsValueType) || (lmrType.IsPointer && (Convert.ToInt64(_rawValue) == 0)); } } internal static object GetHostObjectValue(Type lmrType, object rawValue) { // NOTE: This is just a "for testing purposes" approximation of what the real DkmClrValue.HostObjectValue // will return. We will need to update this implementation to match the real behavior we add // specialized support for additional types. var typeCode = Metadata.Type.GetTypeCode(lmrType); return (lmrType.IsPointer || lmrType.IsEnum || typeCode != TypeCode.DateTime || typeCode != TypeCode.Object) ? rawValue : null; } public string GetValueString() { // The real version does some sort of dynamic dispatch that ultimately calls this method. return _formatter.GetValueString(this); } public bool HasUnderlyingString() { return _formatter.HasUnderlyingString(this); } public string GetUnderlyingString() { return _formatter.GetUnderlyingString(this); } public string EvaluateToString() { // This is a rough approximation of the real functionality. Basically, // if object.ToString is not overridden, we return null and it is the // caller's responsibility to compute a string. var type = this.Type.GetLmrType(); while (type != null) { if (type.IsObject() || type.IsValueType()) { return null; } // We should check the signature and virtual-ness, but this is // close enough for testing. if (type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Any(m => m.Name == "ToString")) { break; } type = type.BaseType; } var rawValue = _rawValue; Debug.Assert(rawValue != null || this.Type.GetLmrType().IsVoid(), "In our mock system, this should only happen for void."); return rawValue == null ? null : rawValue.ToString(); } /// <remarks> /// Very simple expression evaluation (may not support all syntax supported by Concord). /// </remarks> public string EvaluateDebuggerDisplayString(string formatString) { Debug.Assert(!this.IsNull, "Not supported by VIL"); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; int openPos = -1; int length = formatString.Length; for (int i = 0; i < length; i++) { char ch = formatString[i]; if (ch == '{') { if (openPos >= 0) { throw new ArgumentException(string.Format("Nested braces in '{0}'", formatString)); } openPos = i; } else if (ch == '}') { if (openPos < 0) { throw new ArgumentException(string.Format("Unmatched closing brace in '{0}'", formatString)); } string name = formatString.Substring(openPos + 1, i - openPos - 1); openPos = -1; // Ignore any format specifiers. int commaIndex = name.IndexOf(','); if (commaIndex >= 0) { name = name.Substring(0, commaIndex); } var type = ((TypeImpl)this.Type.GetLmrType()).Type; var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; DkmClrValue exprValue; var appDomain = this.Type.AppDomain; var field = type.GetField(name, bindingFlags); if (field != null) { var fieldValue = field.GetValue(_rawValue); exprValue = new DkmClrValue( fieldValue, fieldValue, DkmClrType.Create(appDomain, (TypeImpl)((fieldValue == null) ? field.FieldType : fieldValue.GetType())), alias: null, formatter: _formatter, evalFlags: GetEvaluationResultFlags(fieldValue), valueFlags: DkmClrValueFlags.None, inspectionContext: this.InspectionContext); } else { var property = type.GetProperty(name, bindingFlags); if (property != null) { var propertyValue = property.GetValue(_rawValue); exprValue = new DkmClrValue( propertyValue, propertyValue, DkmClrType.Create(appDomain, (TypeImpl)((propertyValue == null) ? property.PropertyType : propertyValue.GetType())), alias: null, formatter: _formatter, evalFlags: GetEvaluationResultFlags(propertyValue), valueFlags: DkmClrValueFlags.None, inspectionContext: this.InspectionContext); } else { var openParenIndex = name.IndexOf('('); if (openParenIndex >= 0) { name = name.Substring(0, openParenIndex); } var method = type.GetMethod(name, bindingFlags); // The real implementation requires parens on method invocations, so // we'll return error if there wasn't at least an open paren... if ((openParenIndex >= 0) && method != null) { var methodValue = method.Invoke(_rawValue, new object[] { }); exprValue = new DkmClrValue( methodValue, methodValue, DkmClrType.Create(appDomain, (TypeImpl)((methodValue == null) ? method.ReturnType : methodValue.GetType())), alias: null, formatter: _formatter, evalFlags: GetEvaluationResultFlags(methodValue), valueFlags: DkmClrValueFlags.None, inspectionContext: this.InspectionContext); } else { var stringValue = "Problem evaluating expression"; var stringType = DkmClrType.Create(appDomain, (TypeImpl)typeof(string)); exprValue = new DkmClrValue( stringValue, stringValue, stringType, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.Error, inspectionContext: this.InspectionContext); } } } builder.Append(exprValue.GetValueString()); // Re-enter the formatter. } else if (openPos < 0) { builder.Append(ch); } } if (openPos >= 0) { throw new ArgumentException(string.Format("Unmatched open brace in '{0}'", formatString)); } return pooled.ToStringAndFree(); } public DkmClrValue GetMemberValue(string MemberName, int MemberType, string ParentTypeName) { var runtime = this.Type.RuntimeInstance; var memberValue = runtime.GetMemberValue(this, MemberName); if (memberValue != null) { return memberValue; } var declaringType = this.Type.GetLmrType(); if (ParentTypeName != null) { declaringType = GetAncestorType(declaringType, ParentTypeName); Debug.Assert(declaringType != null); } // Special cases for nullables if (declaringType.IsNullable()) { if (MemberName == InternalWellKnownMemberNames.NullableHasValue) { // In our mock implementation, RawValue is null for null nullables, // so we have to compute HasValue some other way. var boolValue = _rawValue != null; var boolType = runtime.GetType((TypeImpl)typeof(bool)); return new DkmClrValue( boolValue, boolValue, type: boolType, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None, inspectionContext: this.InspectionContext); } else if (MemberName == InternalWellKnownMemberNames.NullableValue) { // In our mock implementation, RawValue is of type T rather than // Nullable<T> for nullables, so we'll just return that value // (no need to unwrap by getting "value" field). var valueType = runtime.GetType((TypeImpl)_rawValue.GetType()); return new DkmClrValue( _rawValue, _rawValue, type: valueType, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None, inspectionContext: this.InspectionContext); } } Type declaredType; object value; var evalFlags = DkmEvaluationResultFlags.None; const BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; switch ((MemberTypes)MemberType) { case MemberTypes.Field: var field = declaringType.GetField(MemberName, bindingFlags); declaredType = field.FieldType; if (field.Attributes.HasFlag(FieldAttributes.Literal) || field.Attributes.HasFlag(FieldAttributes.InitOnly)) { evalFlags |= DkmEvaluationResultFlags.ReadOnly; } try { value = field.GetValue(_rawValue); } catch (TargetInvocationException e) { var exception = e.InnerException; return new DkmClrValue( exception, exception, type: runtime.GetType((TypeImpl)exception.GetType()), alias: null, formatter: _formatter, evalFlags: evalFlags | DkmEvaluationResultFlags.ExceptionThrown, valueFlags: DkmClrValueFlags.None, inspectionContext: this.InspectionContext); } break; case MemberTypes.Property: var property = declaringType.GetProperty(MemberName, bindingFlags); declaredType = property.PropertyType; if (property.GetSetMethod(nonPublic: true) == null) { evalFlags |= DkmEvaluationResultFlags.ReadOnly; } try { value = property.GetValue(_rawValue, bindingFlags, null, null, null); } catch (TargetInvocationException e) { var exception = e.InnerException; return new DkmClrValue( exception, exception, type: runtime.GetType((TypeImpl)exception.GetType()), alias: null, formatter: _formatter, evalFlags: evalFlags | DkmEvaluationResultFlags.ExceptionThrown, valueFlags: DkmClrValueFlags.None, inspectionContext: this.InspectionContext); } break; default: throw ExceptionUtilities.UnexpectedValue((MemberTypes)MemberType); } Type type; if (value is Pointer) { unsafe { if (Marshal.SizeOf(typeof(void*)) == 4) { value = (int)Pointer.Unbox(value); } else { value = (long)Pointer.Unbox(value); } } type = declaredType; } else if (value == null || declaredType.IsNullable()) { type = declaredType; } else { type = (TypeImpl)value.GetType(); } return new DkmClrValue( value, value, type: runtime.GetType(type), alias: null, formatter: _formatter, evalFlags: evalFlags, valueFlags: DkmClrValueFlags.None, inspectionContext: this.InspectionContext); } public DkmClrValue GetArrayElement(int[] indices) { var array = (System.Array)_rawValue; var element = array.GetValue(indices); var type = DkmClrType.Create(this.Type.AppDomain, (TypeImpl)((element == null) ? array.GetType().GetElementType() : element.GetType())); return new DkmClrValue( element, element, type: type, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None, inspectionContext: this.InspectionContext); } public ReadOnlyCollection<int> ArrayDimensions { get { var array = (Array)_rawValue; if (array == null) { return null; } int rank = array.Rank; var builder = ArrayBuilder<int>.GetInstance(rank); for (int i = 0; i < rank; i++) { builder.Add(array.GetUpperBound(i) - array.GetLowerBound(i) + 1); } return builder.ToImmutableAndFree(); } } public ReadOnlyCollection<int> ArrayLowerBounds { get { var array = (Array)_rawValue; if (array == null) { return null; } int rank = array.Rank; var builder = ArrayBuilder<int>.GetInstance(rank); for (int i = 0; i < rank; i++) { builder.Add(array.GetLowerBound(i)); } return builder.ToImmutableAndFree(); } } public DkmClrValue InstantiateProxyType(DkmClrType proxyType) { var lmrType = proxyType.GetLmrType(); Debug.Assert(!lmrType.IsGenericTypeDefinition); const BindingFlags bindingFlags = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; var constructor = lmrType.GetConstructors(bindingFlags).Single(); var value = constructor.Invoke(bindingFlags, null, new[] { _rawValue }, null); return new DkmClrValue( value, value, type: proxyType, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None, inspectionContext: this.InspectionContext); } public DkmClrValue InstantiateResultsViewProxy(DkmClrType enumerableType) { var appDomain = enumerableType.AppDomain; var module = GetModule(appDomain, "System.Core.dll"); if (module == null) { return null; } var typeArgs = enumerableType.GenericArguments; Debug.Assert(typeArgs.Count <= 1); var proxyTypeName = (typeArgs.Count == 0) ? "System.Linq.SystemCore_EnumerableDebugView" : "System.Linq.SystemCore_EnumerableDebugView`1"; DkmClrType proxyType; try { proxyType = module.ResolveTypeName(proxyTypeName, typeArgs); } catch (ArgumentException) { // ResolveTypeName throws ArgumentException if type is not found. return null; } return this.InstantiateProxyType(proxyType); } private static DkmClrModuleInstance GetModule(DkmClrAppDomain appDomain, string moduleName) { var modules = appDomain.GetClrModuleInstances(); Debug.Assert(modules.Length > 0); foreach (var module in modules) { if (string.Equals(module.Name, moduleName, StringComparison.OrdinalIgnoreCase)) { return module; } } return null; } private static Type GetAncestorType(Type type, string ancestorTypeName) { if (type.FullName == ancestorTypeName) { return type; } // Search interfaces. foreach (var @interface in type.GetInterfaces()) { var ancestorType = GetAncestorType(@interface, ancestorTypeName); if (ancestorType != null) { return ancestorType; } } // Search base type. var baseType = type.BaseType; if (baseType != null) { return GetAncestorType(baseType, ancestorTypeName); } return null; } private static DkmEvaluationResultFlags GetEvaluationResultFlags(object value) { if (true.Equals(value)) { return DkmEvaluationResultFlags.BooleanTrue; } else if (value is bool) { return DkmEvaluationResultFlags.Boolean; } else { return DkmEvaluationResultFlags.None; } } private unsafe static object Dereference(IntPtr ptr, Type elementType) { // Only handling a subset of types currently. switch (Metadata.Type.GetTypeCode(elementType)) { case TypeCode.Int32: return *(int*)ptr; case TypeCode.Object: if (ptr == IntPtr.Zero) { throw new InvalidOperationException("Dereferencing null"); } return Marshal.PtrToStructure(ptr, ((TypeImpl)elementType).Type); default: throw new InvalidOperationException(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Dks.SimpleToken.Core; using Dks.SimpleToken.Validation.MVC6; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Logging; using Xunit; namespace Dks.SimpleToken.MVC6.Tests { public class MVC6ValidationFilterTest { private const string MatchingParameter = "testParam"; [Fact] public void ShouldDetectValidToken_FromQuery() { //Token generation var tokenProvider = new DummyTokenProvider(); var token = tokenProvider.GenerateToken(new Dictionary<string, string> { { MatchingParameter, "value" } }, 60); //Filter creation var typeFilter = new ValidateTokenAttribute(); var sp = CreateServiceProvider(); var authFilter = typeFilter.CreateInstance(sp) as IAuthorizationFilter; var matchFilter = new MatchTokenDataAttribute(MatchingParameter); //Filter context initialization var actionContext = CraftFakeActionContext(); actionContext.HttpContext.Request.QueryString = QueryString.Create("token", token); var authContext = CraftFakeAuthorizationFilterContext(actionContext); var executingContext = CraftFakeActionExecutingContext(actionContext); executingContext.ActionArguments.Add(MatchingParameter, "value"); //Executing filter action authFilter.OnAuthorization(authContext); Assert.Null(authContext.Result); matchFilter.OnActionExecuting(executingContext); Assert.Null(executingContext.Result); } [Fact] public void ShouldDetectValidToken_FromHeader() { //Token generation var tokenProvider = new DummyTokenProvider(); var token = tokenProvider.GenerateToken(new Dictionary<string, string> { { MatchingParameter, "value" } }, 60); //Filter creation var typeFilter = new ValidateTokenAttribute(); var sp = CreateServiceProvider(); var authFilter = typeFilter.CreateInstance(sp) as IAuthorizationFilter; var matchFilter = new MatchTokenDataAttribute(MatchingParameter); //Filter context initialization var actionContext = CraftFakeActionContext(); actionContext.HttpContext.Request.Headers.Add("X-Secure-Token", token); var authContext = CraftFakeAuthorizationFilterContext(actionContext); var executingContext = CraftFakeActionExecutingContext(actionContext); executingContext.ActionArguments.Add(MatchingParameter, "value"); //Executing filter action authFilter.OnAuthorization(authContext); Assert.Null(authContext.Result); matchFilter.OnActionExecuting(executingContext); Assert.Null(executingContext.Result); } [Fact] public void ShouldDetectMissingToken() { //Filter creation var typeFilter = new ValidateTokenAttribute(); var sp = CreateServiceProvider(); var authFilter = typeFilter.CreateInstance(sp) as IAuthorizationFilter; //Filter context initialization var actionContext = CraftFakeActionContext(); var authContext = CraftFakeAuthorizationFilterContext(actionContext); //Executing filter action authFilter.OnAuthorization(authContext); Assert.NotNull(authContext.Result); Assert.IsType<UnauthorizedResult>(authContext.Result); } [Fact] public void ShouldDetectEmptyToken() { //Filter creation var typeFilter = new ValidateTokenAttribute(); var sp = CreateServiceProvider(); var authFilter = typeFilter.CreateInstance(sp) as IAuthorizationFilter; //Filter context initialization var actionContext = CraftFakeActionContext(); actionContext.HttpContext.Request.QueryString = QueryString.Create("token", " "); var authContext = CraftFakeAuthorizationFilterContext(actionContext); //Executing filter action authFilter.OnAuthorization(authContext); Assert.NotNull(authContext.Result); Assert.IsType<UnauthorizedResult>(authContext.Result); } [Fact] public void ShouldDetectInvalidToken() { //Filter creation var typeFilter = new ValidateTokenAttribute(); var sp = CreateServiceProvider(); var authFilter = typeFilter.CreateInstance(sp) as IAuthorizationFilter; //Filter context initialization var actionContext = CraftFakeActionContext(); actionContext.HttpContext.Request.QueryString = QueryString.Create("token", "RANDOMSTRING"); var authContext = CraftFakeAuthorizationFilterContext(actionContext); //Executing filter action authFilter.OnAuthorization(authContext); Assert.NotNull(authContext.Result); Assert.IsType<UnauthorizedResult>(authContext.Result); } [Fact] public void ShouldDetectExpiredToken() { //Token generation var tokenProvider = new DummyTokenProvider(); var token = tokenProvider.GenerateToken(new Dictionary<string, string> { { MatchingParameter, "value" } }, 1); //Waiting for token to expire Thread.Sleep(1500); //Filter creation var typeFilter = new ValidateTokenAttribute(); var sp = CreateServiceProvider(); var authFilter = typeFilter.CreateInstance(sp) as IAuthorizationFilter; //Filter context initialization var actionContext = CraftFakeActionContext(); actionContext.HttpContext.Request.QueryString = QueryString.Create("token", token); var authContext = CraftFakeAuthorizationFilterContext(actionContext); //Executing filter action authFilter.OnAuthorization(authContext); Assert.NotNull(authContext.Result); Assert.IsType<UnauthorizedResult>(authContext.Result); } [Fact] public void ShouldDetectMismatchingParametersToken() { //Token generation var tokenProvider = new DummyTokenProvider(); var token = tokenProvider.GenerateToken(new Dictionary<string, string> { { MatchingParameter, "value" } }, 60); //Filter creation var typeFilter = new ValidateTokenAttribute(); var sp = CreateServiceProvider(); var authFilter = typeFilter.CreateInstance(sp) as IAuthorizationFilter; var matchFilter = new MatchTokenDataAttribute(MatchingParameter); //Filter context initialization var actionContext = CraftFakeActionContext(); actionContext.HttpContext.Request.QueryString = QueryString.Create("token", token); var authContext = CraftFakeAuthorizationFilterContext(actionContext); var executingContext = CraftFakeActionExecutingContext(actionContext); executingContext.ActionArguments.Add(MatchingParameter, "anothervalue"); //Executing filter action authFilter.OnAuthorization(authContext); Assert.Null(authContext.Result); matchFilter.OnActionExecuting(executingContext); Assert.NotNull(executingContext.Result); Assert.IsType<ForbidResult>(executingContext.Result); } private static AuthorizationFilterContext CraftFakeAuthorizationFilterContext(ActionContext actionContext) { var ctx = new AuthorizationFilterContext(actionContext, new List<IFilterMetadata>()); return ctx; } private static ActionExecutingContext CraftFakeActionExecutingContext(ActionContext actionContext) { var ctx = new ActionExecutingContext(actionContext, new List<IFilterMetadata>(), new Dictionary<string, object>(), null); return ctx; } private static ActionContext CraftFakeActionContext() { var httpContext = new DefaultHttpContext(); var routeData = new RouteData(); var actionDescriptor = new ActionDescriptor(); var ctx = new ActionContext(httpContext, routeData, actionDescriptor); return ctx; } private static IServiceProvider CreateServiceProvider() { var sp = new DummyServiceProvider(); sp.AddType(typeof(ISecureTokenProvider), new DummyTokenProvider()); sp.AddType(typeof(ILoggerFactory), new DummyLoggerFactory()); sp.AddType(typeof(ValidateTokenOptions), new ValidateTokenOptions()); return sp; } private class DummyServiceProvider : IServiceProvider { private Dictionary<Type, object> TypeDictionary = new Dictionary<Type, object>(); public void AddType(Type type, object obj) { TypeDictionary.Add(type, obj); } public object GetService(Type serviceType) { TypeDictionary.TryGetValue(serviceType, out object obj); return obj; } } private class DummyLoggerFactory : ILoggerFactory { public void Dispose() { // noop } public ILogger CreateLogger(string categoryName) { return new DummyLogger(); } public void AddProvider(ILoggerProvider provider) { // noop } private class DummyLogger : ILogger { public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { // noop } public bool IsEnabled(LogLevel logLevel) { return true; } public IDisposable BeginScope<TState>(TState state) { return new DummyDisposable(); } private class DummyDisposable : IDisposable { public void Dispose() { } } } } private class DummyTokenProvider : DefaultSecureTokenProvider { public DummyTokenProvider() : base(new DummyTokenSerializer(), new DummyTokenProtector()) { } private class DummyTokenProtector : ISecureTokenProtector { private static readonly byte[] DummyPreamble = Encoding.UTF8.GetBytes("DUMMY::__"); public byte[] ProtectData(byte[] unprotectedData) { return DummyPreamble.Concat(unprotectedData).ToArray(); } public byte[] UnprotectData(byte[] protectedData) { if (protectedData.Length >= DummyPreamble.Length) { if (protectedData.Take(DummyPreamble.Length).SequenceEqual(DummyPreamble)) { return protectedData.Skip(DummyPreamble.Length).ToArray(); } } throw new Exception(); } } private class DummyTokenSerializer : ISecureTokenSerializer { public byte[] SerializeToken(SecureToken token) { return Encoding.UTF8.GetBytes( $"{token.Issued:O}:::{token.Expire:O}:::{string.Join("&&&", token.Data.Select(kvp => $"{kvp.Key}==={kvp.Value}"))}" ); } public SecureToken DeserializeToken(byte[] serialized) { var str = Encoding.UTF8.GetString(serialized).Split(new[] { ":::" }, StringSplitOptions.None); var issued = DateTimeOffset.Parse(str[0]); var expire = DateTimeOffset.Parse(str[1]); var dict = str[2] .Split(new[] { "&&&" }, StringSplitOptions.None) .Select(p => p.Split(new[] { "===" }, StringSplitOptions.None)) .ToDictionary(pa => pa[0], pa => pa[1]); return SecureToken.Create(issued, expire, dict); } } } } }
using UnityEngine; using UnityEngine.Rendering.LWRP; using UnityEngine.Rendering; namespace UnityEditor.Rendering.LWRP { [CustomEditor(typeof(LightweightRenderPipelineAsset))] public class LightweightRenderPipelineAssetEditor : Editor { internal class Styles { // Groups public static GUIContent generalSettingsText = EditorGUIUtility.TrTextContent("General"); public static GUIContent qualitySettingsText = EditorGUIUtility.TrTextContent("Quality"); public static GUIContent lightingSettingsText = EditorGUIUtility.TrTextContent("Lighting"); public static GUIContent shadowSettingsText = EditorGUIUtility.TrTextContent("Shadows"); public static GUIContent advancedSettingsText = EditorGUIUtility.TrTextContent("Advanced"); // General public static GUIContent rendererTypeText = EditorGUIUtility.TrTextContent("Renderer Type", "Controls the global renderer that LWRP uses for all cameras. Choose between the default Forward Renderer and a custom renderer."); public static GUIContent rendererDataText = EditorGUIUtility.TrTextContent("Data", "A ScriptableObject with rendering data. Required when using a custom Renderer. If none is assigned, LWRP uses the Forward Renderer as default."); public static GUIContent requireDepthTextureText = EditorGUIUtility.TrTextContent("Depth Texture", "If enabled the pipeline will generate camera's depth that can be bound in shaders as _CameraDepthTexture."); public static GUIContent requireOpaqueTextureText = EditorGUIUtility.TrTextContent("Opaque Texture", "If enabled the pipeline will copy the screen to texture after opaque objects are drawn. For transparent objects this can be bound in shaders as _CameraOpaqueTexture."); public static GUIContent opaqueDownsamplingText = EditorGUIUtility.TrTextContent("Opaque Downsampling", "The downsampling method that is used for the opaque texture"); // Quality public static GUIContent hdrText = EditorGUIUtility.TrTextContent("HDR", "Controls the global HDR settings."); public static GUIContent msaaText = EditorGUIUtility.TrTextContent("Anti Aliasing (MSAA)", "Controls the global anti aliasing settings."); public static GUIContent renderScaleText = EditorGUIUtility.TrTextContent("Render Scale", "Scales the camera render target allowing the game to render at a resolution different than native resolution. UI is always rendered at native resolution. When VR is enabled, this is overridden by XRSettings."); // Main light public static GUIContent mainLightRenderingModeText = EditorGUIUtility.TrTextContent("Main Light", "Main light is the brightest directional light."); public static GUIContent supportsMainLightShadowsText = EditorGUIUtility.TrTextContent("Cast Shadows", "If enabled the main light can be a shadow casting light."); public static GUIContent mainLightShadowmapResolutionText = EditorGUIUtility.TrTextContent("Shadow Resolution", "Resolution of the main light shadowmap texture. If cascades are enabled, cascades will be packed into an atlas and this setting controls the maximum shadows atlas resolution."); // Additional lights public static GUIContent addditionalLightsRenderingModeText = EditorGUIUtility.TrTextContent("Additional Lights", "Additional lights support."); public static GUIContent perObjectLimit = EditorGUIUtility.TrTextContent("Per Object Limit", "Maximum amount of additional lights. These lights are sorted and culled per-object."); public static GUIContent supportsAdditionalShadowsText = EditorGUIUtility.TrTextContent("Cast Shadows", "If enabled shadows will be supported for spot lights.\n"); public static GUIContent additionalLightsShadowmapResolution = EditorGUIUtility.TrTextContent("Shadow Resolution", "All additional lights are packed into a single shadowmap atlas. This setting controls the atlas size."); // Shadow settings public static GUIContent shadowDistanceText = EditorGUIUtility.TrTextContent("Distance", "Maximum shadow rendering distance."); public static GUIContent shadowCascadesText = EditorGUIUtility.TrTextContent("Cascades", "Number of cascade splits used in for directional shadows"); public static GUIContent shadowDepthBias = EditorGUIUtility.TrTextContent("Depth Bias", "Controls the distance at which the shadows will be pushed away from the light. Useful for avoiding false self-shadowing artifacts."); public static GUIContent shadowNormalBias = EditorGUIUtility.TrTextContent("Normal Bias", "Controls distance at which the shadow casting surfaces will be shrunk along the surface normal. Useful for avoiding false self-shadowing artifacts."); public static GUIContent supportsSoftShadows = EditorGUIUtility.TrTextContent("Soft Shadows", "If enabled pipeline will perform shadow filtering. Otherwise all lights that cast shadows will fallback to perform a single shadow sample."); // Advanced settings public static GUIContent srpBatcher = EditorGUIUtility.TrTextContent("SRP Batcher (Experimental)", "If enabled, the render pipeline uses the SRP batcher."); public static GUIContent dynamicBatching = EditorGUIUtility.TrTextContent("Dynamic Batching", "If enabled, the render pipeline will batch drawcalls with few triangles together by copying their vertex buffers into a shared buffer on a per-frame basis."); public static GUIContent mixedLightingSupportLabel = EditorGUIUtility.TrTextContent("Mixed Lighting", "Support for mixed light mode."); public static GUIContent shaderVariantLogLevel = EditorGUIUtility.TrTextContent("Shader Variant Log Level", "Controls the level logging in of shader variants information is outputted when a build is performed. Information will appear in the Unity console when the build finishes."); // Dropdown menu options public static string[] mainLightOptions = { "Disabled", "Per Pixel" }; public static string[] shadowCascadeOptions = {"No Cascades", "Two Cascades", "Four Cascades"}; public static string[] opaqueDownsamplingOptions = {"None", "2x (Bilinear)", "4x (Box)", "4x (Bilinear)"}; } SavedBool m_GeneralSettingsFoldout; SavedBool m_QualitySettingsFoldout; SavedBool m_LightingSettingsFoldout; SavedBool m_ShadowSettingsFoldout; SavedBool m_AdvancedSettingsFoldout; SerializedProperty m_RendererTypeProp; SerializedProperty m_RendererDataProp; SerializedProperty m_RequireDepthTextureProp; SerializedProperty m_RequireOpaqueTextureProp; SerializedProperty m_OpaqueDownsamplingProp; SerializedProperty m_HDR; SerializedProperty m_MSAA; SerializedProperty m_RenderScale; SerializedProperty m_MainLightRenderingModeProp; SerializedProperty m_MainLightShadowsSupportedProp; SerializedProperty m_MainLightShadowmapResolutionProp; SerializedProperty m_AdditionalLightsRenderingModeProp; SerializedProperty m_AdditionalLightsPerObjectLimitProp; SerializedProperty m_AdditionalLightShadowsSupportedProp; SerializedProperty m_AdditionalLightShadowmapResolutionProp; SerializedProperty m_ShadowDistanceProp; SerializedProperty m_ShadowCascadesProp; SerializedProperty m_ShadowCascade2SplitProp; SerializedProperty m_ShadowCascade4SplitProp; SerializedProperty m_ShadowDepthBiasProp; SerializedProperty m_ShadowNormalBiasProp; SerializedProperty m_SoftShadowsSupportedProp; SerializedProperty m_SRPBatcher; SerializedProperty m_SupportsDynamicBatching; SerializedProperty m_MixedLightingSupportedProp; SerializedProperty m_ShaderVariantLogLevel; internal static LightRenderingMode selectedLightRenderingMode; public override void OnInspectorGUI() { serializedObject.Update(); DrawGeneralSettings(); DrawQualitySettings(); DrawLightingSettings(); DrawShadowSettings(); DrawAdvancedSettings(); serializedObject.ApplyModifiedProperties(); } void OnEnable() { m_GeneralSettingsFoldout = new SavedBool($"{target.GetType()}.GeneralSettingsFoldout", false); m_QualitySettingsFoldout = new SavedBool($"{target.GetType()}.QualitySettingsFoldout", false); m_LightingSettingsFoldout = new SavedBool($"{target.GetType()}.LightingSettingsFoldout", false); m_ShadowSettingsFoldout = new SavedBool($"{target.GetType()}.ShadowSettingsFoldout", false); m_AdvancedSettingsFoldout = new SavedBool($"{target.GetType()}.AdvancedSettingsFoldout", false); m_RendererTypeProp = serializedObject.FindProperty("m_RendererType"); m_RendererDataProp = serializedObject.FindProperty("m_RendererData"); m_RequireDepthTextureProp = serializedObject.FindProperty("m_RequireDepthTexture"); m_RequireOpaqueTextureProp = serializedObject.FindProperty("m_RequireOpaqueTexture"); m_OpaqueDownsamplingProp = serializedObject.FindProperty("m_OpaqueDownsampling"); m_HDR = serializedObject.FindProperty("m_SupportsHDR"); m_MSAA = serializedObject.FindProperty("m_MSAA"); m_RenderScale = serializedObject.FindProperty("m_RenderScale"); m_MainLightRenderingModeProp = serializedObject.FindProperty("m_MainLightRenderingMode"); m_MainLightShadowsSupportedProp = serializedObject.FindProperty("m_MainLightShadowsSupported"); m_MainLightShadowmapResolutionProp = serializedObject.FindProperty("m_MainLightShadowmapResolution"); m_AdditionalLightsRenderingModeProp = serializedObject.FindProperty("m_AdditionalLightsRenderingMode"); m_AdditionalLightsPerObjectLimitProp = serializedObject.FindProperty("m_AdditionalLightsPerObjectLimit"); m_AdditionalLightShadowsSupportedProp = serializedObject.FindProperty("m_AdditionalLightShadowsSupported"); m_AdditionalLightShadowmapResolutionProp = serializedObject.FindProperty("m_AdditionalLightsShadowmapResolution"); m_ShadowDistanceProp = serializedObject.FindProperty("m_ShadowDistance"); m_ShadowCascadesProp = serializedObject.FindProperty("m_ShadowCascades"); m_ShadowCascade2SplitProp = serializedObject.FindProperty("m_Cascade2Split"); m_ShadowCascade4SplitProp = serializedObject.FindProperty("m_Cascade4Split"); m_ShadowDepthBiasProp = serializedObject.FindProperty("m_ShadowDepthBias"); m_ShadowNormalBiasProp = serializedObject.FindProperty("m_ShadowNormalBias"); m_SoftShadowsSupportedProp = serializedObject.FindProperty("m_SoftShadowsSupported"); m_SRPBatcher = serializedObject.FindProperty("m_UseSRPBatcher"); m_SupportsDynamicBatching = serializedObject.FindProperty("m_SupportsDynamicBatching"); m_MixedLightingSupportedProp = serializedObject.FindProperty("m_MixedLightingSupported"); m_ShaderVariantLogLevel = serializedObject.FindProperty("m_ShaderVariantLogLevel"); selectedLightRenderingMode = (LightRenderingMode)m_AdditionalLightsRenderingModeProp.intValue; } void DrawGeneralSettings() { m_GeneralSettingsFoldout.value = EditorGUILayout.BeginFoldoutHeaderGroup(m_GeneralSettingsFoldout.value, Styles.generalSettingsText); if (m_GeneralSettingsFoldout.value) { EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(m_RendererTypeProp, Styles.rendererTypeText); if (EditorGUI.EndChangeCheck()) { if (m_RendererTypeProp.intValue != (int) RendererType.Custom) m_RendererDataProp.objectReferenceValue = LightweightRenderPipeline.asset.LoadBuiltinRendererData(); } if (m_RendererTypeProp.intValue == (int) RendererType.Custom) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_RendererDataProp, Styles.rendererDataText); EditorGUI.indentLevel--; } EditorGUILayout.PropertyField(m_RequireDepthTextureProp, Styles.requireDepthTextureText); EditorGUILayout.PropertyField(m_RequireOpaqueTextureProp, Styles.requireOpaqueTextureText); EditorGUI.indentLevel++; EditorGUI.BeginDisabledGroup(!m_RequireOpaqueTextureProp.boolValue); EditorGUILayout.PropertyField(m_OpaqueDownsamplingProp, Styles.opaqueDownsamplingText); EditorGUI.EndDisabledGroup(); EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUILayout.Space(); } EditorGUILayout.EndFoldoutHeaderGroup(); } void DrawQualitySettings() { m_QualitySettingsFoldout.value = EditorGUILayout.BeginFoldoutHeaderGroup(m_QualitySettingsFoldout.value, Styles.qualitySettingsText); if (m_QualitySettingsFoldout.value) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_HDR, Styles.hdrText); EditorGUILayout.PropertyField(m_MSAA, Styles.msaaText); EditorGUI.BeginDisabledGroup(XRGraphics.enabled); m_RenderScale.floatValue = EditorGUILayout.Slider(Styles.renderScaleText, m_RenderScale.floatValue, LightweightRenderPipeline.minRenderScale, LightweightRenderPipeline.maxRenderScale); EditorGUI.EndDisabledGroup(); EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUILayout.Space(); } EditorGUILayout.EndFoldoutHeaderGroup(); } void DrawLightingSettings() { m_LightingSettingsFoldout.value = EditorGUILayout.BeginFoldoutHeaderGroup(m_LightingSettingsFoldout.value, Styles.lightingSettingsText); if (m_LightingSettingsFoldout.value) { EditorGUI.indentLevel++; // Main Light bool disableGroup = false; EditorGUI.BeginDisabledGroup(disableGroup); CoreEditorUtils.DrawPopup(Styles.mainLightRenderingModeText, m_MainLightRenderingModeProp, Styles.mainLightOptions); EditorGUI.EndDisabledGroup(); EditorGUI.indentLevel++; disableGroup |= !m_MainLightRenderingModeProp.boolValue; EditorGUI.BeginDisabledGroup(disableGroup); EditorGUILayout.PropertyField(m_MainLightShadowsSupportedProp, Styles.supportsMainLightShadowsText); EditorGUI.EndDisabledGroup(); disableGroup |= !m_MainLightShadowsSupportedProp.boolValue; EditorGUI.BeginDisabledGroup(disableGroup); EditorGUILayout.PropertyField(m_MainLightShadowmapResolutionProp, Styles.mainLightShadowmapResolutionText); EditorGUI.EndDisabledGroup(); EditorGUI.indentLevel--; EditorGUILayout.Space(); // Additional light selectedLightRenderingMode = (LightRenderingMode)EditorGUILayout.EnumPopup(Styles.addditionalLightsRenderingModeText, selectedLightRenderingMode); m_AdditionalLightsRenderingModeProp.intValue = (int)selectedLightRenderingMode; EditorGUI.indentLevel++; disableGroup = m_AdditionalLightsRenderingModeProp.intValue == (int)LightRenderingMode.Disabled; EditorGUI.BeginDisabledGroup(disableGroup); m_AdditionalLightsPerObjectLimitProp.intValue = EditorGUILayout.IntSlider(Styles.perObjectLimit, m_AdditionalLightsPerObjectLimitProp.intValue, 0, LightweightRenderPipeline.maxPerObjectLights); EditorGUI.EndDisabledGroup(); disableGroup |= (m_AdditionalLightsPerObjectLimitProp.intValue == 0 || m_AdditionalLightsRenderingModeProp.intValue != (int)LightRenderingMode.PerPixel); EditorGUI.BeginDisabledGroup(disableGroup); EditorGUILayout.PropertyField(m_AdditionalLightShadowsSupportedProp, Styles.supportsAdditionalShadowsText); EditorGUI.EndDisabledGroup(); disableGroup |= !m_AdditionalLightShadowsSupportedProp.boolValue; EditorGUI.BeginDisabledGroup(disableGroup); EditorGUILayout.PropertyField(m_AdditionalLightShadowmapResolutionProp, Styles.additionalLightsShadowmapResolution); EditorGUI.EndDisabledGroup(); EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUILayout.Space(); } EditorGUILayout.EndFoldoutHeaderGroup(); } void DrawShadowSettings() { m_ShadowSettingsFoldout.value = EditorGUILayout.BeginFoldoutHeaderGroup(m_ShadowSettingsFoldout.value, Styles.shadowSettingsText); if (m_ShadowSettingsFoldout.value) { EditorGUI.indentLevel++; m_ShadowDistanceProp.floatValue = Mathf.Max(0.0f, EditorGUILayout.FloatField(Styles.shadowDistanceText, m_ShadowDistanceProp.floatValue)); CoreEditorUtils.DrawPopup(Styles.shadowCascadesText, m_ShadowCascadesProp, Styles.shadowCascadeOptions); ShadowCascadesOption cascades = (ShadowCascadesOption)m_ShadowCascadesProp.intValue; if (cascades == ShadowCascadesOption.FourCascades) EditorUtils.DrawCascadeSplitGUI<Vector3>(ref m_ShadowCascade4SplitProp); else if (cascades == ShadowCascadesOption.TwoCascades) EditorUtils.DrawCascadeSplitGUI<float>(ref m_ShadowCascade2SplitProp); m_ShadowDepthBiasProp.floatValue = EditorGUILayout.Slider(Styles.shadowDepthBias, m_ShadowDepthBiasProp.floatValue, 0.0f, LightweightRenderPipeline.maxShadowBias); m_ShadowNormalBiasProp.floatValue = EditorGUILayout.Slider(Styles.shadowNormalBias, m_ShadowNormalBiasProp.floatValue, 0.0f, LightweightRenderPipeline.maxShadowBias); EditorGUILayout.PropertyField(m_SoftShadowsSupportedProp, Styles.supportsSoftShadows); EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUILayout.Space(); } EditorGUILayout.EndFoldoutHeaderGroup(); } void DrawAdvancedSettings() { m_AdvancedSettingsFoldout.value = EditorGUILayout.BeginFoldoutHeaderGroup(m_AdvancedSettingsFoldout.value, Styles.advancedSettingsText); if (m_AdvancedSettingsFoldout.value) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_SRPBatcher, Styles.srpBatcher); EditorGUILayout.PropertyField(m_SupportsDynamicBatching, Styles.dynamicBatching); EditorGUILayout.PropertyField(m_MixedLightingSupportedProp, Styles.mixedLightingSupportLabel); EditorGUILayout.PropertyField(m_ShaderVariantLogLevel, Styles.shaderVariantLogLevel); EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUILayout.Space(); } EditorGUILayout.EndFoldoutHeaderGroup(); } } }
// 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 representation of a 32 bit 2's complement ** integer. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Int32 : IComparable, IConvertible, IFormattable, IComparable<Int32>, IEquatable<Int32> { private int m_value; // Do not rename (binary serialization) public const int MaxValue = 0x7fffffff; public const int MinValue = unchecked((int)0x80000000); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns : // 0 if the values are equal // Negative number if _value is less than value // Positive number if _value is more than value // null is considered to be less than any instance, hence returns positive number // If object is not of type Int32, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Int32) { // NOTE: Cannot use return (_value - value) as this causes a wrap // around in cases where _value - value > MaxValue. int i = (int)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeInt32); } public int CompareTo(int value) { // NOTE: Cannot use return (_value - value) as this causes a wrap // around in cases where _value - value > MaxValue. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is Int32)) { return false; } return m_value == ((Int32)obj).m_value; } [NonVersionable] public bool Equals(Int32 obj) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return m_value; } public override String ToString() { return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(String format) { return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format, IFormatProvider provider) { return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } public static int Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static int Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static int Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static int Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider)); } public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider)); } // Parses an integer from a String. Returns false rather // than throwing exceptin if input is invalid // public static bool TryParse(String s, out Int32 result) { if (s == null) { result = 0; return false; } return Number.TryParseInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } // Parses an integer from a String in the given style. Returns false rather // than throwing exceptin if input is invalid // public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return Number.TryParseInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, out int result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Int32; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return m_value; } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int32", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
//----------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // 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 System.IdentityModel.Tokens { using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IdentityModel.Configuration; using System.IdentityModel.Selectors; using System.Security.Claims; using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Security; using System.Xml; using Attributes = System.IdentityModel.Tokens.JwtConfigurationStrings.Attributes; using AttributeValues = System.IdentityModel.Tokens.JwtConfigurationStrings.AttributeValues; using Elements = System.IdentityModel.Tokens.JwtConfigurationStrings.Elements; /// <summary> /// Provides a location for settings that control how the <see cref="JwtSecurityTokenHandler"/> validates or creates a <see cref="JwtSecurityToken"/>. /// </summary> /// <remarks>These values have precedence over <see cref="SecurityTokenHandler.Configuration"/>.</remarks> [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Suppressed for private or internal fields.")] public class JwtSecurityTokenRequirement { // The defaults will only be used if some verification properties are set in config and others are not private X509RevocationMode defaultRevocationMode = X509RevocationMode.Online; private X509CertificateValidationMode defaultValidationMode = X509CertificateValidationMode.PeerOrChainTrust; private StoreLocation defaultStoreLocation = StoreLocation.LocalMachine; private uint defaultTokenLifetimeInMinutes = 600; private uint maxTokenSizeInBytes = 2 * 1024 * 1024; private string nameClaimType; private string roleClaimType; private X509CertificateValidator certificateValidator; // This indicates that the clockSkew was never set private TimeSpan? maxClockSkew = null; /// <summary> /// Initializes a new instance of the <see cref="JwtSecurityTokenRequirement"/> class. /// </summary> public JwtSecurityTokenRequirement() { } /// <summary> /// Initializes a new instance of the <see cref="JwtSecurityTokenRequirement"/> class. /// </summary> /// <remarks> /// <para>A single XML element is expected with up to four optional attributes: {'expected values'} and up to five optional child elements.</para> /// <para>&lt;jwtSecurityTokenRequirement</para> /// <para>&#160;&#160;&#160;&#160;issuerCertificateRevocationMode: {NoCheck, OnLine, OffLine}</para> /// <para>&#160;&#160;&#160;&#160;issuerCertificateTrustedStoreLocation: {CurrentUser, LocalMachine}</para> /// <para>&#160;&#160;&#160;&#160;issuerCertificateValidator: type derived from <see cref="X509CertificateValidator"/></para> /// <para>&#160;&#160;&#160;&#160;issuerCertificateValidationMode: {ChainTrust, Custom, None, PeerTrust, PeerOrChainTrust}</para> /// <para>></para> /// <para>&#160;&#160;&#160;&#160;&lt;nameClaimType value = 'user defined type'/></para> /// <para>&#160;&#160;&#160;&#160;&lt;roleClaimType value = 'user defined type'/></para> /// <para>&#160;&#160;&#160;&#160;&lt;defaultTokenLifetimeInMinutes value = 'uint'/></para> /// <para>&#160;&#160;&#160;&#160;&lt;maxTokenSizeInBytes value = 'uint'/></para> /// <para>&#160;&#160;&#160;&#160;&lt;maxClockSkewInMinutes value = 'uint'/></para> /// <para>&lt;/jwtSecurityTokenRequirement></para> /// </remarks> /// <param name="element">The <see cref="XmlElement"/> to be parsed.</param> /// <exception cref="ArgumentNullException">'element' is null.</exception> /// <exception cref="ConfigurationErrorsException"><see cref="XmlElement.LocalName"/> is not 'jwtSecurityTokenRequirement'.</exception> /// <exception cref="ConfigurationErrorsException">if a <see cref="XmlAttribute.LocalName"/> is not expected.</exception> /// <exception cref="ConfigurationErrorsException">a <see cref="XmlAttribute.Value"/> of &lt;jwtSecurityTokenRequirement> is null or whitespace.</exception> /// <exception cref="ConfigurationErrorsException">a <see cref="XmlAttribute.Value"/> is not expected.</exception> /// <exception cref="ConfigurationErrorsException">if the <see cref="XmlElement.LocalName"/> of a child element of &lt;jwtSecurityTokenRequirement> is not expected.</exception> /// <exception cref="ConfigurationErrorsException">if a child element of &lt;jwtSecurityTokenRequirement> is not well formed.</exception> /// <exception cref="ConfigurationErrorsException">if the 'issuerCertificateValidationMode' == 'Custom' and a 'issuerCertificateValidator' attribute was not specified.</exception> /// <exception cref="ConfigurationErrorsException">if the runtime was not able to create the type specified by a the 'issuerCertificateValidator' attribute.</exception> /// <exception cref="ConfigurationErrorsException">if a child element of &lt;jwtSecurityTokenRequirement> is not well formed.</exception> [SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Reviewed. Suppression is OK here.")] public JwtSecurityTokenRequirement(XmlElement element) { if (element == null) { throw new ArgumentNullException("element"); } if (element.LocalName != Elements.JwtSecurityTokenRequirement) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10601, element.LocalName, element.OuterXml)); } X509RevocationMode revocationMode = this.defaultRevocationMode; X509CertificateValidationMode certificateValidationMode = this.defaultValidationMode; StoreLocation trustedStoreLocation = this.defaultStoreLocation; string customValidator = null; bool createCertificateValidator = false; HashSet<string> itemsProcessed = new HashSet<string>(); foreach (XmlAttribute attribute in element.Attributes) { if (string.IsNullOrWhiteSpace(attribute.Value)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10600, attribute.LocalName, element.OuterXml)); } if (itemsProcessed.Contains(attribute.Value)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10617, attribute.LocalName, element.OuterXml)); } if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.Validator)) { customValidator = attribute.Value; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.RevocationMode)) { createCertificateValidator = true; if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509RevocationModeNoCheck)) { revocationMode = X509RevocationMode.NoCheck; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509RevocationModeOffline)) { revocationMode = X509RevocationMode.Offline; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509RevocationModeOnline)) { revocationMode = X509RevocationMode.Online; } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10606, Attributes.RevocationMode, attribute.Value, string.Format( CultureInfo.InvariantCulture, "'{0}', '{1}', '{2}'", AttributeValues.X509RevocationModeNoCheck, AttributeValues.X509RevocationModeOffline, AttributeValues.X509RevocationModeOnline), element.OuterXml)); } } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.ValidationMode)) { createCertificateValidator = true; if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModeChainTrust)) { certificateValidationMode = X509CertificateValidationMode.ChainTrust; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModePeerOrChainTrust)) { certificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModePeerTrust)) { certificateValidationMode = X509CertificateValidationMode.PeerTrust; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModeNone)) { certificateValidationMode = X509CertificateValidationMode.None; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModeCustom)) { certificateValidationMode = X509CertificateValidationMode.Custom; } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10606, Attributes.ValidationMode, attribute.Value, string.Format( CultureInfo.InvariantCulture, "'{0}', '{1}', '{2}', '{3}', '{4}'", AttributeValues.X509CertificateValidationModeChainTrust, AttributeValues.X509CertificateValidationModePeerOrChainTrust, AttributeValues.X509CertificateValidationModePeerTrust, AttributeValues.X509CertificateValidationModeNone, AttributeValues.X509CertificateValidationModeCustom), element.OuterXml)); } } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.TrustedStoreLocation)) { createCertificateValidator = true; if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509TrustedStoreLocationCurrentUser)) { trustedStoreLocation = StoreLocation.CurrentUser; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509TrustedStoreLocationLocalMachine)) { trustedStoreLocation = StoreLocation.LocalMachine; } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10606, Attributes.TrustedStoreLocation, attribute.Value, "'" + AttributeValues.X509TrustedStoreLocationCurrentUser + "', '" + AttributeValues.X509TrustedStoreLocationLocalMachine + "'", element.OuterXml)); } } else { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10608, Elements.JwtSecurityTokenRequirement, attribute.LocalName, element.OuterXml)); } } List<XmlElement> configElements = XmlUtil.GetXmlElements(element.ChildNodes); HashSet<string> elementsProcessed = new HashSet<string>(); foreach (XmlElement childElement in configElements) { if (childElement.Attributes.Count > 1) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10609, childElement.LocalName, Attributes.Value, element.OuterXml)); } if (childElement.Attributes.Count == 0) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10607, childElement.LocalName, Attributes.Value, element.OuterXml)); } if (string.IsNullOrWhiteSpace(childElement.Attributes[0].LocalName)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10600, Attributes.Value, element.OuterXml)); } if (!StringComparer.Ordinal.Equals(childElement.Attributes[0].LocalName, Attributes.Value)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10610, childElement.LocalName, Attributes.Value, childElement.Attributes[0].LocalName, element.OuterXml)); } if (elementsProcessed.Contains(childElement.LocalName)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10616, childElement.LocalName, element.OuterXml)); } elementsProcessed.Add(childElement.LocalName); if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.NameClaimType)) { this.NameClaimType = childElement.Attributes[0].Value; } else if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.RoleClaimType)) { this.RoleClaimType = childElement.Attributes[0].Value; } else { try { if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.MaxTokenSizeInBytes)) { this.MaximumTokenSizeInBytes = Convert.ToUInt32(childElement.Attributes[0].Value, CultureInfo.InvariantCulture); } else if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.DefaultTokenLifetimeInMinutes)) { this.DefaultTokenLifetimeInMinutes = Convert.ToUInt32(childElement.Attributes[0].Value, CultureInfo.InvariantCulture); } else if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.MaxClockSkewInMinutes)) { // uint.MaxValue < TimeSpan.MaxValue.TotalMinutes. If this can be parsed, we can set it. uint clockSkewInMinutes = Convert.ToUInt32(childElement.Attributes[0].Value, CultureInfo.InvariantCulture); this.MaxClockSkew = TimeSpan.FromMinutes(clockSkewInMinutes); } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10611, Elements.JwtSecurityTokenRequirement, childElement.LocalName, string.Format( CultureInfo.InvariantCulture, "{0}', '{1}', '{2}', '{3}', '{4}", Elements.NameClaimType, Elements.RoleClaimType, Elements.MaxTokenSizeInBytes, Elements.MaxClockSkewInMinutes, Elements.DefaultTokenLifetimeInMinutes), element.OuterXml)); } } catch (OverflowException oex) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10603, childElement.LocalName, childElement.OuterXml, oex), oex); } catch (FormatException fex) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10603, childElement.LocalName, childElement.OuterXml, fex), fex); } catch (ArgumentOutOfRangeException aex) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10603, childElement.LocalName, childElement.OuterXml, aex), aex); } } } if (certificateValidationMode == X509CertificateValidationMode.Custom) { Type customValidatorType = null; if (customValidator == null) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10612, Attributes.ValidationMode, Attributes.Validator, element.OuterXml)); } try { customValidatorType = Type.GetType(customValidator, true); CustomTypeElement typeElement = new CustomTypeElement(); typeElement.Type = customValidatorType; this.certificateValidator = CustomTypeElement.Resolve<X509CertificateValidator>(typeElement); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10613, customValidator, Attributes.Validator, ex, element.OuterXml)); } } else if (customValidator != null) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10619, Attributes.Validator, Attributes.ValidationMode, AttributeValues.X509CertificateValidationModeCustom, certificateValidationMode, typeof(X509CertificateValidator).ToString(), customValidator, element.OuterXml)); } else if (createCertificateValidator) { this.certificateValidator = new X509CertificateValidatorEx(certificateValidationMode, revocationMode, trustedStoreLocation); } } /// <summary> /// Gets or sets the <see cref="X509CertificateValidator"/> for validating <see cref="X509Certificate2"/>(s). /// </summary> public X509CertificateValidator CertificateValidator { get { return this.certificateValidator; } set { this.certificateValidator = value; } } /// <summary> /// Gets or sets the <see cref="string"/> the <see cref="JwtSecurityTokenHandler"/> passes as a parameter to <see cref="ClaimsIdentity(string, string, string)"/>. /// <para>This defines the <see cref="Claim.Type"/> to match when finding the <see cref="Claim.Value"/> that is used for the <see cref="ClaimsIdentity.Name"/> property.</para> /// </summary> public string NameClaimType { get { return this.nameClaimType; } set { this.nameClaimType = value; } } /// <summary> /// Gets or sets the <see cref="string"/> the <see cref="JwtSecurityTokenHandler"/> passes as a parameter to <see cref="ClaimsIdentity(string, string, string)"/>. /// <para>This defines the <see cref="Claim"/>(s) that will be considered when answering <see cref="ClaimsPrincipal.IsInRole( string )"/></para> /// </summary> public string RoleClaimType { get { return this.roleClaimType; } set { this.roleClaimType = value; } } /// <summary> /// Gets or sets the maximum size of a <see cref="JwtSecurityToken"/> the <see cref="JwtSecurityTokenHandler"/> will read and validate. /// </summary> /// <remarks>Default: 2 megabytes.</remarks> /// <exception cref="ArgumentOutOfRangeException">if value is 0.</exception> public uint MaximumTokenSizeInBytes { get { return this.maxTokenSizeInBytes; } set { if (value == 0) { throw new ArgumentOutOfRangeException("value", JwtErrors.Jwt10116); } this.maxTokenSizeInBytes = value; } } /// <summary> /// Gets or sets the default for token lifetime. /// <see cref="JwtSecurityTokenHandler"/> uses this value when creating a <see cref="JwtSecurityToken"/> if the expiration time is not specified. The expiration time will be set to <see cref="DateTime.UtcNow"/> + <see cref="TimeSpan.FromMinutes"/> with <see cref="JwtSecurityTokenRequirement.DefaultTokenLifetimeInMinutes"/> as the parameter. /// </summary> /// <remarks>Default: 600.</remarks> /// <exception cref="ArgumentOutOfRangeException">value == 0.</exception> public uint DefaultTokenLifetimeInMinutes { get { return this.defaultTokenLifetimeInMinutes; } set { if (value == 0) { throw new ArgumentOutOfRangeException("value", JwtErrors.Jwt10115); } this.defaultTokenLifetimeInMinutes = value; } } /// <summary> /// Gets or sets the maximum clock skew to use when validating lifetime of a <see cref="JwtSecurityToken"/>. /// </summary> /// <exception cref="ArgumentOutOfRangeException"><see cref="TimeSpan"/>? has a value and it is less than <see cref="TimeSpan.Zero"/>.</exception> public TimeSpan? MaxClockSkew { get { return this.maxClockSkew; } set { if (value == null && value.HasValue && value.Value < TimeSpan.Zero) { throw new ArgumentOutOfRangeException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10111, value.Value)); } this.maxClockSkew = value; } } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// EmailTemplate /// </summary> [DataContract] public partial class EmailTemplate : IEquatable<EmailTemplate>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="EmailTemplate" /> class. /// </summary> /// <param name="containerCjson">Container cjson.</param> /// <param name="description">Description of email template.</param> /// <param name="emailTemplateOid">Email template oid.</param> /// <param name="emailTemplateVmPath">Email Template VM Path.</param> /// <param name="merchantId">Merchant ID.</param> /// <param name="name">Name of email template.</param> /// <param name="previewAmazonListingKey">Amazon key for preview png image.</param> /// <param name="sortOrder">Sort order (optional).</param> /// <param name="storefrontOid">StoreFront oid.</param> /// <param name="system">True if this email template is system-wide,false if merchant specific.</param> /// <param name="triggerType">Trigger type.</param> public EmailTemplate(string containerCjson = default(string), string description = default(string), int? emailTemplateOid = default(int?), string emailTemplateVmPath = default(string), string merchantId = default(string), string name = default(string), string previewAmazonListingKey = default(string), int? sortOrder = default(int?), int? storefrontOid = default(int?), bool? system = default(bool?), string triggerType = default(string)) { this.ContainerCjson = containerCjson; this.Description = description; this.EmailTemplateOid = emailTemplateOid; this.EmailTemplateVmPath = emailTemplateVmPath; this.MerchantId = merchantId; this.Name = name; this.PreviewAmazonListingKey = previewAmazonListingKey; this.SortOrder = sortOrder; this.StorefrontOid = storefrontOid; this.System = system; this.TriggerType = triggerType; } /// <summary> /// Container cjson /// </summary> /// <value>Container cjson</value> [DataMember(Name="container_cjson", EmitDefaultValue=false)] public string ContainerCjson { get; set; } /// <summary> /// Description of email template /// </summary> /// <value>Description of email template</value> [DataMember(Name="description", EmitDefaultValue=false)] public string Description { get; set; } /// <summary> /// Email template oid /// </summary> /// <value>Email template oid</value> [DataMember(Name="email_template_oid", EmitDefaultValue=false)] public int? EmailTemplateOid { get; set; } /// <summary> /// Email Template VM Path /// </summary> /// <value>Email Template VM Path</value> [DataMember(Name="email_template_vm_path", EmitDefaultValue=false)] public string EmailTemplateVmPath { get; set; } /// <summary> /// Merchant ID /// </summary> /// <value>Merchant ID</value> [DataMember(Name="merchant_id", EmitDefaultValue=false)] public string MerchantId { get; set; } /// <summary> /// Name of email template /// </summary> /// <value>Name of email template</value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Amazon key for preview png image /// </summary> /// <value>Amazon key for preview png image</value> [DataMember(Name="preview_amazon_listing_key", EmitDefaultValue=false)] public string PreviewAmazonListingKey { get; set; } /// <summary> /// Sort order (optional) /// </summary> /// <value>Sort order (optional)</value> [DataMember(Name="sort_order", EmitDefaultValue=false)] public int? SortOrder { get; set; } /// <summary> /// StoreFront oid /// </summary> /// <value>StoreFront oid</value> [DataMember(Name="storefront_oid", EmitDefaultValue=false)] public int? StorefrontOid { get; set; } /// <summary> /// True if this email template is system-wide,false if merchant specific /// </summary> /// <value>True if this email template is system-wide,false if merchant specific</value> [DataMember(Name="system", EmitDefaultValue=false)] public bool? System { get; set; } /// <summary> /// Trigger type /// </summary> /// <value>Trigger type</value> [DataMember(Name="trigger_type", EmitDefaultValue=false)] public string TriggerType { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class EmailTemplate {\n"); sb.Append(" ContainerCjson: ").Append(ContainerCjson).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" EmailTemplateOid: ").Append(EmailTemplateOid).Append("\n"); sb.Append(" EmailTemplateVmPath: ").Append(EmailTemplateVmPath).Append("\n"); sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PreviewAmazonListingKey: ").Append(PreviewAmazonListingKey).Append("\n"); sb.Append(" SortOrder: ").Append(SortOrder).Append("\n"); sb.Append(" StorefrontOid: ").Append(StorefrontOid).Append("\n"); sb.Append(" System: ").Append(System).Append("\n"); sb.Append(" TriggerType: ").Append(TriggerType).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as EmailTemplate); } /// <summary> /// Returns true if EmailTemplate instances are equal /// </summary> /// <param name="input">Instance of EmailTemplate to be compared</param> /// <returns>Boolean</returns> public bool Equals(EmailTemplate input) { if (input == null) return false; return ( this.ContainerCjson == input.ContainerCjson || (this.ContainerCjson != null && this.ContainerCjson.Equals(input.ContainerCjson)) ) && ( this.Description == input.Description || (this.Description != null && this.Description.Equals(input.Description)) ) && ( this.EmailTemplateOid == input.EmailTemplateOid || (this.EmailTemplateOid != null && this.EmailTemplateOid.Equals(input.EmailTemplateOid)) ) && ( this.EmailTemplateVmPath == input.EmailTemplateVmPath || (this.EmailTemplateVmPath != null && this.EmailTemplateVmPath.Equals(input.EmailTemplateVmPath)) ) && ( this.MerchantId == input.MerchantId || (this.MerchantId != null && this.MerchantId.Equals(input.MerchantId)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.PreviewAmazonListingKey == input.PreviewAmazonListingKey || (this.PreviewAmazonListingKey != null && this.PreviewAmazonListingKey.Equals(input.PreviewAmazonListingKey)) ) && ( this.SortOrder == input.SortOrder || (this.SortOrder != null && this.SortOrder.Equals(input.SortOrder)) ) && ( this.StorefrontOid == input.StorefrontOid || (this.StorefrontOid != null && this.StorefrontOid.Equals(input.StorefrontOid)) ) && ( this.System == input.System || (this.System != null && this.System.Equals(input.System)) ) && ( this.TriggerType == input.TriggerType || (this.TriggerType != null && this.TriggerType.Equals(input.TriggerType)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ContainerCjson != null) hashCode = hashCode * 59 + this.ContainerCjson.GetHashCode(); if (this.Description != null) hashCode = hashCode * 59 + this.Description.GetHashCode(); if (this.EmailTemplateOid != null) hashCode = hashCode * 59 + this.EmailTemplateOid.GetHashCode(); if (this.EmailTemplateVmPath != null) hashCode = hashCode * 59 + this.EmailTemplateVmPath.GetHashCode(); if (this.MerchantId != null) hashCode = hashCode * 59 + this.MerchantId.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.PreviewAmazonListingKey != null) hashCode = hashCode * 59 + this.PreviewAmazonListingKey.GetHashCode(); if (this.SortOrder != null) hashCode = hashCode * 59 + this.SortOrder.GetHashCode(); if (this.StorefrontOid != null) hashCode = hashCode * 59 + this.StorefrontOid.GetHashCode(); if (this.System != null) hashCode = hashCode * 59 + this.System.GetHashCode(); if (this.TriggerType != null) hashCode = hashCode * 59 + this.TriggerType.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { // Name (string) maxLength if(this.Name != null && this.Name.Length > 250) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, length must be less than 250.", new [] { "Name" }); } // PreviewAmazonListingKey (string) maxLength if(this.PreviewAmazonListingKey != null && this.PreviewAmazonListingKey.Length > 250) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PreviewAmazonListingKey, length must be less than 250.", new [] { "PreviewAmazonListingKey" }); } // TriggerType (string) maxLength if(this.TriggerType != null && this.TriggerType.Length > 100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for TriggerType, length must be less than 100.", new [] { "TriggerType" }); } yield break; } } }
// 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.IO; using CultureInfo = System.Globalization.CultureInfo; namespace System.Xml.Linq { /// <summary> /// Represents a class that allows elements to be streamed /// on input and output. /// </summary> public class XStreamingElement { internal XName name; internal object content; /// <summary> /// Creates a <see cref="XStreamingElement"/> node with a given name /// </summary> /// <param name="name">The name to assign to the new <see cref="XStreamingElement"/> node</param> public XStreamingElement(XName name) { if (name == null) throw new ArgumentNullException(nameof(name)); this.name = name; } /// <summary> /// Creates a <see cref="XStreamingElement"/> node with a given name and content /// </summary> /// <param name="name">The name to assign to the new <see cref="XStreamingElement"/> node</param> /// <param name="content">The content to assign to the new <see cref="XStreamingElement"/> node</param> public XStreamingElement(XName name, object content) : this(name) { this.content = content is List<object> ? new object[] { content } : content; } /// <summary> /// Creates a <see cref="XStreamingElement"/> node with a given name and content /// </summary> /// <param name="name">The name to assign to the new <see cref="XStreamingElement"/> node</param> /// <param name="content">An array containing content to assign to the new <see cref="XStreamingElement"/> node</param> public XStreamingElement(XName name, params object[] content) : this(name) { this.content = content; } /// <summary> /// Gets or sets the name of this streaming element. /// </summary> public XName Name { get { return name; } set { if (value == null) throw new ArgumentNullException(nameof(value)); name = value; } } /// <summary> /// Add content to an <see cref="XStreamingElement"/> /// </summary> /// <param name="content">Object containing content to add</param> public void Add(object content) { if (content != null) { List<object> list = this.content as List<object>; if (list == null) { list = new List<object>(); if (this.content != null) list.Add(this.content); this.content = list; } list.Add(content); } } /// <summary> /// Add content to an <see cref="XStreamingElement"/> /// </summary> /// <param name="content">array of objects containing content to add</param> public void Add(params object[] content) { Add((object)content); } /// <summary> /// Save the contents of an <see cref="XStreamingElement"/> to a <see cref="Stream"/> /// with formatting. /// </summary> /// <param name="stream"><see cref="Stream"/> to write to </param> public void Save(Stream stream) { Save(stream, SaveOptions.None); } /// <summary> /// Save the contents of an <see cref="XStreamingElement"/> to a <see cref="Stream"/>, /// optionally formatting. /// </summary> /// <param name="stream"><see cref="Stream"/> to write to </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(Stream stream, SaveOptions options) { XmlWriterSettings ws = XNode.GetXmlWriterSettings(options); using (XmlWriter w = XmlWriter.Create(stream, ws)) { Save(w); } } /// <summary> /// Save the contents of an <see cref="XStreamingElement"/> to a text writer /// with formatting. /// </summary> /// <param name="textWriter"><see cref="TextWriter"/> to write to </param> public void Save(TextWriter textWriter) { Save(textWriter, SaveOptions.None); } /// <summary> /// Save the contents of an <see cref="XStreamingElement"/> to a text writer /// optionally formatting. /// </summary> /// <param name="textWriter"><see cref="TextWriter"/> to write to </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(TextWriter textWriter, SaveOptions options) { XmlWriterSettings ws = XNode.GetXmlWriterSettings(options); using (XmlWriter w = XmlWriter.Create(textWriter, ws)) { Save(w); } } /// <summary> /// Save the contents of an <see cref="XStreamingElement"/> to an XML writer, not preserving whitespace /// </summary> /// <param name="writer"><see cref="XmlWriter"/> to write to </param> public void Save(XmlWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.WriteStartDocument(); WriteTo(writer); writer.WriteEndDocument(); } /// <summary> /// Save an <see cref="XStreamingElement"/> to a file with formatting. /// </summary> /// <param name="fileName">Name of file to write content to</param> public void Save(string fileName) { Save(fileName, SaveOptions.None); } /// <summary> /// Save an <see cref="XStreamingElement"/> to a file, optionally formatting. /// </summary> /// <param name="fileName">Name of file to write content to</param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(string fileName, SaveOptions options) { XmlWriterSettings ws = XNode.GetXmlWriterSettings(options); using (XmlWriter w = XmlWriter.Create(fileName, ws)) { Save(w); } } /// <summary> /// Get the XML content of an <see cref="XStreamingElement"/> as a /// formatted string. /// </summary> /// <returns>The XML text as a formatted string</returns> public override string ToString() { return GetXmlString(SaveOptions.None); } /// <summary> /// Gets the XML content of this streaming element as a string. /// </summary> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the content is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> /// <returns>An XML string</returns> public string ToString(SaveOptions options) { return GetXmlString(options); } /// <summary> /// Write this <see cref="XStreamingElement"/> to an <see cref="XmlWriter"/> /// </summary> /// <param name="writer"></param> public void WriteTo(XmlWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); new StreamingElementWriter(writer).WriteStreamingElement(this); } private string GetXmlString(SaveOptions o) { using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) { XmlWriterSettings ws = new XmlWriterSettings(); ws.OmitXmlDeclaration = true; if ((o & SaveOptions.DisableFormatting) == 0) ws.Indent = true; if ((o & SaveOptions.OmitDuplicateNamespaces) != 0) ws.NamespaceHandling |= NamespaceHandling.OmitDuplicates; using (XmlWriter w = XmlWriter.Create(sw, ws)) { WriteTo(w); } return sw.ToString(); } } } }
using System.Diagnostics; using System.Collections.Generic; namespace Cocos2D { public class CCParticleBatchNode : CCNode, ICCTextureProtocol { public const int kCCParticleDefaultCapacity = 500; /// <summary> /// The number of children that will trigger a binary search /// </summary> private const int kBinarySearchTrigger = 50; /// <summary> /// The number of children in the search range that will switch back to linear searching /// </summary> private const int kLinearSearchTrigger = 10; public readonly CCTextureAtlas TextureAtlas = new CCTextureAtlas(); private CCBlendFunc m_tBlendFunc; #region ICCTextureProtocol Members public CCTexture2D Texture { get { return TextureAtlas.Texture; } set { TextureAtlas.Texture = value; // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it if (value != null && !value.HasPremultipliedAlpha && m_tBlendFunc == CCBlendFunc.AlphaBlend) { m_tBlendFunc = CCBlendFunc.NonPremultiplied; } } } public CCBlendFunc BlendFunc { get { return m_tBlendFunc; } set { m_tBlendFunc = value; } } #endregion /* * creation with CCTexture2D */ public CCParticleBatchNode (CCTexture2D tex) : this(tex, kCCParticleDefaultCapacity) { } public CCParticleBatchNode (CCTexture2D tex, int capacity /* = kCCParticleDefaultCapacity*/) { InitWithTexture(tex, capacity); } /* * creation with File Image */ public CCParticleBatchNode (string imageFile, int capacity /* = kCCParticleDefaultCapacity*/) { InitWithFile(imageFile, capacity); } /* * init with CCTexture2D */ public bool InitWithTexture(CCTexture2D tex, int capacity) { TextureAtlas.InitWithTexture(tex, capacity); // no lazy alloc in this node m_pChildren = new CCRawList<CCNode>(capacity); m_tBlendFunc = CCBlendFunc.AlphaBlend; return true; } /* * init with FileImage */ public bool InitWithFile(string fileImage, int capacity) { CCTexture2D tex = CCTextureCache.SharedTextureCache.AddImage(fileImage); return InitWithTexture(tex, capacity); } // CCParticleBatchNode - composition // override visit. // Don't call visit on it's children public override void Visit() { // CAREFUL: // This visit is almost identical to CCNode#visit // with the exception that it doesn't call visit on it's children // // The alternative is to have a void CCSprite#visit, but // although this is less mantainable, is faster // if (!m_bVisible) { return; } //kmGLPushMatrix(); CCDrawManager.PushMatrix(); if (m_pGrid != null && m_pGrid.Active) { m_pGrid.BeforeDraw(); TransformAncestors(); } Transform(); Draw(); if (m_pGrid != null && m_pGrid.Active) { m_pGrid.AfterDraw(this); } //kmGLPopMatrix(); CCDrawManager.PopMatrix(); } // override addChild: public override void AddChild(CCNode child, int zOrder, int tag) { Debug.Assert(child != null, "Argument must be non-null"); Debug.Assert(child is CCParticleSystem, "CCParticleBatchNode only supports CCQuadParticleSystems as children"); var pChild = (CCParticleSystem) child; Debug.Assert(pChild.Texture.Name == TextureAtlas.Texture.Name, "CCParticleSystem is not using the same texture id"); // If this is the 1st children, then copy blending function if (m_pChildren.Count == 0) { BlendFunc = pChild.BlendFunc; } Debug.Assert(m_tBlendFunc.Source == pChild.BlendFunc.Source && m_tBlendFunc.Destination == pChild.BlendFunc.Destination, "Can't add a PaticleSystem that uses a differnt blending function"); //no lazy sorting, so don't call super addChild, call helper instead int pos = AddChildHelper(pChild, zOrder, tag); //get new atlasIndex int atlasIndex; if (pos != 0) { var p = (CCParticleSystem) m_pChildren[pos - 1]; atlasIndex = p.AtlasIndex + p.TotalParticles; } else { atlasIndex = 0; } InsertChild(pChild, atlasIndex, tag); // update quad info pChild.BatchNode = this; } // don't use lazy sorting, reordering the particle systems quads afterwards would be too complex // XXX research whether lazy sorting + freeing current quads and calloc a new block with size of capacity would be faster // XXX or possibly using vertexZ for reordering, that would be fastest // this helper is almost equivalent to CCNode's addChild, but doesn't make use of the lazy sorting private int AddChildHelper(CCParticleSystem child, int z, int aTag) { Debug.Assert(child != null, "Argument must be non-nil"); Debug.Assert(child.Parent == null, "child already added. It can't be added again"); if (m_pChildren == null) { m_pChildren = new CCRawList<CCNode>(4); } //don't use a lazy insert int pos = SearchNewPositionInChildrenForZ(z); m_pChildren.Insert(pos, child); child.Parent = this; child.Tag = aTag; child.m_nZOrder = z; if (m_bRunning) { child.OnEnter(); child.OnEnterTransitionDidFinish(); } return pos; } // Reorder will be done in this function, no "lazy" reorder to particles public override void ReorderChild(CCNode child, int zOrder) { Debug.Assert(child != null, "Child must be non-null"); Debug.Assert(child is CCParticleSystem, "CCParticleBatchNode only supports CCQuadParticleSystems as children"); Debug.Assert(m_pChildren.Contains(child), "Child doesn't belong to batch"); var pChild = (CCParticleSystem) (child); if (zOrder == child.ZOrder) { return; } // no reordering if only 1 child if (m_pChildren.Count > 1) { int newIndex = 0, oldIndex = 0; GetCurrentIndex(ref oldIndex, ref newIndex, pChild, zOrder); if (oldIndex != newIndex) { // reorder m_pChildren.array m_pChildren.RemoveAt(oldIndex); m_pChildren.Insert(newIndex, pChild); // save old altasIndex int oldAtlasIndex = pChild.AtlasIndex; // update atlas index UpdateAllAtlasIndexes(); // Find new AtlasIndex int newAtlasIndex = 0; for (int i = 0; i < m_pChildren.count; i++) { var node = (CCParticleSystem) m_pChildren.Elements[i]; if (node == pChild) { newAtlasIndex = pChild.AtlasIndex; break; } } // reorder textureAtlas quads TextureAtlas.MoveQuadsFromIndex(oldAtlasIndex, pChild.TotalParticles, newAtlasIndex); pChild.UpdateWithNoTime(); } } pChild.m_nZOrder = zOrder; } private void GetCurrentIndex(ref int oldIndex, ref int newIndex, CCNode child, int z) { bool foundCurrentIdx = false; bool foundNewIdx = false; int minusOne = 0; int count = m_pChildren.count; for (int i = 0; i < count; i++) { CCNode node = m_pChildren.Elements[i]; // new index if (node.m_nZOrder > z && ! foundNewIdx) { newIndex = i; foundNewIdx = true; if (foundCurrentIdx && foundNewIdx) { break; } } // current index if (child == node) { oldIndex = i; foundCurrentIdx = true; if (! foundNewIdx) { minusOne = -1; } if (foundCurrentIdx && foundNewIdx) { break; } } } if (! foundNewIdx) { newIndex = count; } newIndex += minusOne; } private int BinarySearchNewPositionInChildrenForZ(int start, int end, int z) { // Partition in half int count = end - start; if (count < kLinearSearchTrigger) { return (SearchNewPositionInChildrenForZ(start, end, z)); } int mid = (start + end) / 2; CCNode child = m_pChildren.Elements[mid]; if (child.m_nZOrder > z) { return BinarySearchNewPositionInChildrenForZ(start, mid, z); } return (BinarySearchNewPositionInChildrenForZ(mid, end, z)); } /// <summary> /// Do a binary search if the number of children is larger than a set limit. /// </summary> /// <param name="z"></param> /// <returns></returns> private int SearchNewPositionInChildrenForZ(int z) { int count = m_pChildren.count; if (count > kBinarySearchTrigger) { return (BinarySearchNewPositionInChildrenForZ(0, count, z)); } return (SearchNewPositionInChildrenForZ(0, count, z)); } /// <summary> /// Linearly search from start to end, exclusive of end, to find a position /// in [start,end) where the given z < z[index+1]. /// </summary> /// <param name="start">The start of the search range</param> /// <param name="end">The end of the search range</param> /// <param name="z">The z for comparison</param> /// <returns>The index on [start,end)</returns> private int SearchNewPositionInChildrenForZ(int start, int end, int z) { int count = m_pChildren.count; for (int i = 0; i < count; i++) { CCNode child = m_pChildren.Elements[i]; if (child.m_nZOrder > z) { return i; } } return count; } // override removeChild: public override void RemoveChild(CCNode child, bool cleanup) { // explicit nil handling if (child == null) { return; } Debug.Assert(child is CCParticleSystem, "CCParticleBatchNode only supports CCQuadParticleSystems as children"); Debug.Assert(m_pChildren.Contains(child), "CCParticleBatchNode doesn't contain the sprite. Can't remove it"); var pChild = (CCParticleSystem) child; base.RemoveChild(pChild, cleanup); // remove child helper TextureAtlas.RemoveQuadsAtIndex(pChild.AtlasIndex, pChild.TotalParticles); // after memmove of data, empty the quads at the end of array TextureAtlas.FillWithEmptyQuadsFromIndex(TextureAtlas.TotalQuads, pChild.TotalParticles); // paticle could be reused for self rendering pChild.BatchNode = null; UpdateAllAtlasIndexes(); } public void RemoveChildAtIndex(int index, bool doCleanup) { RemoveChild(m_pChildren[index], doCleanup); } public override void RemoveAllChildrenWithCleanup(bool doCleanup) { for (int i = 0; i < m_pChildren.count; i++) { ((CCParticleSystem) m_pChildren.Elements[i]).BatchNode = null; } base.RemoveAllChildrenWithCleanup(doCleanup); TextureAtlas.RemoveAllQuads(); } public override void Draw() { if (TextureAtlas.TotalQuads == 0) { return; } CCDrawManager.BlendFunc(m_tBlendFunc); TextureAtlas.DrawQuads(); } private void IncreaseAtlasCapacityTo(int quantity) { CCLog.Log("cocos2d: CCParticleBatchNode: resizing TextureAtlas capacity from [{0}] to [{1}].", TextureAtlas.Capacity, quantity); if (!TextureAtlas.ResizeCapacity(quantity)) { // serious problems CCLog.Log("cocos2d: WARNING: Not enough memory to resize the atlas"); Debug.Assert(false, "XXX: CCParticleBatchNode #increaseAtlasCapacity SHALL handle this assert"); } } //sets a 0'd quad into the quads array public void DisableParticle(int particleIndex) { CCV3F_C4B_T2F_Quad[] quads = TextureAtlas.m_pQuads.Elements; TextureAtlas.Dirty = true; quads[particleIndex].BottomRight.Vertices = CCVertex3F.Zero; quads[particleIndex].TopRight.Vertices = CCVertex3F.Zero; quads[particleIndex].TopLeft.Vertices = CCVertex3F.Zero; quads[particleIndex].BottomLeft.Vertices = CCVertex3F.Zero; } // CCParticleBatchNode - add / remove / reorder helper methods // add child helper private void InsertChild(CCParticleSystem pSystem, int index, int tag) { pSystem.AtlasIndex = index; if (TextureAtlas.TotalQuads + pSystem.TotalParticles > TextureAtlas.Capacity) { IncreaseAtlasCapacityTo(TextureAtlas.TotalQuads + pSystem.TotalParticles); // after a realloc empty quads of textureAtlas can be filled with gibberish (realloc doesn't perform calloc), insert empty quads to prevent it TextureAtlas.FillWithEmptyQuadsFromIndex(TextureAtlas.Capacity - pSystem.TotalParticles, pSystem.TotalParticles); } // make room for quads, not necessary for last child if (pSystem.AtlasIndex + pSystem.TotalParticles != TextureAtlas.TotalQuads) { TextureAtlas.MoveQuadsFromIndex(index, index + pSystem.TotalParticles); } // increase totalParticles here for new particles, update method of particlesystem will fill the quads TextureAtlas.IncreaseTotalQuadsWith(pSystem.TotalParticles); UpdateAllAtlasIndexes(); } //rebuild atlas indexes private void UpdateAllAtlasIndexes() { int index = 0; for (int i = 0; i < m_pChildren.count; i++) { var child = (CCParticleSystem) m_pChildren.Elements[i]; child.AtlasIndex = index; index += child.TotalParticles; } } // CCParticleBatchNode - CocosNodeTexture protocol private void UpdateBlendFunc() { if (!TextureAtlas.Texture.HasPremultipliedAlpha) { m_tBlendFunc = CCBlendFunc.NonPremultiplied; } } } }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.IO; namespace behaviac { /** indicating the action result for enter/exit */ [Flags] public enum EActionResult { EAR_none = 0, EAR_success = 1, EAR_failure = 2, EAR_all = EAR_success | EAR_failure }; public enum LogMode { ELM_tick, ELM_breaked, ELM_continue, ELM_jump, ELM_return, ELM_log }; public class LogManager : IDisposable { #region Singleton private static LogManager ms_instance = null; public LogManager() { Debug.Check(ms_instance == null); ms_instance = this; } public void Dispose() { ms_instance = null; } public static LogManager Instance { get { if (ms_instance == null) { LogManager instance = new LogManager(); Debug.Check(instance != null); Debug.Check(ms_instance != null); } return ms_instance; } } #endregion Singleton /** by default, the log file is _behaviac_$_.log in the current path. you can call this function to specify where to log */ public void SetLogFilePath(string logFilePath) { #if !BEHAVIAC_RELEASE m_logFilePath = logFilePath; #endif } //action public void Log(Agent pAgent, string btMsg, EActionResult actionResult, LogMode mode) { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing) { //BEHAVIAC_PROFILE("LogManager.Instance.LogAction"); if (!System.Object.ReferenceEquals(pAgent, null) && pAgent.IsMasked()) { if (!string.IsNullOrEmpty(btMsg)) { string agentClassName = pAgent.GetClassTypeName(); agentClassName = agentClassName.Replace(".", "::"); string agentName = agentClassName; agentName += "#"; agentName += pAgent.GetName(); string actionResultStr = ""; if (actionResult == EActionResult.EAR_success) { actionResultStr = "success"; } else if (actionResult == EActionResult.EAR_failure) { actionResultStr = "failure"; } else if (actionResult == EActionResult.EAR_all) { actionResultStr = "all"; } else { //although actionResult can be EAR_none or EAR_all, but, as this is the real result of an action //it can only be success or failure //when it is EAR_none, it is for update if (actionResult == behaviac.EActionResult.EAR_none && mode == behaviac.LogMode.ELM_tick) { actionResultStr = "running"; } else { actionResultStr = "none"; } } if (mode == LogMode.ELM_continue) { //[continue]Ship.Ship_1 ships\suicide.xml.BehaviorTreeTask[0]:enter [all/success/failure] [1] int count = Workspace.Instance.GetActionCount(btMsg); Debug.Check(count > 0); string buffer = string.Format("[continue]{0} {1} [{2}] [{3}]\n", agentName, btMsg, actionResultStr, count); Output(pAgent, buffer); } else if (mode == LogMode.ELM_breaked) { //[breaked]Ship.Ship_1 ships\suicide.xml.BehaviorTreeTask[0]:enter [all/success/failure] [1] int count = Workspace.Instance.GetActionCount(btMsg); Debug.Check(count > 0); string buffer = string.Format("[breaked]{0} {1} [{2}] [{3}]\n", agentName, btMsg, actionResultStr, count); Output(pAgent, buffer); } else if (mode == LogMode.ELM_tick) { //[tick]Ship.Ship_1 ships\suicide.xml.BehaviorTreeTask[0]:enter [all/success/failure] [1] //[tick]Ship.Ship_1 ships\suicide.xml.BehaviorTreeTask[0]:update [1] //[tick]Ship.Ship_1 ships\suicide.xml.Selector[1]:enter [all/success/failure] [1] //[tick]Ship.Ship_1 ships\suicide.xml.Selector[1]:update [1] int count = Workspace.Instance.UpdateActionCount(btMsg); if (actionResultStr != "running") { string buffer = string.Format("[tick]{0} {1} [{2}] [{3}]\n", agentName, btMsg, actionResultStr, count); Output(pAgent, buffer); } } else if (mode == LogMode.ELM_jump) { string buffer = string.Format("[jump]{0} {1}\n", agentName, btMsg); Output(pAgent, buffer); } else if (mode == LogMode.ELM_return) { string buffer = string.Format("[return]{0} {1}\n", agentName, btMsg); Output(pAgent, buffer); } else { Debug.Check(false); } } } } #endif } #if !BEHAVIAC_RELEASE private Dictionary<string, Dictionary<string, string>> _planningLoggedProperties = new Dictionary<string, Dictionary<string, string>>(); #endif public void PLanningClearCache() { #if !BEHAVIAC_RELEASE _planningLoggedProperties.Clear(); #endif } //property public void Log(Agent pAgent, string typeName, string varName, string value) { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing) { //BEHAVIAC_PROFILE("LogManager.Instance.LogVar"); if (!System.Object.ReferenceEquals(pAgent, null) && pAgent.IsMasked()) { string agentClassName = pAgent.GetClassTypeName(); agentClassName = agentClassName.Replace(".", "::"); string agentInstanceName = pAgent.GetName(); if (!string.IsNullOrEmpty(agentInstanceName)) { agentInstanceName = agentInstanceName.Replace(".", "::"); } //[property]WorldState.World WorldState.time.276854364 //[property]Ship.Ship_1 GameObject.HP.100 //[property]Ship.Ship_1 GameObject.age.0 //[property]Ship.Ship_1 GameObject.speed.0.000000 string buffer; buffer = string.Format("[property]{0}#{1} {2}->{3}\n", agentClassName, agentInstanceName, varName, value); bool bOutput = true; #if BEHAVIAC_USE_HTN if (pAgent.PlanningTop >= 0) { string agentFullName = string.Format("{0}#{1}", agentClassName, agentInstanceName); Dictionary<string, string> p = null; if (!_planningLoggedProperties.ContainsKey(agentFullName)) { p = new Dictionary<string, string>(); _planningLoggedProperties.Add(agentFullName, p); } else { p = _planningLoggedProperties[agentFullName]; } if (p.ContainsKey(varName)) { if (p[varName] == value) { bOutput = false; } else { p[varName] = value; } } else { p.Add(varName, value); } } #endif// if (bOutput) { Output(pAgent, buffer); } } } #endif } //profiler public void Log(Agent pAgent, string btMsg, long time) { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing) { if (Config.IsProfiling) { //BEHAVIAC_PROFILE("LogManager.Instance.LogProfiler"); if (!System.Object.ReferenceEquals(pAgent, null) && pAgent.IsMasked()) { //string agentClassName = pAgent.GetObjectTypeName(); //string agentInstanceName = pAgent.GetName(); BehaviorTreeTask bt = !System.Object.ReferenceEquals(pAgent, null) ? pAgent.CurrentBT : null; string btName; if (bt != null) { btName = bt.GetName(); } else { btName = "None"; } //[profiler]Ship.Ship_1 ships\suicide.xml.BehaviorTree[0] 0.031 string buffer; //buffer = FormatString("[profiler]%s.%s %s.%s %d\n", agentClassName, agentInstanceName, btName, btMsg, time); buffer = string.Format("[profiler]{0}.xml->{1} {2}\n", btName, btMsg, time); Output(pAgent, buffer); } } } #endif } //mode public void Log(LogMode mode, string filterString, string format, params object[] args) { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing) { //BEHAVIAC_PROFILE("LogManager.Instance.LogMode"); // make result string string buffer = string.Format(format, args); string filterStr = filterString; if (string.IsNullOrEmpty(filterString)) { filterStr = "empty"; } string target = ""; if (mode == LogMode.ELM_tick) { target = string.Format("[applog]{0}:{1}\n", filterStr, buffer); } else if (mode == LogMode.ELM_continue) { target = string.Format("[continue][applog]{0}:{1}\n", filterStr, buffer); } else if (mode == LogMode.ELM_breaked) { //[applog]door opened target = string.Format("[breaked][applog]{0}:{1}\n", filterStr, buffer); } else if (mode == LogMode.ELM_log) { target = string.Format("[log]{0}:{1}\n", filterStr, buffer); } else { Debug.Check(false); } Output(null, target); } #endif } public void Log(string format, params object[] args) { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing) { // make result string string buffer = string.Format(format, args); Output(null, buffer); } #endif } public void LogWorkspace(string format, params object[] args) { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing) { // make result string string buffer = string.Format(format, args); Output(null, buffer); } #endif } public void LogVarValue(Agent pAgent, string name, object value) { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing) { string valueStr = StringUtils.ToString(value); string typeName = ""; if (!Object.ReferenceEquals(value, null)) { typeName = Utils.GetNativeTypeName(value.GetType()); } else { typeName = "Agent"; } string full_name = name; if (!Object.ReferenceEquals(pAgent, null)) { CMemberBase pMember = pAgent.FindMember(name); if (pMember != null) { string classFullName = pMember.GetClassNameString().Replace(".", "::"); full_name = string.Format("{0}::{1}", classFullName, name); } } LogManager.Instance.Log(pAgent, typeName, full_name, valueStr); } #endif } public void Warning(string format, params object[] args) { Log(LogMode.ELM_log, "warning", format, args); } public void Error(string format, params object[] args) { Log(LogMode.ELM_log, "error", format, args); } public void Flush(Agent pAgent) { #if !BEHAVIAC_RELEASE if (Config.IsLogging) { System.IO.StreamWriter fp = GetFile(pAgent); if (fp != null) { lock (fp) { fp.Flush(); } } } #endif } public void Close() { #if !BEHAVIAC_RELEASE if (Config.IsLogging) { try { var e = m_logs.Values.GetEnumerator(); while (e.MoveNext()) { e.Current.Flush(); e.Current.Close(); } m_logs.Clear(); _planningLoggedProperties.Clear(); } catch { } } #endif } virtual protected System.IO.StreamWriter GetFile(Agent pAgent) { #if !BEHAVIAC_RELEASE if (Config.IsLogging) { System.IO.StreamWriter fp = null; //int agentId = pAgent.GetId(); int agentId = -1; if (!m_logs.ContainsKey(agentId)) { string buffer; if (string.IsNullOrEmpty(m_logFilePath)) { if (agentId == -1) { buffer = "_behaviac_$_.log"; } else { buffer = string.Format("Agent_$_{0:3}.log", agentId); } #if !BEHAVIAC_NOT_USE_UNITY if (UnityEngine.Application.platform != UnityEngine.RuntimePlatform.WindowsEditor && UnityEngine.Application.platform != UnityEngine.RuntimePlatform.WindowsPlayer) { buffer = Path.Combine(UnityEngine.Application.persistentDataPath, buffer); } #endif } else { buffer = m_logFilePath; } fp = new System.IO.StreamWriter(buffer); m_logs[agentId] = fp; } else { fp = m_logs[agentId]; } return fp; } #endif return null; } #if !BEHAVIAC_RELEASE private uint _msg_index = 0; #endif private void Output(Agent pAgent, string msg) { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing) { string txt = string.Format("[{0:00000000}]{1}", _msg_index++, msg); System.IO.StreamWriter fp = GetFile(pAgent); string szTime = DateTime.Now.ToString(); string buffer = string.Format("[{0}]{1}", szTime, txt); //socket sending before logging as logging is a 'slow' process if (Config.IsSocketing) { SocketUtils.SendText(txt); } if (Config.IsLogging) { //printf(buffer); if (fp != null) { lock (fp) { fp.Write(buffer); if (Config.IsLoggingFlush) { fp.Flush(); } } } } } #endif } #if !BEHAVIAC_RELEASE private Dictionary<int, System.IO.StreamWriter> m_logs = new Dictionary<int, StreamWriter>(); private string m_logFilePath; #endif }; }//namespace behaviac
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void BlendInt3285() { var test = new ImmBinaryOpTest__BlendInt3285(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__BlendInt3285 { private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__BlendInt3285 testClass) { var result = Avx2.Blend(_fld1, _fld2, 85); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static ImmBinaryOpTest__BlendInt3285() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public ImmBinaryOpTest__BlendInt3285() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Blend( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Blend( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Blend( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Blend( _clsVar1, _clsVar2, 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.Blend(left, right, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__BlendInt3285(); var result = Avx2.Blend(test._fld1, test._fld2, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Blend(_fld1, _fld2, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Blend(test._fld1, test._fld2, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (((85 & (1 << 0)) == 0) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (((85 & (1 << i)) == 0) ? left[i] : right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<Int32>(Vector256<Int32>.85, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * 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.Diagnostics; using System.Net; using System.IO; using System.Net.Sockets; using Xunit; using Xunit.Abstractions; namespace Apache.Geode.Client.IntegrationTests { public class Cluster : IDisposable { private int locatorCount_; private int serverCount_; private bool started_; private List<Locator> locators_; private string name_; internal int jmxManagerPort = Framework.FreeTcpPort(); internal string keyStore_ = Config.SslServerKeyPath + "/server_keystore_chained.jks"; internal string keyStorePassword_ = "apachegeode"; internal string trustStore_ = Config.SslServerKeyPath + "/server_truststore_chained_root.jks"; internal string trustStorePassword_ = "apachegeode"; public Gfsh Gfsh { get; private set; } public bool UseSSL { get; set; } internal PoolFactory ApplyLocators(PoolFactory poolFactory) { foreach (var locator in locators_) { poolFactory.AddLocator(locator.Address.address, locator.Address.port); } return poolFactory; } public Cluster(ITestOutputHelper output, string name, int locatorCount, int serverCount) { started_ = false; Gfsh = new GfshExecute(output); UseSSL = false; name_ = name; locatorCount_ = locatorCount; serverCount_ = serverCount; locators_ = new List<Locator>(); } private bool StartLocators() { var success = true; for (var i = 0; i < locatorCount_; i++) { var locator = new Locator(this, new List<Locator>(), name_ + "/locator/" + i.ToString()); locators_.Add(locator); success = (locator.Start() == 0); } return success; } private bool StartServers() { var success = true; for (var i = 0; i < serverCount_; i++) { var server = new Server(this, locators_, name_ + "/server/" + i.ToString()); var localResult = server.Start(); if (localResult != 0) { success = false; } } return success; } private void RemoveClusterDirectory() { if (Directory.Exists(name_)) { Directory.Delete(name_, true); } } public bool Start() { if (!started_) { RemoveClusterDirectory(); var locatorSuccess = StartLocators(); var serverSuccess = StartServers(); started_ = (locatorSuccess && serverSuccess); } return (started_); } public void Dispose() { if (started_) { this.Gfsh .shutdown() .withIncludeLocators(true) .execute(); } } public Cache CreateCache(IDictionary<string, string> properties) { var cacheFactory = new CacheFactory(); cacheFactory .Set("log-level", "none") .Set("statistic-sampling-enabled", "false"); foreach (var pair in properties) { cacheFactory.Set(pair.Key, pair.Value); } var cache = cacheFactory.Create(); ApplyLocators(cache.GetPoolFactory()).Create("default"); return cache; } public Cache CreateCache() { return CreateCache(new Dictionary<string, string>()); } } public struct Address { public string address; public int port; } public class Locator { private Cluster cluster_; private string name_; private List<Locator> locators_; private bool started_; public Locator(Cluster cluster, List<Locator> locators, string name) { cluster_ = cluster; locators_ = locators; name_ = name; var address = new Address(); address.address = "localhost"; address.port = Framework.FreeTcpPort(); Address = address; } public Address Address { get; private set; } public int Start() { var result = -1; if (!started_) { var locator = cluster_.Gfsh .start() .locator() .withDir(name_) .withName(name_.Replace('/', '_')) .withBindAddress(Address.address) .withPort(Address.port) .withMaxHeap("256m") .withJmxManagerPort(cluster_.jmxManagerPort) .withJmxManagerStart(true) .withHttpServicePort(0); if (cluster_.UseSSL) { locator .withConnect(false) .withSslEnableComponents("all") .withSslKeyStore(cluster_.keyStore_) .withSslKeyStorePassword(cluster_.keyStorePassword_) .withSslTrustStore(cluster_.trustStore_) .withSslTrustStorePassword(cluster_.trustStorePassword_); } result = locator.execute(); if (cluster_.UseSSL) { cluster_.Gfsh.connect() .withJmxManager(Address.address, cluster_.jmxManagerPort) .withUseSsl(true) .withKeyStore(cluster_.keyStore_) .withKeyStorePassword(cluster_.keyStorePassword_) .withTrustStore(cluster_.trustStore_) .withTrustStorePassword(cluster_.trustStorePassword_) .execute(); } started_ = true; } return result; } public int Stop() { var result = cluster_.Gfsh .stop() .locator() .withDir(name_) .execute(); started_ = false; return result; } } public class Server { private Cluster cluster_; private string name_; private List<Locator> locators_; private bool started_; public Server(Cluster cluster, List<Locator> locators, string name) { cluster_ = cluster; locators_ = locators; name_ = name; var address = new Address(); address.address = "localhost"; address.port = 0; Address = address; } public Address Address { get; private set; } public int Start() { var result = -1; if (!started_) { var server = cluster_.Gfsh .start() .server() .withDir(name_) .withName(name_.Replace('/', '_')) .withBindAddress(Address.address) .withPort(Address.port) .withMaxHeap("1g"); if (cluster_.UseSSL) { server .withSslEnableComponents("all") .withSslKeyStore(cluster_.keyStore_) .withSslKeyStorePassword(cluster_.keyStorePassword_) .withSslTrustStore(cluster_.trustStore_) .withSslTrustStorePassword(cluster_.trustStorePassword_); } result = server.execute(); started_ = true; } return result; } public int Stop() { var result = cluster_.Gfsh .stop() .server() .withDir(name_) .execute(); started_ = false; 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 Xunit; using System; using System.Linq; using System.Reflection; using System.Collections.Generic; #pragma warning disable 0414 namespace System.Reflection.Tests { public class FieldInfoPropertyTests { //Verify Static int FieldType [Fact] public void TestFieldType_intstatic() { String fieldname = "intFieldStatic"; FieldInfo fi = getField(fieldname); FieldInfoPropertyTests myInstance = new FieldInfoPropertyTests(); Assert.NotNull(fi); Assert.True(fi.Name.Equals(fieldname)); Assert.True(fi.IsStatic); } //Verify Non Static int FieldType [Fact] public void TestFieldType_intnonstatic() { String fieldname = "intFieldNonStatic"; FieldInfo fi = getField(fieldname); FieldInfoPropertyTests myInstance = new FieldInfoPropertyTests(); Assert.NotNull(fi); Assert.True(fi.Name.Equals(fieldname)); Assert.False(fi.IsStatic); } //Verify Static String FieldType [Fact] public void TestFieldType_strstatic() { String fieldname = "static_strField"; FieldInfo fi = getField(fieldname); FieldInfoPropertyTests myInstance = new FieldInfoPropertyTests(); Assert.NotNull(fi); Assert.True(fi.Name.Equals(fieldname)); Assert.True(fi.IsStatic); } //Verify Non Static String FieldType [Fact] public void TestFieldType_strnonstatic() { String fieldname = "nonstatic_strField"; FieldInfo fi = getField(fieldname); FieldInfoPropertyTests myInstance = new FieldInfoPropertyTests(); Assert.NotNull(fi); Assert.True(fi.Name.Equals(fieldname)); Assert.False(fi.IsStatic); } //Verify Public String FieldType using IsPublic [Fact] public void TestIsPublic1() { String fieldname = "nonstatic_strField"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.IsPublic); } //Verify Public int FieldType using IsPublic [Fact] public void TestIsPublic2() { String fieldname = "intFieldStatic"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.IsPublic); } //Verify Private int FieldType using IsPublic [Fact] public void TestIsPublic3() { String fieldname = "_privateInt"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsPublic); } //Verify Private String FieldType using IsPublic [Fact] public void TestIsPublic4() { String fieldname = "_privateStr"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsPublic); } //Verify Private int FieldType using IsPrivate [Fact] public void TestIsPrivate1() { String fieldname = "_privateInt"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.IsPrivate); } //Verify Private String FieldType using IsPrivate [Fact] public void TestIsPrivate2() { String fieldname = "_privateStr"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.IsPrivate); } //Verify Public String FieldType using IsPrivate [Fact] public void TestIsPrivate3() { String fieldname = "nonstatic_strField"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsPrivate); } //Verify Public int FieldType using IsPrivate [Fact] public void TestIsPrivate4() { String fieldname = "intFieldStatic"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsPrivate); } //Verify Private int FieldType using IsStatic [Fact] public void TestIsStatic1() { String fieldname = "_privateInt"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsStatic); } //Verify public static int FieldType using IsStatic [Fact] public void TestIsStatic2() { String fieldname = "intFieldStatic"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.IsStatic); } //Verify IsAssembly for static object [Fact] public void TestIsAssembly1() { String fieldname = "s_field_Assembly1"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsAssembly); } //Verify IsAssembly for private static object [Fact] public void TestIsAssembly2() { String fieldname = "s_field_Assembly2"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsAssembly); } //Verify IsAssembly for protected static object [Fact] public void TestIsAssembly3() { String fieldname = "Field_Assembly3"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsAssembly); } //Verify IsAssembly for public static object [Fact] public void TestIsAssembly4() { String fieldname = "Field_Assembly4"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsAssembly); } //Verify IsAssembly for internal static object [Fact] public void TestIsAssembly5() { String fieldname = "Field_Assembly5"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.IsAssembly); } //Verify IsFamily for static object [Fact] public void TestIsFamily1() { String fieldname = "s_field_Assembly1"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamily); } //Verify IsFamily for private static object [Fact] public void TestIsFamily2() { String fieldname = "s_field_Assembly2"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamily); } //Verify IsFamily for protected static object [Fact] public void TestIsFamily3() { String fieldname = "Field_Assembly3"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.IsFamily); } //Verify IsFamily for public static object [Fact] public void TestIsFamily4() { String fieldname = "Field_Assembly4"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamily); } //Verify IsFamily for internal static object [Fact] public void TestIsFamily5() { String fieldname = "Field_Assembly5"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamily); } //Verify IsFamilyAndAssembly for s_field_FamilyAndAssembly1 [Fact] public void TestIsFamilyAndAssembly1() { String fieldname = "s_field_FamilyAndAssembly1"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamilyAndAssembly); } //Verify IsFamilyAndAssembly for s_field_FamilyAndAssembly2 [Fact] public void TestIsFamilyAndAssembly2() { String fieldname = "s_field_FamilyAndAssembly2"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamilyAndAssembly); } //Verify IsFamilyAndAssembly for Field_FamilyAndAssembly3 [Fact] public void TestIsFamilyAndAssembly3() { String fieldname = "Field_FamilyAndAssembly3"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamilyAndAssembly); } //Verify IsFamilyAndAssembly for Field_FamilyAndAssembly4 [Fact] public void TestIsFamilyAndAssembly4() { String fieldname = "Field_FamilyAndAssembly4"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamilyAndAssembly); } //Verify IsFamilyAndAssembly for Field_FamilyAndAssembly5 [Fact] public void TestIsFamilyAndAssembly5() { String fieldname = "Field_FamilyAndAssembly5"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamilyAndAssembly); } //Verify IsFamilyOrAssembly for s_field_FamilyOrAssembly1 [Fact] public void TestIsFamilyOrAssembly1() { String fieldname = "s_field_FamilyOrAssembly1"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamilyOrAssembly); } //Verify IsFamilyOrAssembly for s_field_FamilyOrAssembly2 [Fact] public void TestIsFamilyOrAssembly2() { String fieldname = "s_field_FamilyOrAssembly2"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamilyOrAssembly); } //Verify IsFamilyOrAssembly for Field_FamilyOrAssembly3 [Fact] public void TestIsFamilyOrAssembly3() { String fieldname = "Field_FamilyOrAssembly3"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamilyOrAssembly); } //Verify IsFamilyOrAssembly for Field_FamilyOrAssembly4 [Fact] public void TestIsFamilyOrAssembly4() { String fieldname = "Field_FamilyOrAssembly4"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamilyOrAssembly); } //Verify IsFamilyOrAssembly for Field_FamilyOrAssembly5 [Fact] public void TestIsFamilyOrAssembly5() { String fieldname = "Field_FamilyOrAssembly5"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsFamilyOrAssembly); } //Verify IsInitOnly for readonly field [Fact] public void TestIsInitOnly1() { String fieldname = "rointField"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.IsInitOnly); } //Verify IsInitOnly for non- readonly field [Fact] public void TestIsInitOnly2() { String fieldname = "intFieldNonStatic"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsInitOnly); } //Verify IsLiteral for literal fields like constant [Fact] public void TestIsLiteral1() { String fieldname = "constIntField"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.IsLiteral); } //Verify IsLiteral for non constant fields [Fact] public void TestIsLiteral2() { String fieldname = "intFieldNonStatic"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsLiteral); } //Verify FieldType for int field [Fact] public void TestFieldType1() { String fieldname = "intFieldNonStatic"; FieldInfo fi = getField(fieldname); string typeStr = "System.Int32"; Assert.NotNull(fi); Assert.True(fi.FieldType.ToString().Equals(typeStr)); } //Verify FieldType for string field [Fact] public void TestFieldType2() { String fieldname = "nonstatic_strField"; FieldInfo fi = getField(fieldname); string typeStr = "System.String"; Assert.NotNull(fi); Assert.True(fi.FieldType.ToString().Equals(typeStr), "Failed!! Expected FieldType to return " + typeStr); } //Verify FieldType for Object field [Fact] public void TestFieldType3() { String fieldname = "s_field_Assembly1"; FieldInfo fi = getField(fieldname); string typeStr = "System.Object"; Assert.NotNull(fi); Assert.True(fi.FieldType.ToString().Equals(typeStr), "Failed!! Expected FieldType to return " + typeStr); } //Verify FieldAttributes [Fact] public void TestFieldAttribute1() { String fieldname = "intFieldNonStatic"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.Attributes.Equals(FieldAttributes.Public), "Failed!! Expected Field Attribute to be of type Public"); } //Verify FieldAttributes [Fact] public void TestFieldAttribute2() { String fieldname = "intFieldStatic"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.Attributes.Equals(FieldAttributes.Public | FieldAttributes.Static), "Failed!! Expected Field Attribute to be of type Public and static"); } //Verify FieldAttributes [Fact] public void TestFieldAttribute3() { String fieldname = "_privateInt"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.Attributes.Equals(FieldAttributes.Private), "Failed!! Expected Field Attribute to be of type Private"); } //Verify FieldAttributes [Fact] public void TestFieldAttribute4() { String fieldname = "rointField"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.True(fi.Attributes.Equals(FieldAttributes.Public | FieldAttributes.InitOnly), "Failed!! Expected Field Attribute to be of type InitOnly"); } //Verify IsSpecialName for FieldInfo [Fact] public void TestIsSpecialName() { String fieldname = "intFieldNonStatic"; FieldInfo fi = getField(fieldname); Assert.NotNull(fi); Assert.False(fi.IsSpecialName, "Failed: FieldInfo IsSpecialName returned True for field: " + fieldname); } private static FieldInfo getField(string field) { Type t = typeof(FieldInfoPropertyTests); TypeInfo ti = t.GetTypeInfo(); FieldInfo fi = null; fi = ti.DeclaredFields.Single(x => x.Name == field); return fi; } //Fields for Reflection Metadata public static int intFieldStatic = 100; // Field for Reflection public int intFieldNonStatic = 101; //Field for Reflection public static string static_strField = "Static string field"; // Field for Reflection public string nonstatic_strField = "NonStatic string field"; // Field for Reflection private int _privateInt = 1; // Field for Reflection private string _privateStr = "_privateStr"; // Field for Reflection private static Object s_field_Assembly1 = null; // without keyword private static Object s_field_Assembly2 = null; // with private keyword protected static Object Field_Assembly3 = null; // with protected keyword public static Object Field_Assembly4 = null; // with public keyword internal static Object Field_Assembly5 = null; // with internal keyword private static Object s_field_FamilyAndAssembly1 = null; // without keyword private static Object s_field_FamilyAndAssembly2 = null; // with private keyword protected static Object Field_FamilyAndAssembly3 = null; // with protected keyword public static Object Field_FamilyAndAssembly4 = null; // with public keyword internal static Object Field_FamilyAndAssembly5 = null; // with internal keyword private static Object s_field_FamilyOrAssembly1 = null; // without keyword private static Object s_field_FamilyOrAssembly2 = null; // with private keyword protected static Object Field_FamilyOrAssembly3 = null; // with protected keyword public static Object Field_FamilyOrAssembly4 = null; // with public keyword internal static Object Field_FamilyOrAssembly5 = null; // with internal keyword public readonly int rointField = 1; public const int constIntField = 1222; } }
using System; using Franson.BlueTools; using System.Windows.Forms; namespace NetworkScanner { /// <summary> /// Summary description for NetworkEnumerator. /// </summary> public class NetworkScanner : System.Windows.Forms.Form { private System.Windows.Forms.TreeView deviceList; private System.Windows.Forms.Label deviceListLabel; private System.Windows.Forms.StatusBar statusBar; private Network[] networks; private System.Windows.Forms.CheckBox autoDiscover; private System.Windows.Forms.Button discover; private Manager manager; public NetworkScanner() { InitializeComponent(); try { // Fetch the bluetooth manager instance manager = Manager.GetManager(); } catch (Exception exc) { MessageBox.Show(exc.Message); return; } try { // You can get a valid evaluation key at // http://franson.com/bluetools/ // That key will be valid for 14 days. Just cut and paste that key into the statement below. // To get a key that do not expire you need to purchase a license Franson.BlueTools.License license = new Franson.BlueTools.License(); license.LicenseKey = "WoK6HM24B9ECLOPQSXVZPixRDRfuIYHYWrT9"; // Fetch all network instances networks = manager.Networks; } catch (BlueToolsException exc) { MessageBox.Show(exc.Message); return; } // Set the parent of the manager to this control. This is necessary if // we want to invoke methods on controls from within the bluetools // event handlers. manager.Parent = this; // Attach event listeners to all network instances foreach(Network network in networks) { // This allows us to get notified whenever a device has been discovered network.DeviceDiscovered += new BlueToolsEventHandler(network_DeviceDiscovered); // This allows us to get notified whenever a device has been lost network.DeviceLost += new BlueToolsEventHandler(network_DeviceLost); // This allows us get get notified whenever a device discovery // has completed. This will happen event if no new devices have // been discovered; it will deliver the current list of devices // available on the network. This can be used e.g. to update the // names of the devices in the list. network.DeviceDiscoveryCompleted += new BlueToolsEventHandler(network_DeviceDiscoveryCompleted); network.DeviceDiscoveryStarted += new BlueToolsEventHandler(network_DeviceDiscoveryStarted); // This allows us to get notified whenever an error occures in // the network. network.Error += new BlueToolsEventHandler(network_Error); } Closing += new System.ComponentModel.CancelEventHandler(NetworkEnumerator_Closing); } private void InitializeComponent() { this.discover = new System.Windows.Forms.Button(); this.deviceList = new System.Windows.Forms.TreeView(); this.deviceListLabel = new System.Windows.Forms.Label(); this.statusBar = new System.Windows.Forms.StatusBar(); this.autoDiscover = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // discover // this.discover.Location = new System.Drawing.Point(8, 280); this.discover.Name = "discover"; this.discover.TabIndex = 0; this.discover.Text = "Discover"; this.discover.Click += new System.EventHandler(this.discover_Click); // // deviceList // this.deviceList.ImageIndex = -1; this.deviceList.Location = new System.Drawing.Point(8, 24); this.deviceList.Name = "deviceList"; this.deviceList.SelectedImageIndex = -1; this.deviceList.Size = new System.Drawing.Size(392, 248); this.deviceList.TabIndex = 2; // // deviceListLabel // this.deviceListLabel.Location = new System.Drawing.Point(8, 8); this.deviceListLabel.Name = "deviceListLabel"; this.deviceListLabel.Size = new System.Drawing.Size(112, 16); this.deviceListLabel.TabIndex = 3; this.deviceListLabel.Text = "Devices in proximity"; // // statusBar // this.statusBar.Location = new System.Drawing.Point(0, 304); this.statusBar.Name = "statusBar"; this.statusBar.Size = new System.Drawing.Size(408, 22); this.statusBar.TabIndex = 4; // // autoDiscover // this.autoDiscover.Location = new System.Drawing.Point(88, 280); this.autoDiscover.Name = "autoDiscover"; this.autoDiscover.Size = new System.Drawing.Size(120, 24); this.autoDiscover.TabIndex = 5; this.autoDiscover.Text = "Automic Discovery"; this.autoDiscover.CheckedChanged += new System.EventHandler(this.autoDiscover_CheckedChanged); // // NetworkScanner // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(408, 326); this.Controls.Add(this.autoDiscover); this.Controls.Add(this.statusBar); this.Controls.Add(this.deviceListLabel); this.Controls.Add(this.deviceList); this.Controls.Add(this.discover); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "NetworkScanner"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Text = "Network Scanner"; this.Load += new System.EventHandler(this.NetworkScanner_Load); this.ResumeLayout(false); } private void network_DeviceLost(object sender, BlueToolsEventArgs eventArgs) { // In a device lost event, the sender is always a Network and the event // type is always a DiscoveryEventArgs. The device that was lost is // attached to the DiscoveryEventArgs through the Discovery property. RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery; statusBar.Text = "Lost device " + device.Name; // Remove the device from the device and service list // foreach(TreeNode node in deviceList.Nodes) { if(node.Tag.Equals(device.Address.ToString())) { deviceList.Nodes.Remove(node); break; } } // Remove the event handler from the device device.ServiceDiscovered -= new BlueToolsEventHandler(device_ServiceDiscovered); } private void network_DeviceDiscovered(object sender, BlueToolsEventArgs eventArgs) { // In a device discovered event, the sender is always a Network, and the event // is always a DiscoveryEventArgs. The device that was discovered is attached // to the DiscoveryEventArgs through the Discovery property. RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery; statusBar.Text = "Discovered device " + device.Name; // Check if the device is already present in the list // bool found = false; foreach(TreeNode node in deviceList.Nodes) { if(node.Tag.Equals(device.Address.ToString())) { found = true; break; } } if(!found) { // Add the device to the list // TreeNode node = new TreeNode(device.Name.Length == 0 ? device.Address.ToString() : device.Name); node.Tag = device.Address.ToString(); deviceList.Nodes.Add(node); // Add a service discovery listener so we can discover the services // of the device. device.ServiceDiscovered += new BlueToolsEventHandler(device_ServiceDiscovered); // Discover the services of the device. Note that this will generally // not execute immediatelly but instead wait until the device and // any enqueued service discovery has completed. The reason for this // is that the bluetooth stacks generally can't handle several // discoveries. device.DiscoverServicesAsync(ServiceType.RFCOMM); } } private void NetworkEnumerator_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Dispose(); } private void device_ServiceDiscovered(object sender, BlueToolsEventArgs eventArgs) { // In a service discovered event, the sender is always a RemoteDevice instance, // and the event is always a DiscoveryEventArgs. The discovered service is // attached to the DiscoveryEventArgs through the Discovery property. RemoteDevice device = (RemoteDevice)sender; RemoteService service = (RemoteService)((DiscoveryEventArgs)eventArgs).Discovery; // Add the service to the list // foreach(TreeNode node in deviceList.Nodes) { if(node.Tag.Equals(device.Address.ToString())) { TreeNode serviceNode = new TreeNode(service.Name); serviceNode.Tag = service.Address.ToString(); node.Nodes.Add(serviceNode); node.Expand(); } } statusBar.Text = "Discovered service " + service.Name + " of device " + device.Name; } private void network_DeviceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs) { Device[] devices = (Device[])((DiscoveryEventArgs)eventArgs).Discovery; // Update each device in the device list. Some bluetooth stack doesn't // immediatelly return the name of the device, as that is more complicated // than delivering the address only. Therefore, the name might not // be present at first. We compensate for that here. foreach(Device device in devices) { foreach(TreeNode deviceNode in deviceList.Nodes) { if(deviceNode.Tag.Equals(device.Address.ToString())) { deviceNode.Text = device.Name; break; } } } statusBar.Text = "Device discovery completed"; discover.Enabled = true; } private void network_DeviceDiscoveryStarted(object sender, BlueToolsEventArgs eventArgs) { statusBar.Text = "Looking for devices"; } private void ShowError(Exception exc) { System.Windows.Forms.MessageBox.Show(this, exc.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } private void network_Error(object sender, BlueToolsEventArgs eventArgs) { ShowError(((ErrorEventArgs)eventArgs).Exception); } protected override void Dispose(bool disposing) { manager.Dispose(); base.Dispose (disposing); if(disposing) { } } [STAThread] public static void Main(String[] args) { Application.Run(new NetworkScanner()); } private void autoDiscover_CheckedChanged(object sender, System.EventArgs e) { try { foreach(Network network in networks) { // Enable auto discovery on the Network instance. This should // always be used with caution, as the bluetooth stack might // not handle communication properly if it is always busy // with discovering devices. network.AutoDiscovery = autoDiscover.Checked; // Run discoveries as quickly as possible network.AutoRefreshInterval = 0; } discover.Enabled = !autoDiscover.Checked; } catch (Exception exc) { ShowError(exc); } } private void discover_Click(object sender, System.EventArgs e) { try { discover.Enabled = false; foreach(Network network in networks) { network.DiscoverDevicesAsync(); } } catch (Exception exc) { ShowError(exc); } } private void NetworkScanner_Load(object sender, System.EventArgs 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 System.Diagnostics; namespace System.Security.Cryptography { /// <summary> /// Provides support for computing a hash or HMAC value incrementally across several segments. /// </summary> public sealed class IncrementalHash : IDisposable { private const int NTE_BAD_ALGID = unchecked((int)0x80090008); private static readonly byte[] s_empty = new byte[0]; private readonly HashAlgorithmName _algorithmName; private HashAlgorithm _hash; private bool _disposed; private bool _resetPending; private IncrementalHash(HashAlgorithmName name, HashAlgorithm hash) { Debug.Assert(name != null); Debug.Assert(!string.IsNullOrEmpty(name.Name)); Debug.Assert(hash != null); _algorithmName = name; _hash = hash; } /// <summary> /// Get the name of the algorithm being performed. /// </summary> public HashAlgorithmName AlgorithmName { get { return _algorithmName; } } /// <summary> /// Append the entire contents of <paramref name="data"/> to the data already processed in the hash or HMAC. /// </summary> /// <param name="data">The data to process.</param> /// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception> /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception> public void AppendData(byte[] data) { if (data == null) throw new ArgumentNullException(nameof(data)); AppendData(data, 0, data.Length); } /// <summary> /// Append <paramref name="count"/> bytes of <paramref name="data"/>, starting at <paramref name="offset"/>, /// to the data already processed in the hash or HMAC. /// </summary> /// <param name="data">The data to process.</param> /// <param name="offset">The offset into the byte array from which to begin using data.</param> /// <param name="count">The number of bytes in the array to use as data.</param> /// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="offset"/> is out of range. This parameter requires a non-negative number. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is out of range. This parameter requires a non-negative number less than /// the <see cref="Array.Length"/> value of <paramref name="data"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="count"/> is greater than /// <paramref name="data"/>.<see cref="Array.Length"/> - <paramref name="offset"/>. /// </exception> /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception> public void AppendData(byte[] data, int offset, int count) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0 || (count > data.Length)) throw new ArgumentOutOfRangeException(nameof(count)); if ((data.Length - count) < offset) throw new ArgumentException(SR.Argument_InvalidOffLen); if (_disposed) throw new ObjectDisposedException(typeof(IncrementalHash).Name); Debug.Assert(_hash != null); if (_resetPending) { _hash.Initialize(); _resetPending = false; } _hash.TransformBlock(data, offset, count, null, 0); } /// <summary> /// Retrieve the hash or HMAC for the data accumulated from prior calls to /// <see cref="AppendData(byte[])"/>, and return to the state the object /// was in at construction. /// </summary> /// <returns>The computed hash or HMAC.</returns> /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception> public byte[] GetHashAndReset() { if (_disposed) throw new ObjectDisposedException(typeof(IncrementalHash).Name); Debug.Assert(_hash != null); if (_resetPending) { // No point in setting _resetPending to false, we're about to set it to true. _hash.Initialize(); } _hash.TransformFinalBlock(s_empty, 0, 0); byte[] hashValue = _hash.Hash; _resetPending = true; return hashValue; } /// <summary> /// Release all resources used by the current instance of the /// <see cref="IncrementalHash"/> class. /// </summary> public void Dispose() { _disposed = true; if (_hash != null) { _hash.Dispose(); _hash = null; } } /// <summary> /// Create an <see cref="IncrementalHash"/> for the algorithm specified by <paramref name="hashAlgorithm"/>. /// </summary> /// <param name="hashAlgorithm">The name of the hash algorithm to perform.</param> /// <returns> /// An <see cref="IncrementalHash"/> instance ready to compute the hash algorithm specified /// by <paramref name="hashAlgorithm"/>. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="hashAlgorithm"/>.<see cref="HashAlgorithmName.Name"/> is <c>null</c>, or /// the empty string. /// </exception> /// <exception cref="CryptographicException"><paramref name="hashAlgorithm"/> is not a known hash algorithm.</exception> public static IncrementalHash CreateHash(HashAlgorithmName hashAlgorithm) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); return new IncrementalHash(hashAlgorithm, GetHashAlgorithm(hashAlgorithm)); } /// <summary> /// Create an <see cref="IncrementalHash"/> for the Hash-based Message Authentication Code (HMAC) /// algorithm utilizing the hash algorithm specified by <paramref name="hashAlgorithm"/>, and a /// key specified by <paramref name="key"/>. /// </summary> /// <param name="hashAlgorithm">The name of the hash algorithm to perform within the HMAC.</param> /// <param name="key"> /// The secret key for the HMAC. The key can be any length, but a key longer than the output size /// of the hash algorithm specified by <paramref name="hashAlgorithm"/> will be hashed (using the /// algorithm specified by <paramref name="hashAlgorithm"/>) to derive a correctly-sized key. Therefore, /// the recommended size of the secret key is the output size of the hash specified by /// <paramref name="hashAlgorithm"/>. /// </param> /// <returns> /// An <see cref="IncrementalHash"/> instance ready to compute the hash algorithm specified /// by <paramref name="hashAlgorithm"/>. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="hashAlgorithm"/>.<see cref="HashAlgorithmName.Name"/> is <c>null</c>, or /// the empty string. /// </exception> /// <exception cref="CryptographicException"><paramref name="hashAlgorithm"/> is not a known hash algorithm.</exception> public static IncrementalHash CreateHMAC(HashAlgorithmName hashAlgorithm, byte[] key) { if (key == null) throw new ArgumentNullException(nameof(key)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); return new IncrementalHash(hashAlgorithm, GetHMAC(hashAlgorithm, key)); } private static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithm) { if (hashAlgorithm == HashAlgorithmName.MD5) return new MD5CryptoServiceProvider(); if (hashAlgorithm == HashAlgorithmName.SHA1) return new SHA1CryptoServiceProvider(); if (hashAlgorithm == HashAlgorithmName.SHA256) return new SHA256CryptoServiceProvider(); if (hashAlgorithm == HashAlgorithmName.SHA384) return new SHA384CryptoServiceProvider(); if (hashAlgorithm == HashAlgorithmName.SHA512) return new SHA512CryptoServiceProvider(); throw new CryptographicException(NTE_BAD_ALGID); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351")] // We are providing the implementations for these algorithms private static HashAlgorithm GetHMAC(HashAlgorithmName hashAlgorithm, byte[] key) { if (hashAlgorithm == HashAlgorithmName.MD5) return new HMACMD5(key); if (hashAlgorithm == HashAlgorithmName.SHA1) return new HMACSHA1(key); if (hashAlgorithm == HashAlgorithmName.SHA256) return new HMACSHA256(key); if (hashAlgorithm == HashAlgorithmName.SHA384) return new HMACSHA384(key); if (hashAlgorithm == HashAlgorithmName.SHA512) return new HMACSHA512(key); throw new CryptographicException(NTE_BAD_ALGID); } } }
#region Using Directives using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; #endregion Using Directives namespace ScintillaNET { /// <summary> /// Used to display CallTips and Manages CallTip settings. /// </summary> /// <remarks> /// CallTips are a special form of ToolTip that can be displayed specifically for /// a document position. It also display a list of method overloads and /// highlighight a portion of the message. This is useful in IDE scenarios. /// </remarks> [TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))] public class CallTip : TopLevelHelper { #region Fields public const char UpArrow = '\u0001'; public const char DownArrow = '\u0002'; private int _lastPos = -1; private OverloadList _overloadList = null; private string _message = null; private int _highlightStart = -1; private int _highlightEnd = -1; #endregion Fields #region Methods /// <summary> /// Hides the calltip /// </summary> /// <remarks> /// <see cref="Hide"/> and <see cref="Cancel"/> do the same thing /// </remarks> public void Cancel() { NativeScintilla.CallTipCancel(); } /// <summary> /// Hides the calltip /// </summary> /// <remarks> /// <see cref="Hide"/> and <see cref="Cancel"/> do the same thing /// </remarks> public void Hide() { NativeScintilla.CallTipCancel(); } private void ResetBackColor() { BackColor = SystemColors.Info; } private void ResetForeColor() { ForeColor = SystemColors.InfoText; } private void ResetHighlightEnd() { _highlightEnd = -1; } private void ResetHighlightStart() { _highlightStart = -1; } private void ResetHighlightTextColor() { HighlightTextColor = SystemColors.Highlight; } internal void SetBackColorInternal(Color value) { if (value == SystemColors.Info) Scintilla.ColorBag.Remove("CallTip.BackColor"); else Scintilla.ColorBag["CallTip.BackColor"] = value; NativeScintilla.CallTipSetBack(Utilities.ColorToRgb(value)); } internal void SetForeColorInternal(Color value) { if (value == SystemColors.InfoText) Scintilla.ColorBag.Remove("CallTip.ForeColor"); else Scintilla.ColorBag["CallTip.ForeColor"] = value; NativeScintilla.CallTipSetFore(Utilities.ColorToRgb(value)); } internal bool ShouldSerialize() { return ShouldSerializeBackColor() || ShouldSerializeForeColor() || ShouldSerializeHighlightEnd() || ShouldSerializeHighlightStart() || ShouldSerializeHighlightTextColor(); } private bool ShouldSerializeBackColor() { return BackColor != SystemColors.Info; } private bool ShouldSerializeForeColor() { return ForeColor != SystemColors.InfoText; } private bool ShouldSerializeHighlightEnd() { return _highlightEnd >= 0; } private bool ShouldSerializeHighlightStart() { return _highlightStart >= 0; } private bool ShouldSerializeHighlightTextColor() { return HighlightTextColor != SystemColors.Highlight; } /// <summary> /// Displays a calltip without overloads /// </summary> /// <remarks> /// The <see cref="Message"/> must already be populated. The calltip will be displayed at the current document position /// with no highlight. /// </remarks> public void Show() { Show(_message, -1, -1, -1); } /// <summary> /// Displays a calltip without overloads /// </summary> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// The <see cref="Message"/> must already be populated. The calltip will be displayed at the current document position /// </remarks> public void Show(int highlightStart, int highlightEnd) { Show(_message, -1, highlightStart, highlightEnd); } /// <summary> /// Displays a calltip without overloads /// </summary> /// <param name="position">The document position to show the calltip</param> /// <remarks> /// The <see cref="Message"/> must already be populated. The calltip with no highlight /// </remarks> public void Show(int position) { Show(_message, position, -1, -1); } /// <summary> /// Displays a calltip without overloads /// </summary> /// <param name="position">The document position to show the calltip</param> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// The <see cref="Message"/> must already be populated. /// </remarks> public void Show(int position, int highlightStart, int highlightEnd) { Show(_message, position, highlightStart, highlightEnd); } /// <summary> /// Displays a calltip without overloads /// </summary> /// <param name="message">The calltip message to be displayed</param> /// <remarks> /// The calltip will be displayed at the current document position with no highlight /// </remarks> public void Show(string message) { Show(message, -1, -1, -1); } /// <summary> /// Displays a calltip without overloads /// </summary> /// <param name="message">The calltip message to be displayed</param> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// The calltip will be displayed at the current document position /// </remarks> public void Show(string message, int highlightStart, int highlightEnd) { Show(message, -1, highlightStart, highlightEnd); } /// <summary> /// Displays a calltip without overloads /// </summary> /// <param name="message">The calltip message to be displayed</param> /// <param name="position">The document position to show the calltip</param> /// <remarks> /// The calltip will be displayed with no highlight /// </remarks> public void Show(string message, int position) { Show(message, position, -1, -1); } /// <summary> /// Displays a calltip without overloads /// </summary> /// <param name="message">The calltip message to be displayed</param> /// <param name="position">The document position to show the calltip</param> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> public void Show(string message, int position, int highlightStart, int highlightEnd) { _lastPos = position; if (position < 0) position = NativeScintilla.GetCurrentPos(); _overloadList = null; _message = message; NativeScintilla.CallTipShow(position, message); HighlightStart = highlightStart; HighlightEnd = highlightEnd; } /// <summary> /// Shows the calltip with overloads /// </summary> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The <see cref="OverLoadList"/> must already be populated. It will be displayed at the current document /// position starting at overload 0 with no highlight. /// </remarks> public void ShowOverload() { ShowOverload(_overloadList, -1, 0, -1, -1); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The <see cref="OverLoadList"/> must already be populated. It will be displayed at the current document /// position starting at overload 0 /// </remarks> public void ShowOverload(int highlightStart, int highlightEnd) { ShowOverload(_overloadList, -1, 0, highlightStart, highlightEnd); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="position">The document position where the calltip should be displayed</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The <see cref="OverLoadList"/> must already be populated. The overload at position 0 will be displayed /// with no highlight. /// </remarks> public void ShowOverload(int position) { ShowOverload(_overloadList, position, 0, -1, -1); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="position">The document position where the calltip should be displayed</param> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The <see cref="OverLoadList"/> must already be populated. The overload at position 0 will be displayed. /// </remarks> public void ShowOverload(int position, int highlightStart, int highlightEnd) { ShowOverload(_overloadList, position, 0, highlightStart, highlightEnd); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="position">The document position where the calltip should be displayed</param> /// <param name="startIndex">The index of the initial overload to display</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The <see cref="OverLoadList"/> must already be populated. It will be displayed at the current document /// position with no highlight /// </remarks> public void ShowOverload(int position, uint startIndex) { ShowOverload(_overloadList, position, startIndex, -1, -1); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="position">The document position where the calltip should be displayed</param> /// <param name="startIndex">The index of the initial overload to display</param> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The <see cref="OverLoadList"/> must already be populated. /// </remarks> public void ShowOverload(int position, uint startIndex, int highlightStart, int highlightEnd) { ShowOverload(_overloadList, position, startIndex, highlightStart, highlightEnd); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="overloadList">List of overloads to be displayed see <see cref="OverLoadList"/></param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The current document position will be used starting at position 0 with no highlight /// </remarks> public void ShowOverload(OverloadList overloadList) { ShowOverload(overloadList, -1, 0, -1, -1); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="overloadList">List of overloads to be displayed see <see cref="OverLoadList"/></param> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The current document position will be used starting at position 0 /// </remarks> public void ShowOverload(OverloadList overloadList, int highlightStart, int highlightEnd) { ShowOverload(overloadList, -1, 0, highlightStart, highlightEnd); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="overloadList">List of overloads to be displayed see <see cref="OverLoadList"/></param> /// <param name="position">The document position where the calltip should be displayed</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The overload startIndex will be 0 with no Highlight /// </remarks> public void ShowOverload(OverloadList overloadList, int position) { ShowOverload(overloadList, position, 0, -1, -1); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="overloadList">List of overloads to be displayed see <see cref="OverLoadList"/></param> /// <param name="position">The document position where the calltip should be displayed</param> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The overload startIndex will be 0 /// </remarks> public void ShowOverload(OverloadList overloadList, int position, int highlightStart, int highlightEnd) { ShowOverload(overloadList, position, 0, highlightStart, highlightEnd); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="overloadList">List of overloads to be displayed see <see cref="OverLoadList"/></param> /// <param name="position">The document position where the calltip should be displayed</param> /// <param name="startIndex">The index of the initial overload to display</param> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// </remarks> public void ShowOverload(OverloadList overloadList, int position, uint startIndex, int highlightStart, int highlightEnd) { _lastPos = position; _overloadList = overloadList; unchecked { _overloadList.CurrentIndex = (int)startIndex; } _highlightEnd = highlightEnd; _highlightStart = highlightStart; ShowOverloadInternal(); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="overloadList">List of overloads to be displayed see <see cref="OverLoadList"/></param> /// <param name="startIndex">The index of the initial overload to display</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The current document position will be used with no highlight /// </remarks> public void ShowOverload(OverloadList overloadList, uint startIndex) { ShowOverload(overloadList, -1, startIndex, -1, -1); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="overloadList">List of overloads to be displayed see <see cref="OverLoadList"/></param> /// <param name="startIndex">The index of the initial overload to display</param> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The current document position will be used /// </remarks> public void ShowOverload(OverloadList overloadList, uint startIndex, int highlightStart, int highlightEnd) { ShowOverload(overloadList, -1, startIndex, highlightStart, highlightEnd); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="startIndex">The index of the initial overload to display</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The <see cref="OverLoadList"/> must already be populated. It will be displayed at the current document /// position with no highlight. /// </remarks> public void ShowOverload(uint startIndex) { ShowOverload(_overloadList, -1, startIndex, -1, -1); } /// <summary> /// Shows the calltip with overloads /// </summary> /// <param name="startIndex">The index of the initial overload to display</param> /// <param name="highlightStart">Start posision of the part of the message that should be selected</param> /// <param name="highlightEnd">End posision of the part of the message that should be selected</param> /// <remarks> /// ShowOverload automatically handles displaying a calltip with a list of overloads. It automatically shows the /// up and down arrows and cycles through the list of overloads in response to mouse clicks. /// The <see cref="OverLoadList"/> must already be populated. It will be displayed at the current document /// position. /// </remarks> public void ShowOverload(uint startIndex, int highlightStart, int highlightEnd) { ShowOverload(_overloadList, -1, startIndex, highlightStart, highlightEnd); } internal void ShowOverloadInternal() { int pos = _lastPos; if (pos < 0) pos = NativeScintilla.GetCurrentPos(); string s = "\u0001 {1} of {2} \u0002 {0}"; s = string.Format(s, _overloadList.Current, _overloadList.CurrentIndex + 1, _overloadList.Count); NativeScintilla.CallTipCancel(); NativeScintilla.CallTipShow(pos, s); NativeScintilla.CallTipSetHlt(_highlightStart, _highlightEnd); } #endregion Methods #region Properties /// <summary> /// Gets/Sets the background color of all CallTips /// </summary> public Color BackColor { get { if (Scintilla.ColorBag.ContainsKey("CallTip.BackColor")) return Scintilla.ColorBag["CallTip.BackColor"]; return SystemColors.Info; } set { SetBackColorInternal(value); Scintilla.Styles.CallTip.SetBackColorInternal(value); } } /// <summary> /// Gets/Sets Text color of all CallTips /// </summary> public Color ForeColor { get { if (Scintilla.ColorBag.ContainsKey("CallTip.ForeColor")) return Scintilla.ColorBag["CallTip.ForeColor"]; return SystemColors.InfoText; } set { SetForeColorInternal(value); Scintilla.Styles.CallTip.SetForeColorInternal(value); } } /// <summary> /// End position of the text to be highlighted in the CalTip /// </summary> public int HighlightEnd { get { return _highlightEnd; } set { _highlightEnd = value; NativeScintilla.CallTipSetHlt(_highlightStart, _highlightEnd); } } /// <summary> /// Start position of the text to be highlighted in the CalTip /// </summary> public int HighlightStart { get { return _highlightStart; } set { _highlightStart = value; NativeScintilla.CallTipSetHlt(_highlightStart, _highlightStart); } } /// <summary> /// Gets/Sets the Text Color of the portion of the CallTip that is highlighted /// </summary> public Color HighlightTextColor { // Note the default Color of this is SystemColors.Highlight, instead // of HighlightText, which one would normally think. However since // there is no Contrasting HighlightBackColor a light Highlight Color // on the light InfoTip background is nearly impossible to see. get { if (Scintilla.ColorBag.ContainsKey("CallTip.HighlightTextColor")) return Scintilla.ColorBag["CallTip.HighlightTextColor"]; return SystemColors.Highlight; } set { if (value == SystemColors.Highlight) Scintilla.ColorBag.Remove("CallTip.HighlightTextColor"); else Scintilla.ColorBag["CallTip.HighlightTextColor"] = value; NativeScintilla.CallTipSetForeHlt(Utilities.ColorToRgb(value)); } } /// <summary> /// Returns true if a CallTip is currently displayed /// </summary> public bool IsActive { get { return NativeScintilla.CallTipActive(); } } /// <summary> /// The message displayed in the calltip /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Message { get { return _message; } set { _message = value; } } /// <summary> /// List of method overloads to display in the calltip /// </summary> /// <remarks> /// This is used to display IDE type toolips that include Up/Down arrows that cycle /// through the list of overloads when clicked /// </remarks> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public OverloadList OverloadList { get { return _overloadList; } set { _overloadList = value; } } #endregion Properties #region Constructors internal CallTip(Scintilla scintilla) : base(scintilla) { // Go ahead and enable this. It's all pretty idiosyncratic IMO. For one // thing you can't turn it off. We set the CallTip styles by default // anyhow. NativeScintilla.CallTipUseStyle(10); Scintilla.BeginInvoke(new MethodInvoker(delegate() { HighlightTextColor = HighlightTextColor; ForeColor = ForeColor; BackColor = BackColor; })); } #endregion Constructors } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Data.Forms { /// <summary> /// This component allows customization of how log messages are sent. /// </summary> public class LogManager : ILogManager { #region Fields // the actual collection of ILoggers private readonly IDictionary<int, ILogger> _loggers; // increments so that each addition increments the active key. private int _currentKey; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="LogManager"/> class. /// </summary> public LogManager() { InitializeComponent(); _loggers = new Dictionary<int, ILogger>(); _currentKey = 0; DefaultLogManager = this; } #endregion #region Properties /// <summary> /// Gets the default log manager. This ensures that there will always be some kind of log manager. /// When a new LogManager is created, this static is set to be that instance. /// Controlling the DefaultLogManager will control which log manager /// is actively in use. /// </summary> public static ILogManager DefaultLogManager { get; private set; } = new LogManager(); /// <summary> /// Gets a required designer variable. /// </summary> public IContainer Components { get; private set; } /// <summary> /// Gets or sets the list of string directories that may contain dlls with ILogManagers. /// </summary> public List<string> Directories { get; set; } #endregion #region Methods /// <summary> /// To begin logging, create an implementation of the ILogHandler interface, or use the DefaultLogger class that is already implemented in this project. /// Then, call this function to add that logger to the list of active loggers. /// This function will return an integer key that you can use to keep track of your specific logger. /// </summary> /// <param name="logger">The logger that should be added to the list of active loggers.</param> /// <returns>Integer key of this logger.</returns> public int AddLogger(ILogger logger) { // The current key will keep going up even if loggers are removed, just so we don't get into trouble with redundancies. _loggers.Add(_currentKey, logger); _currentKey++; return _currentKey - 1; } /// <summary> /// Adds all the loggers from directories. /// </summary> /// <returns>A list of added loggers.</returns> public List<ILogger> AddLoggersFromDirectories() { return null; // TO DO: treat this like DataManager does } /// <summary> /// The Complete exception is passed here. To get the stack /// trace, be sure to call ex.ToString(). /// </summary> /// <param name="ex">The exception that was thrown by DotSpatial.</param> public void Exception(Exception ex) { foreach (KeyValuePair<int, ILogger> logger in _loggers) { logger.Value.Exception(ex); } } /// <summary> /// This method echoes information about input boxes to all the loggers. /// </summary> /// <param name="text">The string message that appeared on the InputBox.</param> /// <param name="result">The ystem.Windows.Forms.DialogResult describing if the value was cancelled. </param> /// <param name="value">The string containing the value entered.</param> public void LogInput(string text, DialogResult result, string value) { foreach (KeyValuePair<int, ILogger> logger in _loggers) { logger.Value.InputBoxShown(text, result, value); } } /// <summary> /// Displays an InputBox form given the specified text string. The result is returned byref. /// A DialogResult is returned to show whether the user cancelled the form without providing input. /// </summary> /// <param name="text">The string text to use as an input prompt.</param> /// <param name="result">The string result that was typed into the dialog.</param> /// <returns>A DialogResult showing the outcome.</returns> public DialogResult LogInputBox(string text, out string result) { InputBox frm = new InputBox(text); result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result; LogInput(text, frm.DialogResult, result); return frm.DialogResult; } /// <summary> /// Displays an InputBox form given the specified text string. The result is returned byref. /// A DialogResult is returned to show whether the user cancelled the form without providing input. /// </summary> /// <param name="text">The string text to use as an input prompt.</param> /// <param name="caption">The string to use in the title bar of the InputBox.</param> /// <param name="result">The string result that was typed into the dialog.</param> /// <returns>A DialogResult showing the outcome.</returns> public DialogResult LogInputBox(string text, string caption, out string result) { InputBox frm = new InputBox(text, caption); result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result; LogInput(text, frm.DialogResult, result); return frm.DialogResult; } /// <summary> /// Displays an InputBox form given the specified text string. The result is returned byref. /// A DialogResult is returned to show whether the user cancelled the form without providing input. /// </summary> /// <param name="text">The string text to use as an input prompt.</param> /// <param name="caption">The string to use in the title bar of the InputBox.</param> /// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param> /// <param name="result">The string result that was typed into the dialog.</param> /// <returns>A DialogResult showing the outcome.</returns> public DialogResult LogInputBox(string text, string caption, ValidationType validation, out string result) { InputBox frm = new InputBox(text, caption, validation); result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result; LogInput(text, frm.DialogResult, result); return frm.DialogResult; } /// <summary> /// Displays an InputBox form given the specified text string. The result is returned byref. /// A DialogResult is returned to show whether the user cancelled the form without providing input. /// </summary> /// <param name="text">The string text to use as an input prompt.</param> /// <param name="caption">The string to use in the title bar of the InputBox.</param> /// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param> /// <param name="icon">Specifies an icon to display on this form.</param> /// <param name="result">The string result that was typed into the dialog.</param> /// <returns>A DialogResult showing the outcome.</returns> public DialogResult LogInputBox(string text, string caption, ValidationType validation, Icon icon, out string result) { InputBox frm = new InputBox(text, caption, validation, icon); result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result; LogInput(text, frm.DialogResult, result); return frm.DialogResult; } /// <summary> /// Displays an InputBox form given the specified text string. The result is returned byref. /// A DialogResult is returned to show whether the user cancelled the form without providing input. /// </summary> /// <param name="owner">The window that owns this modal dialog.</param> /// <param name="text">The string text to use as an input prompt.</param> /// <param name="result">The string result that was typed into the dialog.</param> /// <returns>A DialogResult showing the outcome.</returns> public DialogResult LogInputBox(Form owner, string text, out string result) { InputBox frm = new InputBox(owner, text); result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result; LogInput(text, frm.DialogResult, result); return frm.DialogResult; } /// <summary> /// Displays an InputBox form given the specified text string. The result is returned byref. /// A DialogResult is returned to show whether the user cancelled the form without providing input. /// </summary> /// <param name="owner">The window that owns this modal dialog.</param> /// <param name="text">The string text to use as an input prompt.</param> /// <param name="caption">The string to use in the title bar of the InputBox.</param> /// <param name="result">The string result that was typed into the dialog.</param> /// <returns>A DialogResult showing the outcome.</returns> public DialogResult LogInputBox(Form owner, string text, string caption, out string result) { InputBox frm = new InputBox(owner, text, caption); result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result; LogInput(text, frm.DialogResult, result); return frm.DialogResult; } /// <summary> /// Displays an InputBox form given the specified text string. The result is returned byref. /// A DialogResult is returned to show whether the user cancelled the form without providing input. /// </summary> /// <param name="owner">The window that owns this modal dialog.</param> /// <param name="text">The string text to use as an input prompt.</param> /// <param name="caption">The string to use in the title bar of the InputBox.</param> /// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param> /// <param name="result">The string result that was typed into the dialog.</param> /// <returns>A DialogResult showing the outcome.</returns> public DialogResult LogInputBox(Form owner, string text, string caption, ValidationType validation, out string result) { InputBox frm = new InputBox(owner, text, caption, validation); result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result; LogInput(text, frm.DialogResult, result); return frm.DialogResult; } /// <summary> /// Displays an InputBox form given the specified text string. The result is returned byref. /// A DialogResult is returned to show whether the user cancelled the form without providing input. /// </summary> /// <param name="owner">The window that owns this modal dialog.</param> /// <param name="text">The string text to use as an input prompt.</param> /// <param name="caption">The string to use in the title bar of the InputBox.</param> /// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param> /// <param name="icon">Specifies an icon to display on this form.</param> /// <param name="result">The string result that was typed into the dialog.</param> /// <returns>A DialogResult showing the outcome.</returns> public DialogResult LogInputBox(Form owner, string text, string caption, ValidationType validation, Icon icon, out string result) { InputBox frm = new InputBox(owner, text, caption, validation, icon); result = frm.ShowDialog() != DialogResult.OK ? string.Empty : frm.Result; LogInput(text, frm.DialogResult, result); return frm.DialogResult; } /// <summary> /// This is called by each of the LogMessageBox methods automatically, but if the user wants to use /// a custom messagebox and then log the message and result directly this is the technique. /// </summary> /// <param name="text">The string text of the message that needs to be logged.</param> /// <param name="result">The dialog result from the shown messagebox.</param> public void LogMessage(string text, DialogResult result) { foreach (KeyValuePair<int, ILogger> logger in _loggers) { logger.Value.MessageBoxShown(text, result); } } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param> /// <param name="text">The text to display in the MessageBox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(IWin32Window owner, string text) { DialogResult res = MessageBox.Show(owner, text); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(IWin32Window owner, string text, string caption) { DialogResult res = MessageBox.Show(owner, text, caption); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { DialogResult res = MessageBox.Show(owner, text, caption, buttons); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox.</param> /// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { DialogResult res = MessageBox.Show(owner, text, caption, buttons, icon); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox.</param> /// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButtons that describes the default button for the MessageBox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { DialogResult res = MessageBox.Show(owner, text, caption, buttons, icon, defaultButton); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="owner">An implementation of the IWin32Window that will own the modal form dialog box.</param> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox.</param> /// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButtons that describes the default button for the MessageBox.</param> /// <param name="options">One of the MessageBoxOptions that describes which display and association options to use for the MessageBox. You may pass 0 if you wish to use the defaults.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options) { DialogResult res = MessageBox.Show(owner, text, caption, buttons, icon, defaultButton, options); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="text">The text to display in the MessageBox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(string text) { DialogResult res = MessageBox.Show(text); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(string text, string caption) { DialogResult res = MessageBox.Show(text, caption); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(string text, string caption, MessageBoxButtons buttons) { DialogResult res = MessageBox.Show(text, caption, buttons); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox.</param> /// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { DialogResult res = MessageBox.Show(text, caption, buttons, icon); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox.</param> /// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButtons that describes the default button for the MessageBox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { DialogResult res = MessageBox.Show(text, caption, buttons, icon, defaultButton); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox.</param> /// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButtons that describes the default button for the MessageBox.</param> /// <param name="options">One of the MessageBoxOptions that describes which display and association options to use for the MessageBox. You may pass 0 if you wish to use the defaults.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options) { DialogResult res = MessageBox.Show(text, caption, buttons, icon, defaultButton, options); LogMessage(text, res); return res; } /// <summary> /// Shows a MessageBox, logs the text of the text and the result chosen by the user. /// </summary> /// <param name="text">The text to display in the MessageBox.</param> /// <param name="caption">The text to display in the title bar of the MessageBox.</param> /// <param name="buttons">One of the MessageBoxButtons that describes which button to display in the MessageBox.</param> /// <param name="icon">One of the MessageBoxIcons that describes which icon to display in the MessageBox.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButtons that describes the default button for the MessageBox.</param> /// <param name="options">One of the MessageBoxOptions that describes which display and association options to use for the MessageBox. You may pass 0 if you wish to use the defaults.</param> /// <param name="displayHelpButton">A boolean indicating whether or not to display a help button on the messagebox.</param> /// <returns>A DialogResult showing the user input from this messagebox.</returns> public DialogResult LogMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, bool displayHelpButton) { DialogResult res = MessageBox.Show(text, caption, buttons, icon, defaultButton, options, displayHelpButton); LogMessage(text, res); return res; } /// <summary> /// A progress message, generally as part of a long loop was sent. It is a bad /// idea to log these to a file as there may be thousands of them. /// </summary> /// <param name="percent">The integer percent from 0 to 100.</param> /// <param name="message">The complete message, showing both status and completion percent.</param> public void Progress(int percent, string message) { foreach (KeyValuePair<int, ILogger> logger in _loggers) { logger.Value.Progress(percent, message); } } /// <summary> /// This event will allow the registering of an entrance into a public Method of a "tools" related /// action to register its entrance into a function as well as logging the parameter names /// and a type specific indicator of their value. /// </summary> /// <param name="methodName">The string name of the method.</param> /// <param name="parameters">The List&lt;string&gt; of Parameter names and string form values.</param> public void PublicMethodEntered(string methodName, List<string> parameters) { foreach (KeyValuePair<int, ILogger> logger in _loggers) { logger.Value.PublicMethodEntered(methodName, parameters); } } /// <summary> /// This event will allow the registering of the exit from each public method. /// </summary> /// <param name="methodName">The Method name of the method being left.</param> public void PublicMethodLeft(string methodName) { foreach (KeyValuePair<int, ILogger> logger in _loggers) { logger.Value.PublicMethodLeft(methodName); } } /// <summary> /// Resets the progress. /// </summary> public void Reset() { foreach (KeyValuePair<int, ILogger> logger in _loggers) { logger.Value.Reset(); } } /// <summary> /// The key specified here is the key that was returned by the AddLogger method. /// </summary> /// <param name="key">The integer key of the logger to remove.</param> /// <returns>True if the logger was successfully removed, or false if the key could not be found.</returns> /// <exception cref="System.ArgumentNullException">key is null.</exception> public bool RemoveLogger(int key) { return _loggers.Remove(key); } /// <summary> /// A status message was sent. Complex methods that have a few major steps will /// call a status message to show which step the process is in. Loops will call the progress method instead. /// </summary> /// <param name="message">The string message that was posted.</param> public void Status(string message) { foreach (KeyValuePair<int, ILogger> logger in _loggers) { logger.Value.Status(message); } } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { Components = new Container(); } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.UserModel { using NPOI.DDF; using NPOI.HSSF.Record; using System; using NPOI.SS.UserModel; /// <summary> /// Represents a simple shape such as a line, rectangle or oval. /// @author Glen Stampoultzis (glens at apache.org) /// </summary> [Serializable] public class HSSFSimpleShape: HSSFShape { // The commented out ones haven't been tested yet or aren't supported // by HSSFSimpleShape. public const short OBJECT_TYPE_LINE = (short)HSSFShapeTypes.Line; public const short OBJECT_TYPE_RECTANGLE = (short)HSSFShapeTypes.Rectangle; public const short OBJECT_TYPE_OVAL = (short)HSSFShapeTypes.Ellipse; public const short OBJECT_TYPE_ARC = (short)HSSFShapeTypes.Arc; // public static short OBJECT_TYPE_CHART = 5; // public static short OBJECT_TYPE_TEXT = 6; // public static short OBJECT_TYPE_BUTTON = 7; public const short OBJECT_TYPE_PICTURE = (short)HSSFShapeTypes.PictureFrame; // public static short OBJECT_TYPE_POLYGON = 9; // public static short OBJECT_TYPE_CHECKBOX = 11; // public static short OBJECT_TYPE_OPTION_BUTTON = 12; // public static short OBJECT_TYPE_EDIT_BOX = 13; // public static short OBJECT_TYPE_LABEL = 14; // public static short OBJECT_TYPE_DIALOG_BOX = 15; // public static short OBJECT_TYPE_SPINNER = 16; // public static short OBJECT_TYPE_SCROLL_BAR = 17; // public static short OBJECT_TYPE_LIST_BOX = 18; // public static short OBJECT_TYPE_GROUP_BOX = 19; public const short OBJECT_TYPE_COMBO_BOX = (short)HSSFShapeTypes.HostControl; public const short OBJECT_TYPE_COMMENT = (short)HSSFShapeTypes.TextBox; public const short OBJECT_TYPE_MICROSOFT_OFFICE_DRAWING = 30; public const int WRAP_SQUARE = 0; public const int WRAP_BY_POINTS = 1; public const int WRAP_NONE = 2; private TextObjectRecord _textObjectRecord; public HSSFSimpleShape(EscherContainerRecord spContainer, ObjRecord objRecord, TextObjectRecord textObjectRecord) : base(spContainer, objRecord) { this._textObjectRecord = textObjectRecord; } public HSSFSimpleShape(EscherContainerRecord spContainer, ObjRecord objRecord) : base(spContainer, objRecord) { } /// <summary> /// Initializes a new instance of the <see cref="HSSFSimpleShape"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="anchor">The anchor.</param> public HSSFSimpleShape(HSSFShape parent, HSSFAnchor anchor) :base(parent, anchor) { _textObjectRecord = CreateTextObjRecord(); } /// <summary> /// Gets the shape type. /// </summary> /// <value>One of the OBJECT_TYPE_* constants.</value> /// @see #OBJECT_TYPE_LINE /// @see #OBJECT_TYPE_OVAL /// @see #OBJECT_TYPE_RECTANGLE /// @see #OBJECT_TYPE_PICTURE /// @see #OBJECT_TYPE_COMMENT public virtual int ShapeType { get { EscherSpRecord spRecord = (EscherSpRecord)GetEscherContainer().GetChildById(EscherSpRecord.RECORD_ID); return spRecord.ShapeType; } set { CommonObjectDataSubRecord cod = (CommonObjectDataSubRecord)GetObjRecord().SubRecords[0]; cod.ObjectType = CommonObjectType.MicrosoftOfficeDrawing; EscherSpRecord spRecord = (EscherSpRecord)GetEscherContainer().GetChildById(EscherSpRecord.RECORD_ID); spRecord.ShapeType = ((short)value); } } public int WrapText { get { EscherSimpleProperty property = (EscherSimpleProperty)GetOptRecord().Lookup(EscherProperties.TEXT__WRAPTEXT); return null == property ? WRAP_SQUARE : property.PropertyValue; } set { SetPropertyValue(new EscherSimpleProperty(EscherProperties.TEXT__WRAPTEXT, false, false, value)); } } protected internal TextObjectRecord GetTextObjectRecord() { return _textObjectRecord; } protected virtual TextObjectRecord CreateTextObjRecord() { TextObjectRecord obj = new TextObjectRecord(); obj.HorizontalTextAlignment = HorizontalTextAlignment.Center; obj.VerticalTextAlignment = VerticalTextAlignment.Center; obj.IsTextLocked = (true); obj.TextOrientation = TextOrientation.None; obj.Str = (new HSSFRichTextString("")); return obj; } /// <summary> /// Get or set the rich text string used by this object. /// </summary> public virtual IRichTextString String { get { return _textObjectRecord.Str; } set { //TODO add other shape types which can not contain text if (ShapeType == 0 || ShapeType == OBJECT_TYPE_LINE) { throw new InvalidOperationException("Cannot set text for shape type: " + ShapeType); } HSSFRichTextString rtr = (HSSFRichTextString)value; // If font is not set we must set the default one if (rtr.NumFormattingRuns == 0) rtr.ApplyFont((short)0); TextObjectRecord txo = GetOrCreateTextObjRecord(); txo.Str = (rtr); if (value.String != null) { SetPropertyValue(new EscherSimpleProperty(EscherProperties.TEXT__TEXTID, value.String.GetHashCode())); } } } internal override HSSFShape CloneShape() { TextObjectRecord txo = null; EscherContainerRecord spContainer = new EscherContainerRecord(); byte[] inSp = GetEscherContainer().Serialize(); spContainer.FillFields(inSp, 0, new DefaultEscherRecordFactory()); ObjRecord obj = (ObjRecord)GetObjRecord().CloneViaReserialise(); if (GetTextObjectRecord() != null && this.String != null && null != this.String.String) { txo = (TextObjectRecord)GetTextObjectRecord().CloneViaReserialise(); } return new HSSFSimpleShape(spContainer, obj, txo); } internal override void AfterInsert(HSSFPatriarch patriarch) { EscherAggregate agg = patriarch.GetBoundAggregate(); agg.AssociateShapeToObjRecord(GetEscherContainer().GetChildById(EscherClientDataRecord.RECORD_ID), GetObjRecord()); if (null != GetTextObjectRecord()) { agg.AssociateShapeToObjRecord(GetEscherContainer().GetChildById(EscherTextboxRecord.RECORD_ID), GetTextObjectRecord()); } } internal override void AfterRemove(HSSFPatriarch patriarch) { patriarch.GetBoundAggregate().RemoveShapeToObjRecord(GetEscherContainer().GetChildById(EscherClientDataRecord.RECORD_ID)); if (null != GetEscherContainer().GetChildById(EscherTextboxRecord.RECORD_ID)) { patriarch.GetBoundAggregate().RemoveShapeToObjRecord(GetEscherContainer().GetChildById(EscherTextboxRecord.RECORD_ID)); } } protected override EscherContainerRecord CreateSpContainer() { EscherContainerRecord spContainer = new EscherContainerRecord(); spContainer.RecordId=EscherContainerRecord.SP_CONTAINER; spContainer.Options = ((short)0x000F); EscherSpRecord sp = new EscherSpRecord(); sp.RecordId = (EscherSpRecord.RECORD_ID); sp.Flags = (EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE); sp.Version = ((short)0x2); EscherClientDataRecord clientData = new EscherClientDataRecord(); clientData.RecordId = (EscherClientDataRecord.RECORD_ID); clientData.Options = ((short)(0x0000)); EscherOptRecord optRecord = new EscherOptRecord(); optRecord.SetEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEDASHING, LINESTYLE_SOLID)); optRecord.SetEscherProperty(new EscherBoolProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x00080008)); // optRecord.SetEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEWIDTH, LINEWIDTH_DEFAULT)); optRecord.SetEscherProperty(new EscherRGBProperty(EscherProperties.FILL__FILLCOLOR, FILL__FILLCOLOR_DEFAULT)); optRecord.SetEscherProperty(new EscherRGBProperty(EscherProperties.LINESTYLE__COLOR, LINESTYLE__COLOR_DEFAULT)); optRecord.SetEscherProperty(new EscherBoolProperty(EscherProperties.FILL__NOFILLHITTEST, NO_FILLHITTEST_FALSE)); optRecord.SetEscherProperty(new EscherBoolProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x00080008)); optRecord.SetEscherProperty(new EscherShapePathProperty(EscherProperties.GEOMETRY__SHAPEPATH, EscherShapePathProperty.COMPLEX)); optRecord.SetEscherProperty(new EscherBoolProperty(EscherProperties.GROUPSHAPE__PRINT, 0x080000)); optRecord.RecordId = EscherOptRecord.RECORD_ID; EscherTextboxRecord escherTextbox = new EscherTextboxRecord(); escherTextbox.RecordId = (EscherTextboxRecord.RECORD_ID); escherTextbox.Options = (short)0x0000; spContainer.AddChildRecord(sp); spContainer.AddChildRecord(optRecord); spContainer.AddChildRecord(this.Anchor.GetEscherAnchor()); spContainer.AddChildRecord(clientData); spContainer.AddChildRecord(escherTextbox); return spContainer; } protected override ObjRecord CreateObjRecord() { ObjRecord obj = new ObjRecord(); CommonObjectDataSubRecord c = new CommonObjectDataSubRecord(); c.IsLocked=true; c.IsPrintable = true; c.IsAutoFill=true; c.IsAutoline=true; EndSubRecord e = new EndSubRecord(); obj.AddSubRecord(c); obj.AddSubRecord(e); return obj; } private TextObjectRecord GetOrCreateTextObjRecord() { if (GetTextObjectRecord() == null) { _textObjectRecord = CreateTextObjRecord(); } EscherTextboxRecord escherTextbox = (EscherTextboxRecord)GetEscherContainer().GetChildById(EscherTextboxRecord.RECORD_ID); if (null == escherTextbox) { escherTextbox = new EscherTextboxRecord(); escherTextbox.RecordId = (EscherTextboxRecord.RECORD_ID); escherTextbox.Options = ((short)0x0000); GetEscherContainer().AddChildRecord(escherTextbox); Patriarch.GetBoundAggregate().AssociateShapeToObjRecord(escherTextbox, _textObjectRecord); } return _textObjectRecord; } public bool FlipVertical { get; set; } public bool FlipHorizontal { get; set; } } }
using System; using System.Text; namespace ICSharpCode.TextEditor.Document { public sealed class TextUtilities { public enum CharacterType { LetterDigitOrUnderscore, WhiteSpace, Other } public static string LeadingWhiteSpaceToTabs(string line, int tabIndent) { StringBuilder stringBuilder = new StringBuilder(line.Length); int num = 0; int i = 0; for (i = 0; i < line.Length; i++) { if (line[i] == ' ') { num++; if (num == tabIndent) { stringBuilder.Append('\t'); num = 0; } } else { if (line[i] != '\t') { break; } stringBuilder.Append('\t'); num = 0; } } if (i < line.Length) { stringBuilder.Append(line.Substring(i - num)); } return stringBuilder.ToString(); } public static bool IsLetterDigitOrUnderscore(char c) { return char.IsLetterOrDigit(c) || c == '_'; } public static string GetExpressionBeforeOffset(TextArea textArea, int initialOffset) { IDocument document = textArea.Document; int num = initialOffset; while (num - 1 > 0) { char charAt = document.GetCharAt(num - 1); if (charAt <= ')') { if (charAt <= '\r') { if (charAt == '\n' || charAt == '\r') { break; } } else { if (charAt != '"') { switch (charAt) { case '\'': { if (num < initialOffset - 1) { return null; } return "'a'"; } case ')': { num = TextUtilities.SearchBracketBackward(document, num - 2, '(', ')'); continue; } } } else { if (num < initialOffset - 1) { return null; } return "\"\""; } } } else { if (charAt <= '>') { if (charAt == '.') { num--; continue; } if (charAt == '>') { if (document.GetCharAt(num - 2) == '-') { num -= 2; continue; } break; } } else { if (charAt == ']') { num = TextUtilities.SearchBracketBackward(document, num - 2, '[', ']'); continue; } if (charAt == '}') { break; } } } if (char.IsWhiteSpace(document.GetCharAt(num - 1))) { num--; } else { int num2 = num - 1; if (!TextUtilities.IsLetterDigitOrUnderscore(document.GetCharAt(num2))) { break; } while (num2 > 0 && TextUtilities.IsLetterDigitOrUnderscore(document.GetCharAt(num2 - 1))) { num2--; } string text = document.GetText(num2, num - num2).Trim(); string a; if (((a = text) != null && (a == "ref" || a == "out" || a == "in" || a == "return" || a == "throw" || a == "case")) || (text.Length > 0 && !TextUtilities.IsLetterDigitOrUnderscore(text[0]))) { break; } num = num2; } } if (num < 0) { return string.Empty; } string text2 = document.GetText(num, textArea.Caret.Offset - num).Trim(); int num3 = text2.LastIndexOf('\n'); if (num3 >= 0) { num += num3 + 1; } return document.GetText(num, textArea.Caret.Offset - num).Trim(); } public static TextUtilities.CharacterType GetCharacterType(char c) { if (TextUtilities.IsLetterDigitOrUnderscore(c)) { return TextUtilities.CharacterType.LetterDigitOrUnderscore; } if (char.IsWhiteSpace(c)) { return TextUtilities.CharacterType.WhiteSpace; } return TextUtilities.CharacterType.Other; } public static int GetFirstNonWSChar(IDocument document, int offset) { while (offset < document.TextLength && char.IsWhiteSpace(document.GetCharAt(offset))) { offset++; } return offset; } public static int FindWordEnd(IDocument document, int offset) { LineSegment lineSegmentForOffset = document.GetLineSegmentForOffset(offset); int num = lineSegmentForOffset.Offset + lineSegmentForOffset.Length; while (offset < num && TextUtilities.IsLetterDigitOrUnderscore(document.GetCharAt(offset))) { offset++; } return offset; } public static int FindWordStart(IDocument document, int offset) { LineSegment lineSegmentForOffset = document.GetLineSegmentForOffset(offset); int offset2 = lineSegmentForOffset.Offset; while (offset > offset2 && TextUtilities.IsLetterDigitOrUnderscore(document.GetCharAt(offset - 1))) { offset--; } return offset; } public static int FindNextWordStart(IDocument document, int offset) { LineSegment lineSegmentForOffset = document.GetLineSegmentForOffset(offset); int num = lineSegmentForOffset.Offset + lineSegmentForOffset.Length; TextUtilities.CharacterType characterType = TextUtilities.GetCharacterType(document.GetCharAt(offset)); while (offset < num) { if (TextUtilities.GetCharacterType(document.GetCharAt(offset)) != characterType) { break; } offset++; } while (offset < num && TextUtilities.GetCharacterType(document.GetCharAt(offset)) == TextUtilities.CharacterType.WhiteSpace) { offset++; } return offset; } public static int FindPrevWordStart(IDocument document, int offset) { if (offset > 0) { LineSegment lineSegmentForOffset = document.GetLineSegmentForOffset(offset); TextUtilities.CharacterType characterType = TextUtilities.GetCharacterType(document.GetCharAt(offset - 1)); while (offset > lineSegmentForOffset.Offset && TextUtilities.GetCharacterType(document.GetCharAt(offset - 1)) == characterType) { offset--; } if (characterType == TextUtilities.CharacterType.WhiteSpace && offset > lineSegmentForOffset.Offset) { characterType = TextUtilities.GetCharacterType(document.GetCharAt(offset - 1)); while (offset > lineSegmentForOffset.Offset && TextUtilities.GetCharacterType(document.GetCharAt(offset - 1)) == characterType) { offset--; } } } return offset; } public static string GetLineAsString(IDocument document, int lineNumber) { LineSegment lineSegment = document.GetLineSegment(lineNumber); return document.GetText(lineSegment.Offset, lineSegment.Length); } public static int SearchBracketBackward(IDocument document, int offset, char openBracket, char closingBracket) { return document.FormattingStrategy.SearchBracketBackward(document, offset, openBracket, closingBracket); } public static int SearchBracketForward(IDocument document, int offset, char openBracket, char closingBracket) { return document.FormattingStrategy.SearchBracketForward(document, offset, openBracket, closingBracket); } public static bool IsEmptyLine(IDocument document, int lineNumber) { return TextUtilities.IsEmptyLine(document, document.GetLineSegment(lineNumber)); } public static bool IsEmptyLine(IDocument document, LineSegment line) { for (int i = line.Offset; i < line.Offset + line.Length; i++) { char charAt = document.GetCharAt(i); if (!char.IsWhiteSpace(charAt)) { return false; } } return true; } private static bool IsWordPart(char ch) { return TextUtilities.IsLetterDigitOrUnderscore(ch) || ch == '.'; } public static string GetWordAt(IDocument document, int offset) { if (offset < 0 || offset >= document.TextLength - 1 || !TextUtilities.IsWordPart(document.GetCharAt(offset))) { return string.Empty; } int i = offset; int num = offset; while (i > 0) { if (!TextUtilities.IsWordPart(document.GetCharAt(i - 1))) { break; } i--; } while (num < document.TextLength - 1 && TextUtilities.IsWordPart(document.GetCharAt(num + 1))) { num++; } return document.GetText(i, num - i + 1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // IntersectQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Operator that yields the intersection of two data sources. /// </summary> /// <typeparam name="TInputOutput"></typeparam> internal sealed class IntersectQueryOperator<TInputOutput> : BinaryQueryOperator<TInputOutput, TInputOutput, TInputOutput> { private readonly IEqualityComparer<TInputOutput> _comparer; // An equality comparer. //--------------------------------------------------------------------------------------- // Constructs a new intersection operator. // internal IntersectQueryOperator(ParallelQuery<TInputOutput> left, ParallelQuery<TInputOutput> right, IEqualityComparer<TInputOutput> comparer) : base(left, right) { Debug.Assert(left != null && right != null, "child data sources cannot be null"); _comparer = comparer; _outputOrdered = LeftChild.OutputOrdered; SetOrdinalIndex(OrdinalIndexState.Shuffled); } internal override QueryResults<TInputOutput> Open( QuerySettings settings, bool preferStriping) { // We just open our child operators, left and then right. Do not propagate the preferStriping value, but // instead explicitly set it to false. Regardless of whether the parent prefers striping or range // partitioning, the output will be hash-partitioned. QueryResults<TInputOutput> leftChildResults = LeftChild.Open(settings, false); QueryResults<TInputOutput> rightChildResults = RightChild.Open(settings, false); return new BinaryQueryOperatorResults(leftChildResults, rightChildResults, this, settings, false); } public override void WrapPartitionedStream<TLeftKey, TRightKey>( PartitionedStream<TInputOutput, TLeftKey> leftPartitionedStream, PartitionedStream<TInputOutput, TRightKey> rightPartitionedStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, bool preferStriping, QuerySettings settings) { Debug.Assert(leftPartitionedStream.PartitionCount == rightPartitionedStream.PartitionCount); if (OutputOrdered) { WrapPartitionedStreamHelper<TLeftKey, TRightKey>( ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TLeftKey>( leftPartitionedStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken), rightPartitionedStream, outputRecipient, settings.CancellationState.MergedCancellationToken); } else { WrapPartitionedStreamHelper<int, TRightKey>( ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TLeftKey>( leftPartitionedStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken), rightPartitionedStream, outputRecipient, settings.CancellationState.MergedCancellationToken); } } //--------------------------------------------------------------------------------------- // This is a helper method. WrapPartitionedStream decides what type TLeftKey is going // to be, and then call this method with that key as a generic parameter. // private void WrapPartitionedStreamHelper<TLeftKey, TRightKey>( PartitionedStream<Pair, TLeftKey> leftHashStream, PartitionedStream<TInputOutput, TRightKey> rightPartitionedStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, CancellationToken cancellationToken) { int partitionCount = leftHashStream.PartitionCount; PartitionedStream<Pair, int> rightHashStream = ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TRightKey>( rightPartitionedStream, null, null, _comparer, cancellationToken); PartitionedStream<TInputOutput, TLeftKey> outputStream = new PartitionedStream<TInputOutput, TLeftKey>(partitionCount, leftHashStream.KeyComparer, OrdinalIndexState.Shuffled); for (int i = 0; i < partitionCount; i++) { if (OutputOrdered) { outputStream[i] = new OrderedIntersectQueryOperatorEnumerator<TLeftKey>( leftHashStream[i], rightHashStream[i], _comparer, leftHashStream.KeyComparer, cancellationToken); } else { outputStream[i] = (QueryOperatorEnumerator<TInputOutput, TLeftKey>)(object) new IntersectQueryOperatorEnumerator<TLeftKey>(leftHashStream[i], rightHashStream[i], _comparer, cancellationToken); } } outputRecipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // This enumerator performs the intersection operation incrementally. It does this by // maintaining a history -- in the form of a set -- of all data already seen. It then // only returns elements that are seen twice (returning each one only once). // class IntersectQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TInputOutput, int> { private QueryOperatorEnumerator<Pair, TLeftKey> _leftSource; // Left data source. private QueryOperatorEnumerator<Pair, int> _rightSource; // Right data source. private IEqualityComparer<TInputOutput> _comparer; // Comparer to use for equality/hash-coding. private Set<TInputOutput> _hashLookup; // The hash lookup, used to produce the intersection. private CancellationToken _cancellationToken; private Shared<int> _outputLoopCount; //--------------------------------------------------------------------------------------- // Instantiates a new intersection operator. // internal IntersectQueryOperatorEnumerator( QueryOperatorEnumerator<Pair, TLeftKey> leftSource, QueryOperatorEnumerator<Pair, int> rightSource, IEqualityComparer<TInputOutput> comparer, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(rightSource != null); _leftSource = leftSource; _rightSource = rightSource; _comparer = comparer; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Walks the two data sources, left and then right, to produce the intersection. // internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey) { Debug.Assert(_leftSource != null); Debug.Assert(_rightSource != null); // Build the set out of the right data source, if we haven't already. if (_hashLookup == null) { _outputLoopCount = new Shared<int>(0); _hashLookup = new Set<TInputOutput>(_comparer); Pair rightElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); int rightKeyUnused = default(int); int i = 0; while (_rightSource.MoveNext(ref rightElement, ref rightKeyUnused)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); _hashLookup.Add((TInputOutput)rightElement.First); } } // Now iterate over the left data source, looking for matches. Pair leftElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); TLeftKey keyUnused = default(TLeftKey); while (_leftSource.MoveNext(ref leftElement, ref keyUnused)) { if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // If we found the element in our set, and if we haven't returned it yet, // we can yield it to the caller. We also mark it so we know we've returned // it once already and never will again. if (_hashLookup.Remove((TInputOutput)leftElement.First)) { currentElement = (TInputOutput)leftElement.First; #if DEBUG currentKey = unchecked((int)0xdeadbeef); #endif return true; } } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_leftSource != null && _rightSource != null); _leftSource.Dispose(); _rightSource.Dispose(); } } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token) { IEnumerable<TInputOutput> wrappedLeftChild = CancellableEnumerable.Wrap(LeftChild.AsSequentialQuery(token), token); IEnumerable<TInputOutput> wrappedRightChild = CancellableEnumerable.Wrap(RightChild.AsSequentialQuery(token), token); return wrappedLeftChild.Intersect(wrappedRightChild, _comparer); } class OrderedIntersectQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TInputOutput, TLeftKey> { private QueryOperatorEnumerator<Pair, TLeftKey> _leftSource; // Left data source. private QueryOperatorEnumerator<Pair, int> _rightSource; // Right data source. private IEqualityComparer<Wrapper<TInputOutput>> _comparer; // Comparer to use for equality/hash-coding. private IComparer<TLeftKey> _leftKeyComparer; // Comparer to use to determine ordering of order keys. private Dictionary<Wrapper<TInputOutput>, Pair> _hashLookup; // The hash lookup, used to produce the intersection. private CancellationToken _cancellationToken; //--------------------------------------------------------------------------------------- // Instantiates a new intersection operator. // internal OrderedIntersectQueryOperatorEnumerator( QueryOperatorEnumerator<Pair, TLeftKey> leftSource, QueryOperatorEnumerator<Pair, int> rightSource, IEqualityComparer<TInputOutput> comparer, IComparer<TLeftKey> leftKeyComparer, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(rightSource != null); _leftSource = leftSource; _rightSource = rightSource; _comparer = new WrapperEqualityComparer<TInputOutput>(comparer); _leftKeyComparer = leftKeyComparer; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Walks the two data sources, left and then right, to produce the intersection. // internal override bool MoveNext(ref TInputOutput currentElement, ref TLeftKey currentKey) { Debug.Assert(_leftSource != null); Debug.Assert(_rightSource != null); // Build the set out of the left data source, if we haven't already. int i = 0; if (_hashLookup == null) { _hashLookup = new Dictionary<Wrapper<TInputOutput>, Pair>(_comparer); Pair leftElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); TLeftKey leftKey = default(TLeftKey); while (_leftSource.MoveNext(ref leftElement, ref leftKey)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // For each element, we track the smallest order key for that element that we saw so far Pair oldEntry; Wrapper<TInputOutput> wrappedLeftElem = new Wrapper<TInputOutput>((TInputOutput)leftElement.First); // If this is the first occurrence of this element, or the order key is lower than all keys we saw previously, // update the order key for this element. if (!_hashLookup.TryGetValue(wrappedLeftElem, out oldEntry) || _leftKeyComparer.Compare(leftKey, (TLeftKey)oldEntry.Second) < 0) { // For each "elem" value, we store the smallest key, and the element value that had that key. // Note that even though two element values are "equal" according to the EqualityComparer, // we still cannot choose arbitrarily which of the two to yield. _hashLookup[wrappedLeftElem] = new Pair(leftElement.First, leftKey); } } } // Now iterate over the right data source, looking for matches. Pair rightElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); int rightKeyUnused = default(int); while (_rightSource.MoveNext(ref rightElement, ref rightKeyUnused)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // If we found the element in our set, and if we haven't returned it yet, // we can yield it to the caller. We also mark it so we know we've returned // it once already and never will again. Pair entry; Wrapper<TInputOutput> wrappedRightElem = new Wrapper<TInputOutput>((TInputOutput)rightElement.First); if (_hashLookup.TryGetValue(wrappedRightElem, out entry)) { currentElement = (TInputOutput)entry.First; currentKey = (TLeftKey)entry.Second; _hashLookup.Remove(new Wrapper<TInputOutput>((TInputOutput)entry.First)); return true; } } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_leftSource != null && _rightSource != null); _leftSource.Dispose(); _rightSource.Dispose(); } } } }
// 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.Threading; // For Thread, Mutex public class TestContextBoundObject { public void TestMethod() { Thread.Sleep(MutexWaitOne2.c_LONG_SLEEP_TIME); } } /// <summary> /// WaitOne(System.Int32, System.Boolean) /// </summary> /// // Exercises Mutex: // Waits infinitely, // Waits a finite time, // Times out appropriately, // Throws Exceptions appropriately. public class MutexWaitOne2 { #region Public Constants public const int c_DEFAULT_SLEEP_TIME = 1000; // 1 second public const int c_LONG_SLEEP_TIME = 5000; // 5 second #endregion #region Private Fields private Mutex m_Mutex = null; #endregion #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest1: Wait Infinite"); try { do { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(SleepLongTime)); thread.Start(); if (m_Mutex.WaitOne(Timeout.Infinite) != true) { TestLibrary.TestFramework.LogError("001", "Can not wait Infinite"); retVal = false; break; } m_Mutex.ReleaseMutex(); } while (false); // do } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; } public bool PosTest2() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest2: Wait some finite time"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(SignalMutex)); thread.Start(); m_Mutex.WaitOne(2 * c_DEFAULT_SLEEP_TIME); m_Mutex.ReleaseMutex(); } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; } public bool PosTest3() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest3: Wait some finite time will quit for timeout"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(SignalMutex)); thread.Start(); Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race if (false != m_Mutex.WaitOne(c_DEFAULT_SLEEP_TIME / 10)) { m_Mutex.ReleaseMutex(); TestLibrary.TestFramework.LogError("004", "WaitOne returns true when wait time out"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; } public bool PosTest4() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest4: Wait some finite time will quit for timeout when another thread is in nondefault managed context"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(CallContextBoundObjectMethod)); thread.Start(); Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race if (false != m_Mutex.WaitOne(c_DEFAULT_SLEEP_TIME)) { m_Mutex.ReleaseMutex(); TestLibrary.TestFramework.LogError("006", "WaitOne returns true when wait some finite time will quit for timeout when another thread is in nondefault managed context"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("007", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; } public bool PosTest5() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest5: Wait some finite time will quit for timeout when another thread is in nondefault managed context"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(CallContextBoundObjectMethod)); thread.Start(); Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race if (false != m_Mutex.WaitOne(c_DEFAULT_SLEEP_TIME)) { m_Mutex.ReleaseMutex(); TestLibrary.TestFramework.LogError("008", "WaitOne returns true when wait some finite time will quit for timeout when another thread is in nondefault managed context"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; } public bool PosTest6() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest6: Wait infinite time when another thread is in nondefault managed context"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(CallContextBoundObjectMethod)); thread.Start(); Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race if (true != m_Mutex.WaitOne(Timeout.Infinite)) { m_Mutex.ReleaseMutex(); TestLibrary.TestFramework.LogError("010", "WaitOne returns false when wait infinite time when another thread is in nondefault managed context"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("011", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; } public bool PosTest7() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("PosTest7: Wait infinite time when another thread is in nondefault managed context"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(CallContextBoundObjectMethod)); thread.Start(); Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race if (true != m_Mutex.WaitOne(Timeout.Infinite)) { m_Mutex.ReleaseMutex(); TestLibrary.TestFramework.LogError("012", "WaitOne returns false when wait infinite time when another thread is in nondefault managed context"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("013", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { // Wait for the thread to terminate if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; } #endregion #region Negative Test Cases public bool NegTest1() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("NegTest1: AbandonedMutexException should be thrown if a thread exited without releasing a mutex"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(NeverReleaseMutex)); thread.Start(); Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race m_Mutex.WaitOne(Timeout.Infinite); // AbandonedMutexException is not thrown on Windows 98 or Windows ME //if (Environment.OSVersion.Platform == PlatformID.Win32NT) //{ TestLibrary.TestFramework.LogError("101", "AbandonedMutexException is not thrown if a thread exited without releasing a mutex"); retVal = false; //} } catch (AbandonedMutexException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { if (null != thread) { thread.Join(); } if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; } public bool NegTest2() { bool retVal = true; Thread thread = null; TestLibrary.TestFramework.BeginScenario("NegTest2: ObjectDisposedException should be thrown if current instance has already been disposed"); try { m_Mutex = new Mutex(); thread = new Thread(new ThreadStart(DisposeMutex)); thread.Start(); Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race Thread.Sleep(c_DEFAULT_SLEEP_TIME); m_Mutex.WaitOne(Timeout.Infinite); TestLibrary.TestFramework.LogError("103", "ObjectDisposedException is not thrown if current instance has already been disposed"); retVal = false; } catch (ObjectDisposedException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { if (null != thread) { thread.Join(); } if (null != m_Mutex) { ((IDisposable)m_Mutex).Dispose(); } } return retVal; } public bool NegTest3() { bool retVal = true; int testInt = 0; TestLibrary.TestFramework.BeginScenario("NegTest3: Check ArgumentOutOfRangeException will be thrown if millisecondsTimeout is a negative number other than -1"); try { testInt = TestLibrary.Generator.GetInt32(); if (testInt > 0) { testInt = 0 - testInt; } if (testInt == -1) { testInt--; } m_Mutex = new Mutex(); m_Mutex.WaitOne(testInt); TestLibrary.TestFramework.LogError("105", "ArgumentOutOfRangeException is not thrown if millisecondsTimeout is a negative number other than -1"); TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] testInt = " + testInt); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] testInt = " + testInt); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { if (null != m_Mutex) { m_Mutex.Dispose(); } } return retVal; } #endregion #endregion public static int Main() { MutexWaitOne2 test = new MutexWaitOne2(); TestLibrary.TestFramework.BeginTestCase("MutexWaitOne2"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private void SleepLongTime() { m_Mutex.WaitOne(); Thread.Sleep(c_LONG_SLEEP_TIME); m_Mutex.ReleaseMutex(); } private void SignalMutex() { m_Mutex.WaitOne(); Thread.Sleep(c_DEFAULT_SLEEP_TIME); m_Mutex.ReleaseMutex(); } private void NeverReleaseMutex() { m_Mutex.WaitOne(); Thread.Sleep(c_DEFAULT_SLEEP_TIME); } private void DisposeMutex() { Thread.Sleep(c_DEFAULT_SLEEP_TIME); ((IDisposable)m_Mutex).Dispose(); } private void CallContextBoundObjectMethod() { m_Mutex.WaitOne(); TestContextBoundObject obj = new TestContextBoundObject(); obj.TestMethod(); m_Mutex.ReleaseMutex(); } #endregion }
#region [License] // The MIT License (MIT) // // Copyright (c) 2014, Unity Technologies // Copyright (c) 2014, Cristian Alexandru Geambasu // // 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. // // https://bitbucket.org/Unity-Technologies/ui #endregion using UnityEngine; using UnityEngine.EventSystems; #if UNITY_EDITOR using UnityEditor; #endif using System; using System.Collections.Generic; namespace TeamUtility.IO { [AddComponentMenu("Event/Standalone Input Module")] public class StandaloneInputModule : PointerInputModule { private float m_NextAction; private Vector2 m_LastMousePosition; private Vector2 m_MousePosition; protected StandaloneInputModule() { } [Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)] public enum InputMode { Mouse, Buttons } [Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)] public InputMode inputMode { get { return InputMode.Mouse; } } [SerializeField] private string m_HorizontalAxis = "MenuHorizontal"; /// <summary> /// Name of the vertical axis for movement (if axis events are used). /// </summary> [SerializeField] private string m_VerticalAxis = "MenuVertical"; /// <summary> /// Name of the submit button. /// </summary> [SerializeField] private string m_SubmitButton = "Submit"; /// <summary> /// Name of the submit button. /// </summary> [SerializeField] private string m_CancelButton = "Cancel"; [SerializeField] private float m_InputActionsPerSecond = 10; [SerializeField] private bool m_AllowActivationOnMobileDevice; public bool allowActivationOnMobileDevice { get { return m_AllowActivationOnMobileDevice; } set { m_AllowActivationOnMobileDevice = value; } } public float inputActionsPerSecond { get { return m_InputActionsPerSecond; } set { m_InputActionsPerSecond = value; } } /// <summary> /// Name of the horizontal axis for movement (if axis events are used). /// </summary> public string horizontalAxis { get { return m_HorizontalAxis; } set { m_HorizontalAxis = value; } } /// <summary> /// Name of the vertical axis for movement (if axis events are used). /// </summary> public string verticalAxis { get { return m_VerticalAxis; } set { m_VerticalAxis = value; } } public string submitButton { get { return m_SubmitButton; } set { m_SubmitButton = value; } } public string cancelButton { get { return m_CancelButton; } set { m_CancelButton = value; } } public override void UpdateModule() { m_LastMousePosition = m_MousePosition; m_MousePosition = InputManager.mousePosition; } public override bool IsModuleSupported() { // Check for mouse presence instead of whether touch is supported, // as you can connect mouse to a tablet and in that case we'd want // to use StandaloneInputModule for non-touch input events. return m_AllowActivationOnMobileDevice || InputManager.mousePresent; } public override bool ShouldActivateModule() { if (!base.ShouldActivateModule()) return false; var shouldActivate = InputManager.GetButtonDown(m_SubmitButton); shouldActivate |= InputManager.GetButtonDown(m_CancelButton); shouldActivate |= !Mathf.Approximately(InputManager.GetAxisRaw(m_HorizontalAxis), 0.0f); shouldActivate |= !Mathf.Approximately(InputManager.GetAxisRaw(m_VerticalAxis), 0.0f); shouldActivate |= (m_MousePosition - m_LastMousePosition).sqrMagnitude > 0.0f; shouldActivate |= InputManager.GetMouseButtonDown(0); return shouldActivate; } public override void ActivateModule() { base.ActivateModule(); m_MousePosition = InputManager.mousePosition; m_LastMousePosition = InputManager.mousePosition; var toSelect = eventSystem.currentSelectedGameObject; if (toSelect == null) toSelect = eventSystem.lastSelectedGameObject; if (toSelect == null) toSelect = eventSystem.firstSelectedGameObject; eventSystem.SetSelectedGameObject(toSelect, GetBaseEventData()); } public override void DeactivateModule() { base.DeactivateModule(); ClearSelection(); } public override void Process() { bool usedEvent = SendUpdateEventToSelectedObject(); if (eventSystem.sendNavigationEvents) { if (!usedEvent) usedEvent |= SendMoveEventToSelectedObject(); if (!usedEvent) SendSubmitEventToSelectedObject(); } ProcessMouseEvent(); } /// <summary> /// Process submit keys. /// </summary> private bool SendSubmitEventToSelectedObject() { if (eventSystem.currentSelectedGameObject == null) return false; var data = GetBaseEventData(); if (InputManager.GetButtonDown(m_SubmitButton)) ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.submitHandler); if (InputManager.GetButtonDown(m_CancelButton)) ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.cancelHandler); return data.used; } private bool AllowMoveEventProcessing(float time) { string inputConfigName = InputManager.CurrentConfiguration.name; AxisConfiguration hAxisConfig = InputManager.GetAxisConfiguration(inputConfigName, m_HorizontalAxis); AxisConfiguration vAxisConfig = InputManager.GetAxisConfiguration(inputConfigName, m_VerticalAxis); bool allow = hAxisConfig.AnyKeyDown; allow |= vAxisConfig.AnyKeyDown; allow |= (time > m_NextAction); return allow; } private Vector2 GetRawMoveVector() { Vector2 move = Vector2.zero; move.x = InputManager.GetAxisRaw(m_HorizontalAxis); move.y = InputManager.GetAxisRaw(m_VerticalAxis); if (InputManager.GetButtonDown(m_HorizontalAxis)) { if (move.x < 0) move.x = -1f; if (move.x > 0) move.x = 1f; } if (InputManager.GetButtonDown(m_VerticalAxis)) { if (move.y < 0) move.y = -1f; if (move.y > 0) move.y = 1f; } return move; } /// <summary> /// Process keyboard events. /// </summary> private bool SendMoveEventToSelectedObject() { float time = Time.unscaledTime; if (!AllowMoveEventProcessing(time)) return false; Vector2 movement = GetRawMoveVector(); // Debug.Log(m_ProcessingEvent.rawType + " axis:" + m_AllowAxisEvents + " value:" + "(" + x + "," + y + ")"); var axisEventData = GetAxisEventData(movement.x, movement.y, 0.6f); if (!Mathf.Approximately(axisEventData.moveVector.x, 0f) || !Mathf.Approximately(axisEventData.moveVector.y, 0f)) { ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, axisEventData, ExecuteEvents.moveHandler); } m_NextAction = time + 1f / m_InputActionsPerSecond; return axisEventData.used; } /// <summary> /// Process all mouse events. /// </summary> private void ProcessMouseEvent() { var mouseData = GetMousePointerEventData(); var pressed = mouseData.AnyPressesThisFrame(); var released = mouseData.AnyReleasesThisFrame(); var leftButtonData = mouseData.GetButtonState(PointerEventData.InputButton.Left).eventData; if (!UseMouse(pressed, released, leftButtonData.buttonData)) return; // Process the first mouse button fully ProcessMousePress(leftButtonData); ProcessMove(leftButtonData.buttonData); ProcessDrag(leftButtonData.buttonData); // Now process right / middle clicks ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData); ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData.buttonData); ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData); ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData.buttonData); if (!Mathf.Approximately(leftButtonData.buttonData.scrollDelta.sqrMagnitude, 0.0f)) { var scrollHandler = ExecuteEvents.GetEventHandler<IScrollHandler>(leftButtonData.buttonData.pointerCurrentRaycast.gameObject); ExecuteEvents.ExecuteHierarchy(scrollHandler, leftButtonData.buttonData, ExecuteEvents.scrollHandler); } } private static bool UseMouse(bool pressed, bool released, PointerEventData pointerData) { if (pressed || released || pointerData.IsPointerMoving() || pointerData.IsScrolling()) return true; return false; } private bool SendUpdateEventToSelectedObject() { if (eventSystem.currentSelectedGameObject == null) return false; var data = GetBaseEventData(); ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.updateSelectedHandler); return data.used; } /// <summary> /// Process the current mouse press. /// </summary> private void ProcessMousePress(MouseButtonEventData data) { var pointerEvent = data.buttonData; var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject; // PointerDown notification if (data.PressedThisFrame()) { pointerEvent.eligibleForClick = true; pointerEvent.delta = Vector2.zero; pointerEvent.dragging = false; pointerEvent.useDragThreshold = true; pointerEvent.pressPosition = pointerEvent.position; pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast; DeselectIfSelectionChanged(currentOverGo, pointerEvent); // search for the control that will receive the press // if we can't find a press handler set the press // handler to be what would receive a click. var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler); // didnt find a press handler... search for a click handler if (newPressed == null) newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo); // Debug.Log("Pressed: " + newPressed); float time = Time.unscaledTime; if (newPressed == pointerEvent.lastPress) { var diffTime = time - pointerEvent.clickTime; if (diffTime < 0.3f) ++pointerEvent.clickCount; else pointerEvent.clickCount = 1; pointerEvent.clickTime = time; } else { pointerEvent.clickCount = 1; } pointerEvent.pointerPress = newPressed; pointerEvent.rawPointerPress = currentOverGo; pointerEvent.clickTime = time; // Save the drag handler as well pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo); if (pointerEvent.pointerDrag != null) ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag); } // PointerUp notification if (data.ReleasedThisFrame()) { // Debug.Log("Executing pressup on: " + pointer.pointerPress); ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler); // Debug.Log("KeyCode: " + pointer.eventData.keyCode); // see if we mouse up on the same element that we clicked on... var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo); // PointerClick and Drop events if (pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick) { ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler); } else if (pointerEvent.pointerDrag != null) { ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler); } pointerEvent.eligibleForClick = false; pointerEvent.pointerPress = null; pointerEvent.rawPointerPress = null; if (pointerEvent.pointerDrag != null && pointerEvent.dragging) ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler); pointerEvent.dragging = false; pointerEvent.pointerDrag = null; // redo pointer enter / exit to refresh state // so that if we moused over somethign that ignored it before // due to having pressed on something else // it now gets it. if (currentOverGo != pointerEvent.pointerEnter) { HandlePointerExitAndEnter(pointerEvent, null); HandlePointerExitAndEnter(pointerEvent, currentOverGo); } } } #if UNITY_EDITOR && (UNITY_4_6 || UNITY_4_7 || UNITY_5) [MenuItem("Team Utility/Input Manager/Use Custom Input Module", false, 200)] private static void FixEventSystem() { UnityEngine.EventSystems.StandaloneInputModule[] im = UnityEngine.Object.FindObjectsOfType<UnityEngine.EventSystems.StandaloneInputModule>(); if(im.Length > 0) { for(int i = 0; i < im.Length; i++) { im[i].gameObject.AddComponent<TeamUtility.IO.StandaloneInputModule>(); UnityEngine.Object.DestroyImmediate(im[i]); } EditorUtility.DisplayDialog("Success", "All built-in standalone input modules have been replaced!", "OK"); Debug.LogFormat("{0} built-in standalone input module(s) have been replaced", im.Length); } else { EditorUtility.DisplayDialog("Warning", "Unable to find any built-in input modules in the scene!", "OK"); } } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Validation; namespace System.Collections.Immutable { /// <content> /// Contains the inner Builder class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableHashSet<T> { /// <summary> /// A hash set that mutates with little or no memory allocations, /// can produce and/or build on immutable hash set instances very efficiently. /// </summary> /// <remarks> /// <para> /// While <see cref="ImmutableHashSet&lt;T&gt;.Union(IEnumerable&lt;T&gt;)"/> and other bulk change methods /// already provide fast bulk change operations on the collection, this class allows /// multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] public sealed class Builder : IReadOnlyCollection<T>, ISet<T> { /// <summary> /// The root of the binary tree that stores the collection. Contents are typically not entirely frozen. /// </summary> private ImmutableSortedDictionary<int, HashBucket>.Node root = ImmutableSortedDictionary<int, HashBucket>.Node.EmptyNode; /// <summary> /// The equality comparer. /// </summary> private IEqualityComparer<T> equalityComparer; /// <summary> /// The number of elements in this collection. /// </summary> private int count; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableHashSet<T> immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int version; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashSet&lt;T&gt;.Builder"/> class. /// </summary> /// <param name="set">The set.</param> internal Builder(ImmutableHashSet<T> set) { Requires.NotNull(set, "set"); this.root = set.root; this.count = set.count; this.equalityComparer = set.equalityComparer; this.immutable = set; } #region ISet<T> Properties /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns>The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</returns> public int Count { get { return this.count; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.</returns> bool ICollection<T>.IsReadOnly { get { return false; } } #endregion /// <summary> /// Gets or sets the key comparer. /// </summary> /// <value> /// The key comparer. /// </value> public IEqualityComparer<T> KeyComparer { get { return this.equalityComparer; } set { Requires.NotNull(value, "value"); if (value != this.equalityComparer) { var result = Union(this, new MutationInput(ImmutableSortedDictionary<int, HashBucket>.Node.EmptyNode, value, 0)); this.immutable = null; this.equalityComparer = value; this.Root = result.Root; this.count = result.Count; // whether the offset or absolute, since the base is 0, it's no difference. } } } /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return this.version; } } /// <summary> /// Gets the initial data to pass to a query or mutation method. /// </summary> private MutationInput Origin { get { return new MutationInput(this.Root, this.equalityComparer, this.count); } } /// <summary> /// Gets or sets the root of this data structure. /// </summary> private ImmutableSortedDictionary<int, HashBucket>.Node Root { get { return this.root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. this.version++; if (this.root != value) { this.root = value; // Clear any cached value for the immutable view since it is now invalidated. this.immutable = null; } } } #region Public methods /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this.root, this); } /// <summary> /// Creates an immutable hash set based on the contents of this instance. /// </summary> /// <returns>An immutable set.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableHashSet<T> ToImmutable() { // Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (this.immutable == null) { this.immutable = ImmutableHashSet<T>.Wrap(this.root, this.equalityComparer, this.count); } return this.immutable; } #endregion #region ISet<T> Methods /// <summary> /// Adds the specified item. /// </summary> /// <param name="item">The item.</param> /// <returns>True if the item did not already belong to the collection.</returns> public bool Add(T item) { var result = ImmutableHashSet<T>.Add(item, this.Origin); this.Apply(result); return result.Count != 0; } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public bool Remove(T item) { var result = ImmutableHashSet<T>.Remove(item, this.Origin); this.Apply(result); return result.Count != 0; } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> public bool Contains(T item) { return ImmutableHashSet<T>.Contains(item, this.Origin); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception> public void Clear() { this.count = 0; this.Root = ImmutableSortedDictionary<int, HashBucket>.Node.EmptyNode; } /// <summary> /// Removes all elements in the specified collection from the current set. /// </summary> /// <param name="other">The collection of items to remove from the set.</param> public void ExceptWith(IEnumerable<T> other) { var result = ImmutableHashSet<T>.Except(other, this.equalityComparer, this.root); this.Apply(result); } /// <summary> /// Modifies the current set so that it contains only elements that are also in a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void IntersectWith(IEnumerable<T> other) { var result = ImmutableHashSet<T>.Intersect(other, this.Origin); this.Apply(result); } /// <summary> /// Determines whether the current set is a proper (strict) subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct subset of other; otherwise, false.</returns> public bool IsProperSubsetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsProperSubsetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a proper (strict) superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> public bool IsProperSupersetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsProperSupersetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a subset of other; otherwise, false.</returns> public bool IsSubsetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsSubsetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> public bool IsSupersetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsSupersetOf(other, this.Origin); } /// <summary> /// Determines whether the current set overlaps with the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set and other share at least one common element; otherwise, false.</returns> public bool Overlaps(IEnumerable<T> other) { return ImmutableHashSet<T>.Overlaps(other, this.Origin); } /// <summary> /// Determines whether the current set and the specified collection contain the same elements. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is equal to other; otherwise, false.</returns> public bool SetEquals(IEnumerable<T> other) { return ImmutableHashSet<T>.SetEquals(other, this.Origin); } /// <summary> /// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void SymmetricExceptWith(IEnumerable<T> other) { var result = ImmutableHashSet<T>.SymmetricExcept(other, this.Origin); this.Apply(result); } /// <summary> /// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void UnionWith(IEnumerable<T> other) { var result = ImmutableHashSet<T>.Union(other, this.Origin); this.Apply(result); } #endregion #region ICollection<T> Members /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> void ICollection<T>.Add(T item) { this.Add(item); } /// <summary> /// See the <see cref="ICollection&lt;T&gt;"/> interface. /// </summary> void ICollection<T>.CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (T item in this) { array[arrayIndex++] = item; } } #endregion #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Applies the result of some mutation operation to this instance. /// </summary> /// <param name="result">The result.</param> private void Apply(MutationResult result) { this.Root = result.Root; if (result.CountType == CountType.Adjustment) { this.count += result.Count; } else { this.count = result.Count; } } } } }
//------------------------------------------------------------------------------ // <copyright file="MobileControlDesigner.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.Design.MobileControls { using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Web.UI; using System.Web.UI.Design; using System.Web.UI.Design.MobileControls.Adapters; using System.Web.UI.Design.MobileControls.Util; using System.Web.UI.MobileControls; [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class MobileControlDesigner : ControlDesigner, IMobileDesigner, IDeviceSpecificDesigner { private bool _containmentStatusDirty = true; private ContainmentStatus _containmentStatus; private IDesignerHost _host; private IWebFormsDocumentService _iWebFormsDocumentService; private IMobileWebFormServices _iMobileWebFormServices; private MobileControl _mobileControl; private System.Windows.Forms.Control _header; internal static readonly String resourceDllUrl = "res://" + typeof(MobileControlDesigner).Module.FullyQualifiedName; internal static readonly String errorIcon = resourceDllUrl + "//ERROR_GIF"; internal static readonly String infoIcon = resourceDllUrl + "//INFO_GIF"; internal static readonly String defaultErrorDesignTimeHTML = @" <table cellpadding=2 cellspacing=0 width='{4}' style='font-family:tahoma;font-size:8pt;color:buttontext;background-color:buttonface;border: solid 1px;border-top-color:buttonhighlight;border-left-color:buttonhighlight;border-bottom-color:buttonshadow;border-right-color:buttonshadow'> <tr><td><span style='font-weight:bold'>&nbsp;{0}</span> - {1}</td></tr> <tr><td> <table style='font-family:tahoma;font-size:8pt;color:window;background-color:ButtonShadow'> <tr> <td valign='top'><img src={3} /></td> <td width='100%'>{2}</td> </tr> </table> </td></tr> </table> "; internal static readonly String _formPanelContainmentErrorMessage = SR.GetString(SR.MobileControl_FormPanelContainmentErrorMessage); internal static readonly String _mobilePageErrorMessage = SR.GetString(SR.MobileControl_MobilePageErrorMessage); internal static readonly String _topPageContainmentErrorMessage = SR.GetString(SR.MobileControl_TopPageContainmentErrorMessage); internal static readonly String _userControlWarningMessage = SR.GetString(SR.MobileControl_UserControlWarningMessage); private const String _appliedDeviceFiltersPropName = "AppliedDeviceFilters"; private const String _propertyOverridesPropName = "PropertyOverrides"; private const String _defaultDeviceSpecificIdentifier = "unique"; private static readonly string[] _nonBrowsableProperties = new string[] { "EnableTheming", "Expressions", "SkinID", }; // predefined constants used for mergingContext internal const int MergingContextChoices = 0; internal const int MergingContextTemplates = 1; internal const int MergingContextProperties = 2; [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Editor(typeof(AppliedDeviceFiltersTypeEditor), typeof(UITypeEditor)), MergableProperty(false), MobileCategory(SR.Category_DeviceSpecific), MobileSysDescription(SR.MobileControl_AppliedDeviceFiltersDescription), ParenthesizePropertyName(true), ] protected String AppliedDeviceFilters { get { return String.Empty; } } protected ContainmentStatus ContainmentStatus { get { if (!_containmentStatusDirty) { return _containmentStatus; } _containmentStatus = DesignerAdapterUtil.GetContainmentStatus(_mobileControl); _containmentStatusDirty = false; return _containmentStatus; } } internal Object DesignTimeElementInternal { get { return typeof(HtmlControlDesigner).InvokeMember("DesignTimeElement", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic, null, this, null, CultureInfo.InvariantCulture); } } public override bool DesignTimeHtmlRequiresLoadComplete { get { return true; } } private IDesignerHost Host { get { if (_host != null) { return _host; } _host = (IDesignerHost)GetService(typeof(IDesignerHost)); Debug.Assert(_host != null); return _host; } } internal IMobileWebFormServices IMobileWebFormServices { get { if (_iMobileWebFormServices == null) { _iMobileWebFormServices = (IMobileWebFormServices)GetService(typeof(IMobileWebFormServices)); } return _iMobileWebFormServices; } } private IWebFormsDocumentService IWebFormsDocumentService { get { if (_iWebFormsDocumentService == null) { _iWebFormsDocumentService = (IWebFormsDocumentService)GetService(typeof(IWebFormsDocumentService)); Debug.Assert(_iWebFormsDocumentService != null); } return _iWebFormsDocumentService; } } /// <summary> /// Indicates whether the initial page load is completed /// </summary> protected bool LoadComplete { get { return !IWebFormsDocumentService.IsLoading; } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Editor(typeof(PropertyOverridesTypeEditor), typeof(UITypeEditor)), MergableProperty(false), MobileCategory(SR.Category_DeviceSpecific), MobileSysDescription(SR.MobileControl_DeviceSpecificPropsDescription), ParenthesizePropertyName(true), ] protected String PropertyOverrides { get { return String.Empty; } } private bool ValidContainment { get { return ( ContainmentStatus == ContainmentStatus.InForm || ContainmentStatus == ContainmentStatus.InPanel || ContainmentStatus == ContainmentStatus.InTemplateFrame); } } protected virtual String GetErrorMessage(out bool infoMode) { infoMode = false; // Skip containment checking if the control is placed in MobileUserControl if (!DesignerAdapterUtil.InMobileUserControl(_mobileControl)) { if (DesignerAdapterUtil.InUserControl(_mobileControl)) { infoMode = true; return MobileControlDesigner._userControlWarningMessage; } if (!DesignerAdapterUtil.InMobilePage(_mobileControl)) { return _mobilePageErrorMessage; } if (!ValidContainment) { return _formPanelContainmentErrorMessage; } } bool containsTag; bool containsDataboundLiteral; _mobileControl.GetControlText(out containsTag, out containsDataboundLiteral); if (containsTag) { return SR.GetString(SR.MobileControl_InnerTextCannotContainTagsDesigner); } // Containment is valid, return null; return null; } /// <summary> /// <para> /// Gets the HTML to be used for the design time representation of the control runtime. /// </para> /// </summary> /// <returns> /// <para> /// The design time HTML. /// </para> /// </returns> public sealed override String GetDesignTimeHtml() { if (!LoadComplete) { return null; } bool infoMode = false; String errorMessage = GetErrorMessage(out infoMode); SetStyleAttributes(); if (null != errorMessage) { return GetDesignTimeErrorHtml(errorMessage, infoMode); } String designTimeHTML = null; try { designTimeHTML = GetDesignTimeNormalHtml(); } catch (Exception ex) { Debug.Fail(ex.ToString()); designTimeHTML = GetDesignTimeErrorHtml(ex.Message, false); } return designTimeHTML; } protected virtual String GetDesignTimeNormalHtml() { return GetEmptyDesignTimeHtml(); } /// <summary> /// <para> /// Gets the HTML to be used at design time as the representation of the /// control when the control runtime does not return any rendered /// HTML. The default behavior is to return a string containing the name /// of the component. /// </para> /// </summary> /// <returns> /// <para> /// The name of the component, by default. /// </para> /// </returns> protected override String GetEmptyDesignTimeHtml() { return "<div style='width:100%'>" + base.GetEmptyDesignTimeHtml() + "</div>"; } protected override sealed String GetErrorDesignTimeHtml(Exception e) { return base.GetErrorDesignTimeHtml(e); } /// <summary> /// /// </summary> protected virtual String GetDesignTimeErrorHtml(String errorMessage, bool infoMode) { return DesignerAdapterUtil.GetDesignTimeErrorHtml( errorMessage, infoMode, _mobileControl, Behavior, ContainmentStatus); } /// <summary> /// <para> /// Gets the HTML to be persisted for the content present within the associated server control runtime. /// </para> /// </summary> /// <returns> /// <para> /// Persistable Inner HTML. /// </para> /// </returns> public override String GetPersistInnerHtml() { if (!IsDirty) { // Returning a null string will prevent the actual save. return null; } StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); // HACK ALERT: // We need to temporarily swap out the Text property to avoid being // persisted into control inner text. However, setting the Text property // will wipe out all control collections, therefore we need to cache // the Text value too. bool hasControls = _mobileControl.HasControls(); if ((_mobileControl is TextControl || _mobileControl is TextView) && hasControls) { String originalText = null; Control[] children = null; // Cache all child controls here. children = new Control[_mobileControl.Controls.Count]; _mobileControl.Controls.CopyTo(children, 0); // Replace the text with empty string. if (_mobileControl is TextControl) { originalText = ((TextControl)_mobileControl).Text; ((TextControl)_mobileControl).Text = String.Empty; } else { originalText = ((TextView)_mobileControl).Text; ((TextView)_mobileControl).Text = String.Empty; } try { // Persist inner properties without Text property. MobileControlPersister.PersistInnerProperties(sw, _mobileControl, Host); // Persist the child collections. foreach (Control c in children) { MobileControlPersister.PersistControl(sw, c, Host); } } finally { // Write the original text back to control. if (_mobileControl is TextControl) { ((TextControl)_mobileControl).Text = originalText; } else { ((TextView)_mobileControl).Text = originalText; } // Add the child controls back. foreach (Control c in children) { _mobileControl.Controls.Add(c); } } } else { MobileControlPersister.PersistInnerProperties(sw, _mobileControl, Host); } IsDirty = false; return sw.ToString(); } /// <summary> /// <para> /// Initializes the designer with the component for design. /// </para> /// </summary> /// <param name='component'> /// The control element for design. /// </param> /// <remarks> /// <para> /// This is called by the designer host to establish the component for /// design. /// </para> /// </remarks> /// <seealso cref='System.ComponentModel.Design.IDesigner'/> public override void Initialize(IComponent component) { Debug.Assert(component is System.Web.UI.MobileControls.MobileControl, "MobileControlDesigner.Initialize - Invalid MobileControl Control"); base.Initialize(component); _mobileControl = (System.Web.UI.MobileControls.MobileControl) component; } protected virtual void SetStyleAttributes() { //Debug.Assert(Behavior != null, "Behavior is null, Load completed? " + LoadComplete.ToString()); DesignerAdapterUtil.SetStandardStyleAttributes(Behavior, ContainmentStatus); } public override void OnComponentChanged(Object sender, ComponentChangedEventArgs ce) { // Delegate to the base class implementation first! base.OnComponentChanged(sender, ce); MemberDescriptor member = ce.Member; if (member != null && member.GetType().FullName.Equals(Constants.ReflectPropertyDescriptorTypeFullName)) { PropertyDescriptor propDesc = (PropertyDescriptor)member; String propName = propDesc.Name; if ((_mobileControl is TextControl || _mobileControl is TextView) && propName.Equals("Text")) { _mobileControl.Controls.Clear(); } } } /// <summary> /// <para> /// Notification that is called when the associated control is parented. /// </para> /// </summary> public override void OnSetParent() { base.OnSetParent(); _containmentStatusDirty = true; if (LoadComplete) { UpdateRendering(); } } protected override void PreFilterProperties(IDictionary properties) { base.PreFilterProperties(properties); properties[_appliedDeviceFiltersPropName] = TypeDescriptor.CreateProperty(this.GetType(), _appliedDeviceFiltersPropName, typeof(String)); properties[_propertyOverridesPropName] = TypeDescriptor.CreateProperty(this.GetType(), _propertyOverridesPropName, typeof(String)); foreach (string propertyName in _nonBrowsableProperties) { PropertyDescriptor property = (PropertyDescriptor) properties[propertyName]; Debug.Assert(property != null, "Property is null: " + propertyName); if (property != null) { properties[propertyName] = TypeDescriptor.CreateProperty(this.GetType(), property, BrowsableAttribute.No); } } } /* * IMobileDesigner INTERFACE IMPLEMENTATION */ /// <summary> /// /// </summary> public void UpdateRendering() { _mobileControl.RefreshStyle(); UpdateDesignTimeHtml(); } //////////////////////////////////////////////////////////////////////// // Begin IDeviceSpecificDesigner Implementation //////////////////////////////////////////////////////////////////////// void IDeviceSpecificDesigner.SetDeviceSpecificEditor (IRefreshableDeviceSpecificEditor editor) { } String IDeviceSpecificDesigner.CurrentDeviceSpecificID { get { return _defaultDeviceSpecificIdentifier; } } System.Windows.Forms.Control IDeviceSpecificDesigner.Header { get { return _header; } } System.Web.UI.Control IDeviceSpecificDesigner.UnderlyingControl { get { return _mobileControl; } } Object IDeviceSpecificDesigner.UnderlyingObject { get { return _mobileControl; } } void IDeviceSpecificDesigner.InitHeader(int mergingContext) { HeaderPanel panel = new HeaderPanel(); HeaderLabel lblDescription = new HeaderLabel(); lblDescription.TabIndex = 0; lblDescription.Text = SR.GetString( SR.MobileControl_SettingGenericChoiceDescription ); panel.Height = lblDescription.Height; panel.Width = lblDescription.Width; panel.Controls.Add(lblDescription); _header = panel; } void IDeviceSpecificDesigner.RefreshHeader(int mergingContext) { } bool IDeviceSpecificDesigner.GetDeviceSpecific(String deviceSpecificParentID, out DeviceSpecific ds) { Debug.Assert(_defaultDeviceSpecificIdentifier == deviceSpecificParentID); ds = ((MobileControl) _mobileControl).DeviceSpecific; return true; } void IDeviceSpecificDesigner.SetDeviceSpecific(String deviceSpecificParentID, DeviceSpecific ds) { Debug.Assert(_defaultDeviceSpecificIdentifier == deviceSpecificParentID); if (null != ds) { ds.SetOwner((MobileControl) _mobileControl); } _mobileControl.DeviceSpecific = ds; } void IDeviceSpecificDesigner.UseCurrentDeviceSpecificID() { } //////////////////////////////////////////////////////////////////////// // End IDeviceSpecificDesigner Implementation //////////////////////////////////////////////////////////////////////// } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Management.Automation; using System.Management.Automation.Internal; using System.Collections; using System.Collections.Generic; using System.Text; using System.Diagnostics.CodeAnalysis; #if CORECLR // Used for 'IsAssignableFrom' which is not available under 'Type' in CoreClR but provided // as an extenstion method in 'System.Reflection.TypeExtensions' using System.Reflection; #endif namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// normalized parameter class to be constructed from the command line parameters /// using the metadata information provided by an instance of CommandParameterDefinition /// it's basically the hash table with the normalized values /// </summary> internal class MshParameter { internal Hashtable hash = null; internal object GetEntry(string key) { if (this.hash.ContainsKey(key)) return this.hash[key]; return AutomationNull.Value; } } internal class NameEntryDefinition : HashtableEntryDefinition { internal const string NameEntryKey = "name"; internal NameEntryDefinition() : base(NameEntryKey, new string[] { FormatParameterDefinitionKeys.LabelEntryKey }, new Type[] { typeof(string) }, false) { } } /// <summary> /// metadata base class for hashtable entry definitions /// it contains the key name and the allowable types /// it also provides hooks for type expansion /// </summary> internal class HashtableEntryDefinition { internal HashtableEntryDefinition(string name, IEnumerable<string> secondaryNames, Type[] types, bool mandatory) : this(name, types, mandatory) { SecondaryNames = secondaryNames; } internal HashtableEntryDefinition(string name, Type[] types, bool mandatory) { KeyName = name; AllowedTypes = types; Mandatory = mandatory; } internal HashtableEntryDefinition(string name, Type[] types) : this(name, types, false) { } internal virtual Hashtable CreateHashtableFromSingleType(object val) { // NOTE: must override for the default type(s) entry // this entry will have to expand the object into a hash table throw PSTraceSource.NewNotSupportedException(); } internal bool IsKeyMatch(string key) { if (CommandParameterDefinition.FindPartialMatch(key, this.KeyName)) { return true; } if (this.SecondaryNames != null) { foreach (string secondaryKey in this.SecondaryNames) { if (CommandParameterDefinition.FindPartialMatch(key, secondaryKey)) { return true; } } } return false; } internal virtual object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable) { return null; } internal virtual object ComputeDefaultValue() { return AutomationNull.Value; } internal string KeyName { get; } internal Type[] AllowedTypes { get; } internal bool Mandatory { get; } internal IEnumerable<string> SecondaryNames { get; } } /// <summary> /// metadata abstract base class to contain hash entries definitions /// </summary> internal abstract class CommandParameterDefinition { [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] internal CommandParameterDefinition() { SetEntries(); } protected abstract void SetEntries(); internal virtual MshParameter CreateInstance() { return new MshParameter(); } /// <summary> /// for a key name, verify it is a legal entry: /// 1. it must match (partial match allowed) /// 2. it must be unambiguous (if partial match) /// If an error condition occurs, an exception will be thrown /// </summary> /// <param name="keyName">key to verify</param> /// <param name="invocationContext">invocation context for error reporting</param> /// <returns>matching hash table entry</returns> /// <exception cref="ArgumentException"></exception> internal HashtableEntryDefinition MatchEntry(string keyName, TerminatingErrorContext invocationContext) { if (string.IsNullOrEmpty(keyName)) PSTraceSource.NewArgumentNullException("keyName"); HashtableEntryDefinition matchingEntry = null; for (int k = 0; k < this.hashEntries.Count; k++) { if (this.hashEntries[k].IsKeyMatch(keyName)) { // we have a match if (matchingEntry == null) { // this is the first match, we save the entry // and we keep going for ambiguity check matchingEntry = this.hashEntries[k]; } else { // we already had a match, we have an ambiguous key ProcessAmbiguousKey(invocationContext, keyName, matchingEntry, this.hashEntries[k]); } } } if (matchingEntry != null) { // we found an unambiguous match return matchingEntry; } // we did not have a match ProcessIllegalKey(invocationContext, keyName); return null; } internal static bool FindPartialMatch(string key, string normalizedKey) { if (key.Length < normalizedKey.Length) { // shorter, could be an abbreviation if (string.Equals(key, normalizedKey.Substring(0, key.Length), StringComparison.OrdinalIgnoreCase)) { // found abbreviation return true; } } if (string.Equals(key, normalizedKey, StringComparison.OrdinalIgnoreCase)) { // found full match return true; } return false; } #region Error Processing private static void ProcessAmbiguousKey(TerminatingErrorContext invocationContext, string keyName, HashtableEntryDefinition matchingEntry, HashtableEntryDefinition currentEntry) { string msg = StringUtil.Format(FormatAndOut_MshParameter.AmbiguousKeyError, keyName, matchingEntry.KeyName, currentEntry.KeyName); ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyAmbiguous", msg); } private static void ProcessIllegalKey(TerminatingErrorContext invocationContext, string keyName) { string msg = StringUtil.Format(FormatAndOut_MshParameter.IllegalKeyError, keyName); ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyIllegal", msg); } #endregion internal List<HashtableEntryDefinition> hashEntries = new List<HashtableEntryDefinition>(); } /// <summary> /// engine to process a generic object[] from the command line and /// generate a list of MshParameter objects , given the metadata provided by /// a class derived from CommandParameterDefinition /// </summary> internal sealed class ParameterProcessor { #region tracer [TraceSource("ParameterProcessor", "ParameterProcessor")] internal static PSTraceSource tracer = PSTraceSource.GetTracer("ParameterProcessor", "ParameterProcessor"); #endregion tracer internal static void ThrowParameterBindingException(TerminatingErrorContext invocationContext, string errorId, string msg) { ErrorRecord errorRecord = new ErrorRecord( new NotSupportedException(), errorId, ErrorCategory.InvalidArgument, null); errorRecord.ErrorDetails = new ErrorDetails(msg); invocationContext.ThrowTerminatingError(errorRecord); } internal ParameterProcessor(CommandParameterDefinition p) { _paramDef = p; } /// <exception cref="ArgumentException"></exception> internal List<MshParameter> ProcessParameters(object[] p, TerminatingErrorContext invocationContext) { if (p == null || p.Length == 0) return null; List<MshParameter> retVal = new List<MshParameter>(); MshParameter currParam; bool originalParameterWasHashTable = false; for (int k = 0; k < p.Length; k++) { // we always copy into a fresh hash table currParam = _paramDef.CreateInstance(); var actualObject = PSObject.Base(p[k]); if (actualObject is IDictionary) { originalParameterWasHashTable = true; currParam.hash = VerifyHashTable((IDictionary)actualObject, invocationContext); } else if ((actualObject != null) && MatchesAllowedTypes(actualObject.GetType(), _paramDef.hashEntries[0].AllowedTypes)) { // a simple type was specified, build a hash with one entry currParam.hash = _paramDef.hashEntries[0].CreateHashtableFromSingleType(actualObject); } else { // unknown type, error // provide error message (the user did not enter a hash table) ProcessUnknownParameterType(invocationContext, actualObject, _paramDef.hashEntries[0].AllowedTypes); } // value range validation and post processing on the hash table VerifyAndNormalizeParameter(currParam, invocationContext, originalParameterWasHashTable); retVal.Add(currParam); } return retVal; } private static bool MatchesAllowedTypes(Type t, Type[] allowedTypes) { for (int k = 0; k < allowedTypes.Length; k++) { if (allowedTypes[k].IsAssignableFrom(t)) return true; } return false; } /// <exception cref="ArgumentException"></exception> private Hashtable VerifyHashTable(IDictionary hash, TerminatingErrorContext invocationContext) { // full blown hash, need to: // 1. verify names(keys) and expand names if there are partial matches // 2. verify value types Hashtable retVal = new Hashtable(); foreach (DictionaryEntry e in hash) { if (e.Key == null) { ProcessNullHashTableKey(invocationContext); } string currentStringKey = e.Key as string; if (currentStringKey == null) { ProcessNonStringHashTableKey(invocationContext, e.Key); } // find a match for the key HashtableEntryDefinition def = _paramDef.MatchEntry(currentStringKey, invocationContext); if (retVal.Contains(def.KeyName)) { // duplicate key error ProcessDuplicateHashTableKey(invocationContext, currentStringKey, def.KeyName); } // now the key is verified, need to check the type bool matchType = false; if (def.AllowedTypes == null || def.AllowedTypes.Length == 0) { // we match on any type, it will be up to the entry to further check matchType = true; } else { for (int t = 0; t < def.AllowedTypes.Length; t++) { if (e.Value == null) { ProcessMissingKeyValue(invocationContext, currentStringKey); } if (def.AllowedTypes[t].IsAssignableFrom(e.Value.GetType())) { matchType = true; break; } } } if (!matchType) { // bad type error ProcessIllegalHashTableKeyValue(invocationContext, currentStringKey, e.Value.GetType(), def.AllowedTypes); } retVal.Add(def.KeyName, e.Value); } return retVal; } /// <exception cref="ArgumentException"></exception> private void VerifyAndNormalizeParameter(MshParameter parameter, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable) { for (int k = 0; k < _paramDef.hashEntries.Count; k++) { if (parameter.hash.ContainsKey(_paramDef.hashEntries[k].KeyName)) { // we have a key, just do some post processing normalization // retrieve the value object val = parameter.hash[_paramDef.hashEntries[k].KeyName]; object newVal = _paramDef.hashEntries[k].Verify(val, invocationContext, originalParameterWasHashTable); if (newVal != null) { // if a new value is provided, we need to update the hash entry parameter.hash[_paramDef.hashEntries[k].KeyName] = newVal; } } else { // we do not have the key, we might want to have a default value object defaultValue = _paramDef.hashEntries[k].ComputeDefaultValue(); if (defaultValue != AutomationNull.Value) { // we have a default value, add it parameter.hash[_paramDef.hashEntries[k].KeyName] = defaultValue; } else if (_paramDef.hashEntries[k].Mandatory) { // no default value and mandatory: we cannot proceed ProcessMissingMandatoryKey(invocationContext, _paramDef.hashEntries[k].KeyName); } } } } #region Error Processing private static void ProcessUnknownParameterType(TerminatingErrorContext invocationContext, object actualObject, Type[] allowedTypes) { string allowedTypesList = CatenateTypeArray(allowedTypes); string msg; if (actualObject != null) { msg = StringUtil.Format(FormatAndOut_MshParameter.UnknownParameterTypeError, actualObject.GetType().FullName, allowedTypesList); } else { msg = StringUtil.Format(FormatAndOut_MshParameter.NullParameterTypeError, allowedTypesList); } ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyUnknownType", msg); } private static void ProcessDuplicateHashTableKey(TerminatingErrorContext invocationContext, string duplicateKey, string existingKey) { string msg = StringUtil.Format(FormatAndOut_MshParameter.DuplicateKeyError, duplicateKey, existingKey); ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyDuplicate", msg); } private static void ProcessNullHashTableKey(TerminatingErrorContext invocationContext) { string msg = StringUtil.Format(FormatAndOut_MshParameter.DictionaryKeyNullError); ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyNull", msg); } private static void ProcessNonStringHashTableKey(TerminatingErrorContext invocationContext, object key) { string msg = StringUtil.Format(FormatAndOut_MshParameter.DictionaryKeyNonStringError, key.GetType().Name); ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyNonString", msg); } private static void ProcessIllegalHashTableKeyValue(TerminatingErrorContext invocationContext, string key, Type actualType, Type[] allowedTypes) { string msg; string errorID; if (allowedTypes.Length > 1) { string legalTypes = CatenateTypeArray(allowedTypes); msg = StringUtil.Format(FormatAndOut_MshParameter.IllegalTypeMultiError, key, actualType.FullName, legalTypes ); errorID = "DictionaryKeyIllegalValue1"; } else { msg = StringUtil.Format(FormatAndOut_MshParameter.IllegalTypeSingleError, key, actualType.FullName, allowedTypes[0] ); errorID = "DictionaryKeyIllegalValue2"; } ParameterProcessor.ThrowParameterBindingException(invocationContext, errorID, msg); } private static void ProcessMissingKeyValue(TerminatingErrorContext invocationContext, string keyName) { string msg = StringUtil.Format(FormatAndOut_MshParameter.MissingKeyValueError, keyName); ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyMissingValue", msg); } private static void ProcessMissingMandatoryKey(TerminatingErrorContext invocationContext, string keyName) { string msg = StringUtil.Format(FormatAndOut_MshParameter.MissingKeyMandatoryEntryError, keyName); ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyMandatoryEntry", msg); } #endregion #region Utilities private static string CatenateTypeArray(Type[] arr) { string[] strings = new string[arr.Length]; for (int k = 0; k < arr.Length; k++) { strings[k] = arr[k].FullName; } return CatenateStringArray(strings); } internal static string CatenateStringArray(string[] arr) { StringBuilder sb = new StringBuilder(); sb.Append("{"); for (int k = 0; k < arr.Length; k++) { if (k > 0) { sb.Append(", "); } sb.Append(arr[k]); } sb.Append("}"); return sb.ToString(); } #endregion private CommandParameterDefinition _paramDef = null; } }
#region License // // RegistryStrategy.cs January 2010 // // Copyright (C) 2010, Niall Gallagher <niallg@users.sf.net> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // #endregion #region Using directives using SimpleFramework.Xml.Strategy; using SimpleFramework.Xml.Stream; using System.Collections.Generic; using System; #endregion namespace SimpleFramework.Xml.Util { /// <summary> /// The <c>RegistryStrategy</c> object is used to intercept /// the serialization process and delegate to custom converters. The /// custom converters are resolved from a <c>Registry</c> /// object, which is provided to the constructor. If there is no /// binding for a particular object then serialization is delegated /// to an internal strategy. All converters resolved by this are /// instantiated once and cached internally for performance. /// <p> /// By default the <c>TreeStrategy</c> is used to perform the /// normal serialization process should there be no class binding /// specifying a converter to use. However, any implementation can /// be used, including the <c>CycleStrategy</c>, which handles /// cycles in the object graph. To specify the internal strategy to /// use it can be provided in the constructor. /// </summary> /// <seealso> /// SimpleFramework.Xml.Util.Registry /// </seealso> public class RegistryStrategy : Strategy { /// <summary> /// This is the registry that is used to resolve bindings. /// </summary> private readonly Registry registry; /// <summary> /// This is the strategy used if there is no bindings. /// </summary> private readonly Strategy strategy; /// <summary> /// Constructor for the <c>RegistryStrategy</c> object. This /// is used to create a strategy that will intercept the normal /// serialization process by searching for bindings within the /// provided <c>Registry</c> instance. /// </summary> /// <param name="registry"> /// this is the registry instance with bindings /// </param> public RegistryStrategy(Registry registry) { this(registry, new TreeStrategy()); } /// <summary> /// Constructor for the <c>RegistryStrategy</c> object. This /// is used to create a strategy that will intercept the normal /// serialization process by searching for bindings within the /// provided <c>Registry</c> instance. /// </summary> /// <param name="registry"> /// this is the registry instance with bindings /// </param> /// <param name="strategy"> /// this is the strategy to delegate to /// </param> public RegistryStrategy(Registry registry, Strategy strategy){ this.registry = registry; this.strategy = strategy; } /// <summary> /// This is used to read the <c>Value</c> which will be used /// to represent the deserialized object. If there is an binding /// present then the value will contain an object instance. If it /// does not then it is up to the internal strategy to determine /// what the returned value contains. /// </summary> /// <param name="type"> /// this is the type that represents a method or field /// </param> /// <param name="node"> /// this is the node representing the XML element /// </param> /// <param name="map"> /// this is the session map that contain variables /// </param> /// <returns> /// the value representing the deserialized value /// </returns> public Value Read(Type type, NodeMap<InputNode> node, Dictionary map) { Value value = strategy.Read(type, node, map); if(IsReference(value)) { return value; } return Read(type, node, value); } /// <summary> /// This is used to read the <c>Value</c> which will be used /// to represent the deserialized object. If there is an binding /// present then the value will contain an object instance. If it /// does not then it is up to the internal strategy to determine /// what the returned value contains. /// </summary> /// <param name="type"> /// this is the type that represents a method or field /// </param> /// <param name="node"> /// this is the node representing the XML element /// </param> /// <param name="value"> /// this is the value from the internal strategy /// </param> /// <returns> /// the value representing the deserialized value /// </returns> public Value Read(Type type, NodeMap<InputNode> node, Value value) { Converter converter = Lookup(type, value); InputNode source = node.getNode(); if(converter != null) { Object data = converter.Read(source); if(value != null) { value.setValue(data); } return new Reference(value, data); } return value; } /// <summary> /// This is used to serialize a representation of the object value /// provided. If there is a <c>Registry</c> binding present /// for the provided type then this will use the converter specified /// to serialize a representation of the object. If however there /// is no binding present then this will delegate to the internal /// strategy. This returns true if the serialization has completed. /// </summary> /// <param name="type"> /// this is the type that represents the field or method /// </param> /// <param name="value"> /// this is the object instance to be serialized /// </param> /// <param name="node"> /// this is the XML element to be serialized to /// </param> /// <param name="map"> /// this is the session map used by the serializer /// </param> /// <returns> /// this returns true if it was serialized, false otherwise /// </returns> public bool Write(Type type, Object value, NodeMap<OutputNode> node, Dictionary map) { bool reference = strategy.Write(type, value, node, map); if(!reference) { return Write(type, value, node); } return reference; } /// <summary> /// This is used to serialize a representation of the object value /// provided. If there is a <c>Registry</c> binding present /// for the provided type then this will use the converter specified /// to serialize a representation of the object. If however there /// is no binding present then this will delegate to the internal /// strategy. This returns true if the serialization has completed. /// </summary> /// <param name="type"> /// this is the type that represents the field or method /// </param> /// <param name="value"> /// this is the object instance to be serialized /// </param> /// <param name="node"> /// this is the XML element to be serialized to /// </param> /// <returns> /// this returns true if it was serialized, false otherwise /// </returns> public bool Write(Type type, Object value, NodeMap<OutputNode> node) { Converter converter = Lookup(type, value); OutputNode source = node.getNode(); if(converter != null) { converter.Write(source, value); return true; } return false; } /// <summary> /// This is used to acquire a <c>Converter</c> instance for /// the provided value object. The value object is used to resolve /// the converter to use for the serialization process. /// </summary> /// <param name="type"> /// this is the type representing the field or method /// </param> /// <param name="value"> /// this is the value that is to be serialized /// </param> /// <returns> /// this returns the converter instance that is matched /// </returns> public Converter Lookup(Type type, Value value) { Class real = type.getType(); if(value != null) { real = value.getType(); } return registry.Lookup(real); } /// <summary> /// This is used to acquire a <c>Converter</c> instance for /// the provided object instance. The instance class is used to /// resolve the converter to use for the serialization process. /// </summary> /// <param name="type"> /// this is the type representing the field or method /// </param> /// <param name="value"> /// this is the value that is to be serialized /// </param> /// <returns> /// this returns the converter instance that is matched /// </returns> public Converter Lookup(Type type, Object value) { Class real = type.getType(); if(value != null) { real = value.getClass(); } return registry.Lookup(real); } /// <summary> /// This is used to determine if the <c>Value</c> provided /// represents a reference. If it does represent a reference then /// this will return true, if it does not then this returns false. /// </summary> /// <param name="value"> /// this is the value instance to be evaluated /// </param> /// <returns> /// this returns true if the value represents a reference /// </returns> public bool IsReference(Value value) { return value != null && value.IsReference(); } } }