context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Packets; using QuantConnect.Queues; using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.DataFeeds.Enumerators; namespace QuantConnect.Tests.Engine.DataFeeds { [TestFixture] public class DataQueueHandlerManagerTests { [TestCase("TradierBrokerage")] [TestCase("QuantConnect.Brokerages.InteractiveBrokers.InteractiveBrokersBrokerage")] [TestCase("OandaBrokerage")] [TestCase("GDAXDataQueueHandler")] [TestCase("BitfinexBrokerage")] public void GetFactoryFromDataQueueHandler(string dataQueueHandler) { var factory = JobQueue.GetFactoryFromDataQueueHandler(dataQueueHandler); Assert.NotNull(factory); } [Test] public void SetJob() { //Array IDQH var dataHandlers = Newtonsoft.Json.JsonConvert.SerializeObject(new[] { "FakeDataQueue" }); var jobWithArrayIDQH = new LiveNodePacket { Brokerage = "OandaBrokerage", DataQueueHandler = dataHandlers }; var compositeDataQueueHandler = new DataQueueHandlerManager(); compositeDataQueueHandler.SetJob(jobWithArrayIDQH); compositeDataQueueHandler.Dispose(); } [Test] public void SubscribeReturnsNull() { var compositeDataQueueHandler = new DataQueueHandlerManager(); var enumerator = compositeDataQueueHandler.Subscribe(GetConfig(), (_, _) => {}); Assert.Null(enumerator); compositeDataQueueHandler.Dispose(); } [Test] public void SubscribeReturnsNotNull() { var dataHandlers = Newtonsoft.Json.JsonConvert.SerializeObject(new[] { "FakeDataQueue" }); var job = new LiveNodePacket { Brokerage = "OandaBrokerage", DataQueueHandler = dataHandlers }; var compositeDataQueueHandler = new DataQueueHandlerManager(); compositeDataQueueHandler.SetJob(job); var enumerator = compositeDataQueueHandler.Subscribe(GetConfig(), (_, _) => {}); Assert.NotNull(enumerator); compositeDataQueueHandler.Dispose(); enumerator.Dispose(); } [Test] public void Unsubscribe() { var compositeDataQueueHandler = new DataQueueHandlerManager(); compositeDataQueueHandler.Unsubscribe(GetConfig()); compositeDataQueueHandler.Dispose(); } [Test] public void IsNotUniverseProvider() { var compositeDataQueueHandler = new DataQueueHandlerManager(); Assert.IsFalse(compositeDataQueueHandler.HasUniverseProvider); Assert.Throws<NotSupportedException>(() => compositeDataQueueHandler.LookupSymbols(Symbols.ES_Future_Chain, false)); Assert.Throws<NotSupportedException>(() => compositeDataQueueHandler.CanPerformSelection()); compositeDataQueueHandler.Dispose(); } [Test] public void DoubleSubscribe() { var compositeDataQueueHandler = new DataQueueHandlerManager(); compositeDataQueueHandler.SetJob(new LiveNodePacket { Brokerage = "OandaBrokerage", DataQueueHandler = "[ \"TestDataHandler\" ]" }); var dataConfig = GetConfig(); var enumerator = compositeDataQueueHandler.Subscribe(dataConfig, (_, _) => {}); Assert.Throws<ArgumentException>(() => compositeDataQueueHandler.Subscribe(dataConfig, (_, _) => { })); compositeDataQueueHandler.Dispose(); } [Test] public void SingleSubscribe() { TestDataHandler.UnsubscribeCounter = 0; var compositeDataQueueHandler = new DataQueueHandlerManager(); compositeDataQueueHandler.SetJob(new LiveNodePacket { Brokerage = "OandaBrokerage", DataQueueHandler = "[ \"TestDataHandler\" ]" }); var dataConfig = GetConfig(); var enumerator = compositeDataQueueHandler.Subscribe(dataConfig, (_, _) => {}); compositeDataQueueHandler.Unsubscribe(dataConfig); compositeDataQueueHandler.Unsubscribe(dataConfig); compositeDataQueueHandler.Unsubscribe(dataConfig); Assert.AreEqual(1, TestDataHandler.UnsubscribeCounter); compositeDataQueueHandler.Dispose(); } [TestCase(false)] [TestCase(true)] public void MappedConfig(bool canonicalUnsubscribeFirst) { TestDataHandler.UnsubscribeCounter = 0; TestDataHandler.SubscribeCounter = 0; var compositeDataQueueHandler = new DataQueueHandlerManager(); compositeDataQueueHandler.SetJob(new LiveNodePacket { Brokerage = "OandaBrokerage", DataQueueHandler = "[ \"TestDataHandler\" ]" }); var canonicalSymbol = Symbols.ES_Future_Chain.UpdateMappedSymbol(Symbols.Future_ESZ18_Dec2018.ID.ToString()); var canonicalConfig = GetConfig(canonicalSymbol); var contractConfig = GetConfig(Symbols.Future_ESZ18_Dec2018); var enumerator = new LiveSubscriptionEnumerator(canonicalConfig, compositeDataQueueHandler, (_, _) => {}); var enumerator2 = new LiveSubscriptionEnumerator(contractConfig, compositeDataQueueHandler, (_, _) => {}); var firstUnsubscribe = canonicalUnsubscribeFirst ? canonicalConfig : contractConfig; var secondUnsubscribe = canonicalUnsubscribeFirst ? contractConfig : canonicalConfig; Assert.AreEqual(2, TestDataHandler.SubscribeCounter); compositeDataQueueHandler.UnsubscribeWithMapping(firstUnsubscribe); Assert.AreEqual(1, TestDataHandler.UnsubscribeCounter); compositeDataQueueHandler.UnsubscribeWithMapping(secondUnsubscribe); Assert.AreEqual(2, TestDataHandler.UnsubscribeCounter); enumerator.Dispose(); enumerator2.Dispose(); compositeDataQueueHandler.Dispose(); } private static SubscriptionDataConfig GetConfig(Symbol symbol = null) { return new SubscriptionDataConfig(typeof(TradeBar), symbol ?? Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, false, false, false, false, TickType.Trade, false); } private class TestDataHandler : IDataQueueHandler { public static int SubscribeCounter { get; set; } public static int UnsubscribeCounter { get; set; } public void Dispose() { } public IEnumerator<BaseData> Subscribe(SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler) { SubscribeCounter++; return Enumerable.Empty<BaseData>().GetEnumerator(); } public void Unsubscribe(SubscriptionDataConfig dataConfig) { UnsubscribeCounter++; } public void SetJob(LiveNodePacket job) { } public bool IsConnected { get; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/field_mask.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class FieldMaskReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/field_mask.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static FieldMaskReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiBnb29nbGUvcHJvdG9idWYvZmllbGRfbWFzay5wcm90bxIPZ29vZ2xlLnBy", "b3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUJRChNjb20uZ29v", "Z2xlLnByb3RvYnVmQg5GaWVsZE1hc2tQcm90b1ABoAEBogIDR1BCqgIeR29v", "Z2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.FieldMask), global::Google.Protobuf.WellKnownTypes.FieldMask.Parser, new[]{ "Paths" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// `FieldMask` represents a set of symbolic field paths, for example: /// /// paths: "f.a" /// paths: "f.b.d" /// /// Here `f` represents a field in some root message, `a` and `b` /// fields in the message found in `f`, and `d` a field found in the /// message in `f.b`. /// /// Field masks are used to specify a subset of fields that should be /// returned by a get operation or modified by an update operation. /// Field masks also have a custom JSON encoding (see below). /// /// # Field Masks in Projections /// /// When used in the context of a projection, a response message or /// sub-message is filtered by the API to only contain those fields as /// specified in the mask. For example, if the mask in the previous /// example is applied to a response message as follows: /// /// f { /// a : 22 /// b { /// d : 1 /// x : 2 /// } /// y : 13 /// } /// z: 8 /// /// The result will not contain specific values for fields x,y and z /// (there value will be set to the default, and omitted in proto text /// output): /// /// f { /// a : 22 /// b { /// d : 1 /// } /// } /// /// A repeated field is not allowed except at the last position of a /// field mask. /// /// If a FieldMask object is not present in a get operation, the /// operation applies to all fields (as if a FieldMask of all fields /// had been specified). /// /// Note that a field mask does not necessarily applies to the /// top-level response message. In case of a REST get operation, the /// field mask applies directly to the response, but in case of a REST /// list operation, the mask instead applies to each individual message /// in the returned resource list. In case of a REST custom method, /// other definitions may be used. Where the mask applies will be /// clearly documented together with its declaration in the API. In /// any case, the effect on the returned resource/resources is required /// behavior for APIs. /// /// # Field Masks in Update Operations /// /// A field mask in update operations specifies which fields of the /// targeted resource are going to be updated. The API is required /// to only change the values of the fields as specified in the mask /// and leave the others untouched. If a resource is passed in to /// describe the updated values, the API ignores the values of all /// fields not covered by the mask. /// /// In order to reset a field's value to the default, the field must /// be in the mask and set to the default value in the provided resource. /// Hence, in order to reset all fields of a resource, provide a default /// instance of the resource and set all fields in the mask, or do /// not provide a mask as described below. /// /// If a field mask is not present on update, the operation applies to /// all fields (as if a field mask of all fields has been specified). /// Note that in the presence of schema evolution, this may mean that /// fields the client does not know and has therefore not filled into /// the request will be reset to their default. If this is unwanted /// behavior, a specific service may require a client to always specify /// a field mask, producing an error if not. /// /// As with get operations, the location of the resource which /// describes the updated values in the request message depends on the /// operation kind. In any case, the effect of the field mask is /// required to be honored by the API. /// /// ## Considerations for HTTP REST /// /// The HTTP kind of an update operation which uses a field mask must /// be set to PATCH instead of PUT in order to satisfy HTTP semantics /// (PUT must only be used for full updates). /// /// # JSON Encoding of Field Masks /// /// In JSON, a field mask is encoded as a single string where paths are /// separated by a comma. Fields name in each path are converted /// to/from lower-camel naming conventions. /// /// As an example, consider the following message declarations: /// /// message Profile { /// User user = 1; /// Photo photo = 2; /// } /// message User { /// string display_name = 1; /// string address = 2; /// } /// /// In proto a field mask for `Profile` may look as such: /// /// mask { /// paths: "user.display_name" /// paths: "photo" /// } /// /// In JSON, the same mask is represented as below: /// /// { /// mask: "user.displayName,photo" /// } /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class FieldMask : pb::IMessage<FieldMask> { private static readonly pb::MessageParser<FieldMask> _parser = new pb::MessageParser<FieldMask>(() => new FieldMask()); public static pb::MessageParser<FieldMask> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public FieldMask() { OnConstruction(); } partial void OnConstruction(); public FieldMask(FieldMask other) : this() { paths_ = other.paths_.Clone(); } public FieldMask Clone() { return new FieldMask(this); } /// <summary>Field number for the "paths" field.</summary> public const int PathsFieldNumber = 1; private static readonly pb::FieldCodec<string> _repeated_paths_codec = pb::FieldCodec.ForString(10); private readonly pbc::RepeatedField<string> paths_ = new pbc::RepeatedField<string>(); /// <summary> /// The set of field mask paths. /// </summary> public pbc::RepeatedField<string> Paths { get { return paths_; } } public override bool Equals(object other) { return Equals(other as FieldMask); } public bool Equals(FieldMask other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!paths_.Equals(other.paths_)) return false; return true; } public override int GetHashCode() { int hash = 1; hash ^= paths_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { paths_.WriteTo(output, _repeated_paths_codec); } public int CalculateSize() { int size = 0; size += paths_.CalculateSize(_repeated_paths_codec); return size; } public void MergeFrom(FieldMask other) { if (other == null) { return; } paths_.Add(other.paths_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { paths_.AddEntriesFrom(input, _repeated_paths_codec); break; } } } } } #endregion } #endregion Designer generated code
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract001.abstract001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract001.abstract001; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> abstract public class Base { public abstract int Foo(dynamic o); } public class Derived : Base { public override int Foo(object o) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(2); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract002.abstract002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract002.abstract002; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> abstract public class Base { public abstract int Foo(dynamic o); } public class Derived : Base { public override int Foo(object o) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base d = new Derived(); d.Foo(2); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract003.abstract003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract003.abstract003; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public interface IFoo { void Foo(); } abstract public class Base { public abstract int Foo(dynamic o); } public class Derived : Base, IFoo { void IFoo.Foo() { Test.Status = 2; } public override int Foo(object o) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); IFoo x = d as IFoo; d.Foo(2); if (Test.Status != 1) return 1; x.Foo(); if (Test.Status != 2) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract004.abstract004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract004.abstract004; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> abstract public class Base { public abstract int Foo(object o); } public class Derived : Base { public override int Foo(dynamic o) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(2); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract005.abstract005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract005.abstract005; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> abstract public class Base { public abstract int Foo(dynamic o); } public class Derived : Base { public override int Foo(dynamic o) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(2); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual001.virtual001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual001.virtual001; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int Foo(object o) { Test.Status = 2; return 1; } } public class Derived : Base { public override int Foo(dynamic d) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(3); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual002.virtual002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual002.virtual002; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int Foo(dynamic o) { Test.Status = 2; return 1; } } public class Derived : Base { public override int Foo(object d) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(3); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual003.virtual003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual003.virtual003; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int Foo(dynamic o) { Test.Status = 2; return 1; } } public class Derived : Base { public override int Foo(dynamic d) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(3); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual004.virtual004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual004.virtual004; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int Foo(object o) { Test.Status = 3; return 1; } } public class Derived : Base { public override int Foo(dynamic d) { Test.Status = 2; return 1; } } public class FurtherDerived : Derived { public override int Foo(object d) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { FurtherDerived d = new FurtherDerived(); d.Foo(3); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual005.virtual005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual005.virtual005; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int Foo(dynamic o) { Test.Status = 3; return 1; } } public class Derived : Base { public override int Foo(object d) { Test.Status = 2; return 1; } } public class FurtherDerived : Derived { public override int Foo(dynamic d) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { FurtherDerived d = new FurtherDerived(); d.Foo(3); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual006.virtual006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual006.virtual006; // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int this[object o] { get { Test.Status = 2; return 2; } } } public class Derived : Base { public override int this[dynamic d] { get { Test.Status = 1; return 1; } } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); int x = d[3]; if (Test.Status != 1 || x != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename001.simplename001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename001.simplename001; // <Title>Classes - Simple Name (Method) Calling</Title> // <Description> ICE </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> namespace NS { public class C { public static int Bar(C t) { return 1; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v2 = new C(); return (1 == Bar(v2)) ? 0 : 1; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename003.simplename003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename003.simplename003; // <Title>Classes - Simple Name (Method) Calling</Title> // <Description> </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> namespace NS { abstract public class Base { protected static int result = 0; public static bool Bar(object o) { result = 1; return false; } public abstract int Foo(dynamic o); public virtual int Hoo(object o) { return 0; } public virtual int Poo(int n, dynamic o) { return 0; } } public class Derived : Base { public override int Foo(object o) { result = 2; return 0; } public new int Hoo(dynamic o) { result = 3; return 0; } public sealed override int Poo(int n, dynamic o) { result = 4; return 0; } public bool RunTest() { bool ret = true; dynamic d = new Derived(); Bar(d); ret &= (1 == result); Foo(d); ret &= (2 == result); Hoo(d); ret &= (3 == result); dynamic x = 100; Poo(x, d); ret &= (4 == result); return ret; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { var v = new Derived(); return v.RunTest() ? 0 : 1; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename004.simplename004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename004.simplename004; // <Title>Classes - Simple Name (Method) Calling</Title> // <Description> </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> namespace NS { public struct MyType { public static int Bar<T>(object o) { return 1; } public int Foo<U>(object p1, object p2) { return 2; } public int Har<V>(object o, params int[] ary) { return 3; } public int Poo<W>(object p1, ref object p2, out dynamic p3) { p3 = default(dynamic); return 4; } public int Dar<Y>(object p1, int p2 = 100, long p3 = 200) { return 5; } public bool RunTest() { bool ret = true; dynamic d = null; ret &= (1 == Bar<string>(d)); ret &= (2 == Foo<double>(d, d)); d = new MyType(); dynamic d1 = 999; ret &= (1 == Bar<float>(d)); ret &= (2 == Foo<ulong>(d, d1)); ret &= (3 == Har<long>(d)); ret &= (4 == Poo<short>(d, ref d1, out d1)); ret &= (3 == Har<long>(d, d1)); ret &= (5 == Dar<char>(d)); ret &= (5 == Dar<char>(d, p2: 100)); ret &= (5 == Dar<char>(d, p3: 99, p2: 88)); return ret; } } public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { var v = new MyType(); return v.RunTest() ? 0 : 1; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename005.simplename005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename005.simplename005; // <Title>Classes - Simple Name (Method) Calling</Title> // <Description> ICE </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> namespace NS1 { public delegate void MyDel01(object p1); public delegate void MyDel02(string p1); public delegate bool MyDel03(object p1, string p2); public delegate bool MyDel04(string p1, string p2); public delegate void MyDel05(string p1, out int p2, ref long p3); public delegate void MyDel06(object p1, out int p2, ref long p3); public delegate int MyDel07(int p1, int p2 = -1, int p3 = -2); public delegate int MyDel08(object p1, byte p2 = 101); public delegate int MyDel09(object p1, int p2 = 1, long p3 = 2); public class Test { private static int s_result = -1; public void MyMtd01(object p1) { s_result = 1; } public void MyMtd02(string p1) { s_result = 2; } public bool MyMtd03(object p1, string p2) { s_result = 3; return true; } public bool MyMtd04(string p1, string p2) { s_result = 4; return false; } public void MyMtd05(string p1, out int p2, ref long p3) { s_result = 5; p2 = -30; } public void MyMtd06(object p1, out int p2, ref long p3) { s_result = 6; p2 = -40; } public int MyMtd07(int p1, int p2 = -10, int p3 = -20) { s_result = 7; return p3; } public int MyMtd08(object p1, byte p2 = 99) { s_result = 8; return 1; } public int MyMtd09(object p1, int p2 = 10, long p3 = 20) { s_result = 9; return p2; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var t = new Test(); return (t.RunTest()) ? 0 : 1; } public bool RunTest() { dynamic v1 = new MyDel01(MyMtd01); dynamic d = null; dynamic d1 = "12345"; v1(d); bool ret = (1 == s_result); v1 = new MyDel02(MyMtd02); v1(d); ret &= (2 == s_result); v1 = new MyDel03(MyMtd03); v1(d, d1); ret &= (3 == s_result); v1 = new MyDel04(MyMtd04); v1(d, d1); ret &= (4 == s_result); d = 12345; v1 = new MyDel05(MyMtd05); //v1(d1, out d, ref d); // by design //ret &= (5 == result); v1 = new MyDel06(MyMtd06); //v1(d1, out d, ref d); //ret &= (6 == result); v1 = new MyDel07(MyMtd07); v1(d); ret &= (7 == s_result); s_result = -1; v1(d, p3: 100); ret &= (7 == s_result); s_result = -1; v1(d, p3: 100, p2: 200); ret &= (7 == s_result); d = null; v1 = new MyDel08(MyMtd08); v1(d); // ret &= (8 == s_result); v1 = new MyDel09(MyMtd09); v1(d); // ret &= (9 == s_result); return ret; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.memberaccess002.memberaccess002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.memberaccess002.memberaccess002; // <Title> Operator -.is, as</Title> // <Description>(By Design)</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class A { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic x = DayOfWeek.Monday; try { var y = x.value__; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) // Should not EX { System.Console.WriteLine(e); return 1; } return 0; } } //</Code> }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices { /// <summary> /// Provides a collection of methods for interoperating with <see cref="Memory{T}"/>, <see cref="ReadOnlyMemory{T}"/>, /// <see cref="Span{T}"/>, and <see cref="ReadOnlySpan{T}"/>. /// </summary> public static partial class MemoryMarshal { /// <summary> /// Casts a Span of one primitive type <typeparamref name="T"/> to Span of bytes. /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <param name="span">The source slice, of type <typeparamref name="T"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> contains pointers. /// </exception> /// <exception cref="System.OverflowException"> /// Thrown if the Length property of the new Span would exceed int.MaxValue. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<byte> AsBytes<T>(Span<T> span) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); return new Span<byte>( ref Unsafe.As<T, byte>(ref GetReference(span)), checked(span.Length * Unsafe.SizeOf<T>())); } /// <summary> /// Casts a ReadOnlySpan of one primitive type <typeparamref name="T"/> to ReadOnlySpan of bytes. /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <param name="span">The source slice, of type <typeparamref name="T"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> contains pointers. /// </exception> /// <exception cref="System.OverflowException"> /// Thrown if the Length property of the new Span would exceed int.MaxValue. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<byte> AsBytes<T>(ReadOnlySpan<T> span) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); return new ReadOnlySpan<byte>( ref Unsafe.As<T, byte>(ref GetReference(span)), checked(span.Length * Unsafe.SizeOf<T>())); } /// <summary>Creates a <see cref="Memory{T}"/> from a <see cref="ReadOnlyMemory{T}"/>.</summary> /// <param name="memory">The <see cref="ReadOnlyMemory{T}"/>.</param> /// <returns>A <see cref="Memory{T}"/> representing the same memory as the <see cref="ReadOnlyMemory{T}"/>, but writable.</returns> /// <remarks> /// <see cref="AsMemory{T}(ReadOnlyMemory{T})"/> must be used with extreme caution. <see cref="ReadOnlyMemory{T}"/> is used /// to represent immutable data and other memory that is not meant to be written to; <see cref="Memory{T}"/> instances created /// by <see cref="AsMemory{T}(ReadOnlyMemory{T})"/> should not be written to. The method exists to enable variables typed /// as <see cref="Memory{T}"/> but only used for reading to store a <see cref="ReadOnlyMemory{T}"/>. /// </remarks> public static Memory<T> AsMemory<T>(ReadOnlyMemory<T> memory) => Unsafe.As<ReadOnlyMemory<T>, Memory<T>>(ref memory); /// <summary> /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element /// would have been stored. Such a reference may or may not be null. It can be used for pinning but must never be dereferenced. /// </summary> public static ref T GetReference<T>(Span<T> span) => ref span._pointer.Value; /// <summary> /// Returns a reference to the 0th element of the ReadOnlySpan. If the ReadOnlySpan is empty, returns a reference to the location where the 0th element /// would have been stored. Such a reference may or may not be null. It can be used for pinning but must never be dereferenced. /// </summary> public static ref T GetReference<T>(ReadOnlySpan<T> span) => ref span._pointer.Value; /// <summary> /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to fake non-null pointer. Such a reference can be used /// for pinning but must never be dereferenced. This is useful for interop with methods that do not accept null pointers for zero-sized buffers. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe ref T GetNonNullPinnableReference<T>(Span<T> span) => ref (span.Length != 0) ? ref span._pointer.Value : ref Unsafe.AsRef<T>((void*)1); /// <summary> /// Returns a reference to the 0th element of the ReadOnlySpan. If the ReadOnlySpan is empty, returns a reference to fake non-null pointer. Such a reference /// can be used for pinning but must never be dereferenced. This is useful for interop with methods that do not accept null pointers for zero-sized buffers. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe ref T GetNonNullPinnableReference<T>(ReadOnlySpan<T> span) => ref (span.Length != 0) ? ref span._pointer.Value : ref Unsafe.AsRef<T>((void*)1); /// <summary> /// Casts a Span of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>. /// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <remarks> /// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means. /// </remarks> /// <param name="span">The source slice, of type <typeparamref name="TFrom"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<TTo> Cast<TFrom, TTo>(Span<TFrom> span) where TFrom : struct where TTo : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom)); if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo)); // Use unsigned integers - unsigned division by constant (especially by power of 2) // and checked casts are faster and smaller. uint fromSize = (uint)Unsafe.SizeOf<TFrom>(); uint toSize = (uint)Unsafe.SizeOf<TTo>(); uint fromLength = (uint)span.Length; int toLength; if (fromSize == toSize) { // Special case for same size types - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize` // should be optimized to just `length` but the JIT doesn't do that today. toLength = (int)fromLength; } else if (fromSize == 1) { // Special case for byte sized TFrom - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize` // becomes `(ulong)fromLength / (ulong)toSize` but the JIT can't narrow it down to `int` // and can't eliminate the checked cast. This also avoids a 32 bit specific issue, // the JIT can't eliminate long multiply by 1. toLength = (int)(fromLength / toSize); } else { // Ensure that casts are done in such a way that the JIT is able to "see" // the uint->ulong casts and the multiply together so that on 32 bit targets // 32x32to64 multiplication is used. ulong toLengthUInt64 = (ulong)fromLength * (ulong)fromSize / (ulong)toSize; toLength = checked((int)toLengthUInt64); } return new Span<TTo>( ref Unsafe.As<TFrom, TTo>(ref span._pointer.Value), toLength); } /// <summary> /// Casts a ReadOnlySpan of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>. /// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <remarks> /// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means. /// </remarks> /// <param name="span">The source slice, of type <typeparamref name="TFrom"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<TTo> Cast<TFrom, TTo>(ReadOnlySpan<TFrom> span) where TFrom : struct where TTo : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom)); if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo)); // Use unsigned integers - unsigned division by constant (especially by power of 2) // and checked casts are faster and smaller. uint fromSize = (uint)Unsafe.SizeOf<TFrom>(); uint toSize = (uint)Unsafe.SizeOf<TTo>(); uint fromLength = (uint)span.Length; int toLength; if (fromSize == toSize) { // Special case for same size types - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize` // should be optimized to just `length` but the JIT doesn't do that today. toLength = (int)fromLength; } else if (fromSize == 1) { // Special case for byte sized TFrom - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize` // becomes `(ulong)fromLength / (ulong)toSize` but the JIT can't narrow it down to `int` // and can't eliminate the checked cast. This also avoids a 32 bit specific issue, // the JIT can't eliminate long multiply by 1. toLength = (int)(fromLength / toSize); } else { // Ensure that casts are done in such a way that the JIT is able to "see" // the uint->ulong casts and the multiply together so that on 32 bit targets // 32x32to64 multiplication is used. ulong toLengthUInt64 = (ulong)fromLength * (ulong)fromSize / (ulong)toSize; toLength = checked((int)toLengthUInt64); } return new ReadOnlySpan<TTo>( ref Unsafe.As<TFrom, TTo>(ref MemoryMarshal.GetReference(span)), toLength); } /// <summary> /// Create a new span over a portion of a regular managed object. This can be useful /// if part of a managed object represents a "fixed array." This is dangerous because the /// <paramref name="length"/> is not checked. /// </summary> /// <param name="reference">A reference to data.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <returns>The lifetime of the returned span will not be validated for safety by span-aware languages.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> CreateSpan<T>(ref T reference, int length) => new Span<T>(ref reference, length); /// <summary> /// Create a new read-only span over a portion of a regular managed object. This can be useful /// if part of a managed object represents a "fixed array." This is dangerous because the /// <paramref name="length"/> is not checked. /// </summary> /// <param name="reference">A reference to data.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <returns>The lifetime of the returned span will not be validated for safety by span-aware languages.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<T> CreateReadOnlySpan<T>(ref T reference, int length) => new ReadOnlySpan<T>(ref reference, length); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal class OpenSslX509Encoder : IX509Pal { public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal certificatePal) { switch (oid.Value) { case Oids.RsaRsa: return BuildRsaPublicKey(encodedKeyValue); case Oids.Ecc: return ((OpenSslX509CertificateReader)certificatePal).GetECDsaPublicKey(); } // NotSupportedException is what desktop and CoreFx-Windows throw in this situation. throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } public string X500DistinguishedNameDecode(byte[] encodedDistinguishedName, X500DistinguishedNameFlags flags) { return X500NameEncoder.X500DistinguishedNameDecode(encodedDistinguishedName, true, flags); } public byte[] X500DistinguishedNameEncode(string distinguishedName, X500DistinguishedNameFlags flag) { throw new NotImplementedException(); } public string X500DistinguishedNameFormat(byte[] encodedDistinguishedName, bool multiLine) { throw new NotImplementedException(); } public X509ContentType GetCertContentType(byte[] rawData) { throw new NotImplementedException(); } public X509ContentType GetCertContentType(string fileName) { throw new NotImplementedException(); } public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages) { throw new NotImplementedException(); } public void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages) { using (SafeAsn1BitStringHandle bitString = Interop.Crypto.DecodeAsn1BitString(encoded, encoded.Length)) { Interop.Crypto.CheckValidOpenSslHandle(bitString); byte[] decoded = Interop.Crypto.GetAsn1StringBytes(bitString.DangerousGetHandle()); // Only 9 bits are defined. if (decoded.Length > 2) { throw new CryptographicException(); } // DER encodings of BIT_STRING values number the bits as // 01234567 89 (big endian), plus a number saying how many bits of the last byte were padding. // // So digitalSignature (0) doesn't mean 2^0 (0x01), it means the most significant bit // is set in this byte stream. // // BIT_STRING values are compact. So a value of cRLSign (6) | keyEncipherment (2), which // is 0b0010001 => 0b0010 0010 (1 bit padding) => 0x22 encoded is therefore // 0x02 (length remaining) 0x01 (1 bit padding) 0x22. // // OpenSSL's d2i_ASN1_BIT_STRING is going to take that, and return 0x22. 0x22 lines up // exactly with X509KeyUsageFlags.CrlSign (0x20) | X509KeyUsageFlags.KeyEncipherment (0x02) // // Once the decipherOnly (8) bit is added to the mix, the values become: // 0b001000101 => 0b0010 0010 1000 0000 (7 bits padding) // { 0x03 0x07 0x22 0x80 } // And OpenSSL returns new byte[] { 0x22 0x80 } // // The value of X509KeyUsageFlags.DecipherOnly is 0x8000. 0x8000 in a little endian // representation is { 0x00 0x80 }. This means that the DER storage mechanism has effectively // ended up being little-endian for BIT_STRING values. Untwist the bytes, and now the bits all // line up with the existing X509KeyUsageFlags. int value = 0; if (decoded.Length > 0) { value = decoded[0]; } if (decoded.Length > 1) { value |= decoded[1] << 8; } keyUsages = (X509KeyUsageFlags)value; } } public byte[] EncodeX509BasicConstraints2Extension( bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint) { throw new NotImplementedException(); } public void DecodeX509BasicConstraintsExtension( byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { throw new NotImplementedException(); } public void DecodeX509BasicConstraints2Extension( byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { if (!Interop.Crypto.DecodeX509BasicConstraints2Extension( encoded, encoded.Length, out certificateAuthority, out hasPathLengthConstraint, out pathLengthConstraint)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } } public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages) { throw new NotImplementedException(); } public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { OidCollection oids = new OidCollection(); using (SafeEkuExtensionHandle eku = Interop.Crypto.DecodeExtendedKeyUsage(encoded, encoded.Length)) { Interop.Crypto.CheckValidOpenSslHandle(eku); int count = Interop.Crypto.GetX509EkuFieldCount(eku); for (int i = 0; i < count; i++) { IntPtr oidPtr = Interop.Crypto.GetX509EkuField(eku, i); if (oidPtr == IntPtr.Zero) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } string oidValue = Interop.Crypto.GetOidValue(oidPtr); oids.Add(new Oid(oidValue)); } } usages = oids; } public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier) { throw new NotImplementedException(); } public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier) { subjectKeyIdentifier = DecodeX509SubjectKeyIdentifierExtension(encoded); } internal static byte[] DecodeX509SubjectKeyIdentifierExtension(byte[] encoded) { DerSequenceReader reader = DerSequenceReader.CreateForPayload(encoded); return reader.ReadOctetString(); } public byte[] ComputeCapiSha1OfPublicKey(PublicKey key) { throw new NotImplementedException(); } private static RSA BuildRsaPublicKey(byte[] encodedData) { using (SafeRsaHandle rsaHandle = Interop.Crypto.DecodeRsaPublicKey(encodedData, encodedData.Length)) { Interop.Crypto.CheckValidOpenSslHandle(rsaHandle); RSAParameters rsaParameters = Interop.Crypto.ExportRsaParameters(rsaHandle, false); RSA rsa = new RSAOpenSsl(); rsa.ImportParameters(rsaParameters); return rsa; } } } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_865 : MapLoop { public M_865() : base(null) { Content.AddRange(new MapBaseEntity[] { new BCA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PAM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new CSH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_SAC(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new DIS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new INC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new LDT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CTB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new G53() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N9(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new L_AMT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_ADV(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_POC(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_CTT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } //1000 public class L_SAC : MapLoop { public L_SAC(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2000 public class L_N9 : MapLoop { public L_N9(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, }); } } //3000 public class L_N1 : MapLoop { public L_N1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4000 public class L_AMT : MapLoop { public L_AMT(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //5000 public class L_ADV : MapLoop { public L_ADV(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ADV() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MTX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6000 public class L_POC : MapLoop { public L_POC(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new POC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PO3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PAM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 }, new L_PID(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PO4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new L_SAC_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new IT8() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CSH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new DIS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new INC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SDQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 500 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_ACK(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 104 }, new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new SPI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CTB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_AMT_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_QTY(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_SCH(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new L_LDT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N9_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new L_SLN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new L_PD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6100 public class L_PID : MapLoop { public L_PID(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PID() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //6150 public class L_SAC_1 : MapLoop { public L_SAC_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6200 public class L_ACK : MapLoop { public L_ACK(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ACK() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6250 public class L_AMT_1 : MapLoop { public L_AMT_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6300 public class L_QTY : MapLoop { public L_QTY(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6350 public class L_SCH : MapLoop { public L_SCH(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SCH() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6400 public class L_LDT : MapLoop { public L_LDT(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LDT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6410 public class L_LM : MapLoop { public L_LM(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6500 public class L_N9_1 : MapLoop { public L_N9_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, }); } } //6600 public class L_N1_1 : MapLoop { public L_N1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new SCH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new L_LDT_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6610 public class L_LDT_1 : MapLoop { public L_LDT_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LDT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6700 public class L_SLN : MapLoop { public L_SLN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SLN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new PO3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PAM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new ACK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 104 }, new L_SAC_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new PO4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new ADV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_QTY_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N9_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //6710 public class L_SAC_2 : MapLoop { public L_SAC_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6720 public class L_QTY_1 : MapLoop { public L_QTY_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6730 public class L_N9_2 : MapLoop { public L_N9_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6740 public class L_N1_2 : MapLoop { public L_N1_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6800 public class L_PD : MapLoop { public L_PD(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PDD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //7000 public class L_CTT : MapLoop { public L_CTT(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new CTT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Security.Principal; using Microsoft.VisualStudio.TestTools.UnitTesting; using NakedFramework.Architecture.Component; using NakedFramework.Architecture.Facet; using NakedFramework.Architecture.Reflect; using NakedFramework.Architecture.SpecImmutable; using NakedFramework.Metamodel.Facet; using NakedObjects.Reflector.FacetFactory; // ReSharper disable UnusedType.Local // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local namespace NakedObjects.Reflector.Test.FacetFactory; [TestClass] // ReSharper disable UnusedParameter.Local // ReSharper disable ClassNeverInstantiated.Local public class CollectionFieldMethodsFacetFactoryTest : AbstractFacetFactoryTest { private CollectionFieldMethodsFacetFactory facetFactory; protected override Type[] SupportedTypes => new[] { typeof(IPropertyAccessorFacet), typeof(ITypeOfFacet) }; protected override IFacetFactory FacetFactory => facetFactory; [TestMethod] public void TestCannotInferTypeOfFacetIfNoExplicitAddToOrRemoveFromMethods() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var property = FindProperty(typeof(Customer6), "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); Assert.IsNull(Specification.GetFacet(typeof(ITypeOfFacet))); Assert.IsNotNull(metamodel); } [TestMethod] public override void TestFeatureTypes() { var featureTypes = facetFactory.FeatureTypes; Assert.IsFalse(featureTypes.HasFlag(FeatureType.Objects)); Assert.IsFalse(featureTypes.HasFlag(FeatureType.Properties)); Assert.IsTrue(featureTypes.HasFlag(FeatureType.Collections)); Assert.IsFalse(featureTypes.HasFlag(FeatureType.Actions)); Assert.IsFalse(featureTypes.HasFlag(FeatureType.ActionParameters)); } [TestMethod] public void TestInstallsDisabledAlways() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var property = FindProperty(typeof(CustomerStatic), "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDisabledFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is DisabledFacetAlways); Assert.IsNotNull(metamodel); } [TestMethod] public void TestInstallsHiddenForSessionFacetAndRemovesMethod() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var property = FindProperty(typeof(CustomerStatic), "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IHideForSessionFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is HideForSessionFacetNone); Assert.IsNotNull(metamodel); } [TestMethod] public void TestPropertyAccessorFacetIsInstalledForArrayListAndMethodRemoved() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var property = FindProperty(typeof(Customer1), "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IPropertyAccessorFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is PropertyAccessorFacet); Assert.IsNotNull(metamodel); } [TestMethod] public void TestPropertyAccessorFacetIsInstalledForIListAndMethodRemoved() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var property = FindProperty(typeof(Customer), "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IPropertyAccessorFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is PropertyAccessorFacet); Assert.IsNotNull(metamodel); } [TestMethod] public void TestPropertyAccessorFacetIsInstalledForObjectArrayAndMethodRemoved() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var property = FindProperty(typeof(Customer3), "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IPropertyAccessorFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is PropertyAccessorFacet); Assert.IsNotNull(metamodel); } [TestMethod] public void TestPropertyAccessorFacetIsInstalledForOrderArrayAndMethodRemoved() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var property = FindProperty(typeof(Customer4), "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IPropertyAccessorFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is PropertyAccessorFacet); Assert.IsNotNull(metamodel); } [TestMethod] public void TestPropertyAccessorFacetIsInstalledForSetAndMethodRemoved() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var property = FindProperty(typeof(Customer2), "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IPropertyAccessorFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is PropertyAccessorFacet); Assert.IsNotNull(metamodel); } [TestMethod] public void TestSetFacetAddedToSet() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var type = typeof(Customer18); var property = FindProperty(type, "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IIsASetFacet)); Assert.IsNotNull(facet); Assert.IsInstanceOfType(facet, typeof(IsASetFacet)); Assert.IsNotNull(metamodel); } [TestMethod] public void TestSetFacetNoAddedToList() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var type = typeof(Customer17); var property = FindProperty(type, "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IIsASetFacet)); Assert.IsNull(facet); Assert.IsNotNull(metamodel); } #region Nested type: Customer private class Customer { public IList Orders => null; } #endregion #region Nested type: Customer1 private class Customer1 { public ArrayList Orders => null; } #endregion #region Nested type: Customer10 private class Customer10 { public IList Orders => null; public void RemoveFromOrders(Order o) { } } #endregion #region Nested type: Customer11 private class Customer11 { public IList Orders => null; public void RemoveFromOrders(Order o) { } } #endregion #region Nested type: Customer12 private class Customer12 { public IList Orders => null; public void ClearOrders() { } } #endregion #region Nested type: Customer13 private class Customer13 { public IList Orders => null; } #endregion #region Nested type: Customer14 private class Customer14 { public IList Orders => null; public void AddToOrders(Order o) { } public string ValidateAddToOrders(Order o) => null; } #endregion #region Nested type: Customer15 private class Customer15 { public IList Orders => null; public void RemoveFromOrders(Order o) { } public string ValidateRemoveFromOrders(Order o) => null; } #endregion #region Nested type: Customer16 private class Customer16 { public IList<Order> Orders => null; public void AddToOrders(Order o) { } } #endregion #region Nested type: Customer17 private class Customer17 { public IList<Order> Orders => null; public void AddToOrders(Customer c) { } public void RemoveFromOrders(Customer c) { } } #endregion #region Nested type: Customer18 private class Customer18 { public ISet<Order> Orders => null; public void AddToOrders(Customer c) { } public void RemoveFromOrders(Customer c) { } } #endregion #region Nested type: Customer2 private class Customer2 { public ArrayList Orders => null; } #endregion #region Nested type: Customer3 private class Customer3 { public object[] Orders => null; } #endregion #region Nested type: Customer4 private class Customer4 { public Order[] Orders => null; } #endregion #region Nested type: Customer5 private class Customer5 { public IList Orders => null; } #endregion #region Nested type: Customer6 private class Customer6 { public IList Orders => null; } #endregion #region Nested type: Customer7 private class Customer7 { public IList Orders => null; } #endregion #region Nested type: Customer8 private class Customer8 { public IList Orders => null; public void AddToOrders(Order o) { } } #endregion #region Nested type: Customer9 private class Customer9 { public IList Orders => null; public void AddToOrders(Order o) { } } #endregion #region Nested type: CustomerStatic public class CustomerStatic { public IList Orders => null; public static string NameOrders() => "Most Recent Orders"; public static string DescriptionOrders() => "Some old description"; public static bool AlwaysHideOrders() => true; public static bool ProtectOrders() => true; public static bool HideOrders(IPrincipal principal) => true; public static string DisableOrders(IPrincipal principal) => "disabled for this user"; public static void OtherOrders() { } public static bool AlwaysHideOtherOrders() => false; public static bool ProtectOtherOrders() => false; } #endregion #region Nested type: Order private class Order { } #endregion #region Setup/Teardown [TestInitialize] public override void SetUp() { base.SetUp(); facetFactory = new CollectionFieldMethodsFacetFactory(GetOrder<CollectionFieldMethodsFacetFactory>(), LoggerFactory); } [TestCleanup] public override void TearDown() { facetFactory = null; base.TearDown(); } #endregion } // Copyright (c) Naked Objects Group Ltd. // ReSharper restore UnusedMember.Local // ReSharper restore UnusedParameter.Local // ReSharper restore ClassNeverInstantiated.Local
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using typescriptDTS.Areas.HelpPage.ModelDescriptions; using typescriptDTS.Areas.HelpPage.Models; namespace typescriptDTS.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesCreate1 { public partial class IndicesCreate1YamlTests { [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CreateIndexWithMappings1Tests : YamlTestsBase { [Test] public void CreateIndexWithMappings1Test() { //do indices.create _body = new { mappings= new { type_1= new {} } }; this.Do(()=> _client.IndicesCreate("test_index", _body)); //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_index")); //match _response.test_index.mappings.type_1.properties: this.IsMatch(_response.test_index.mappings.type_1.properties, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CreateIndexWithSettings2Tests : YamlTestsBase { [Test] public void CreateIndexWithSettings2Test() { //do indices.create _body = new { settings= new { number_of_replicas= "0" } }; this.Do(()=> _client.IndicesCreate("test_index", _body)); //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("test_index")); //match _response.test_index.settings.index.number_of_replicas: this.IsMatch(_response.test_index.settings.index.number_of_replicas, 0); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CreateIndexWithWarmers3Tests : YamlTestsBase { [Test] public void CreateIndexWithWarmers3Test() { //do indices.create _body = new { warmers= new { test_warmer= new { source= new { query= new { match_all= new {} } } } } }; this.Do(()=> _client.IndicesCreate("test_index", _body)); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("test_index")); //match _response.test_index.warmers.test_warmer.source.query.match_all: this.IsMatch(_response.test_index.warmers.test_warmer.source.query.match_all, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CreateIndexWithAliases4Tests : YamlTestsBase { [Test] public void CreateIndexWithAliases4Test() { //do indices.create _body = new { aliases= new { test_alias= new {}, test_blias= new { routing= "b" }, test_clias= new { filter= new { term= new { field= "value" } } } } }; this.Do(()=> _client.IndicesCreate("test_index", _body)); //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias.search_routing: this.IsMatch(_response.test_index.aliases.test_blias.search_routing, @"b"); //match _response.test_index.aliases.test_blias.index_routing: this.IsMatch(_response.test_index.aliases.test_blias.index_routing, @"b"); //is_false _response.test_index.aliases.test_blias.filter; this.IsFalse(_response.test_index.aliases.test_blias.filter); //match _response.test_index.aliases.test_clias.filter.term.field: this.IsMatch(_response.test_index.aliases.test_clias.filter.term.field, @"value"); //is_false _response.test_index.aliases.test_clias.index_routing; this.IsFalse(_response.test_index.aliases.test_clias.index_routing); //is_false _response.test_index.aliases.test_clias.search_routing; this.IsFalse(_response.test_index.aliases.test_clias.search_routing); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CreateIndexWithMappingsSettingsWarmersAndAliases5Tests : YamlTestsBase { [Test] public void CreateIndexWithMappingsSettingsWarmersAndAliases5Test() { //do indices.create _body = new { mappings= new { type_1= new {} }, settings= new { number_of_replicas= "0" }, warmers= new { test_warmer= new { source= new { query= new { match_all= new {} } } } }, aliases= new { test_alias= new {}, test_blias= new { routing= "b" } } }; this.Do(()=> _client.IndicesCreate("test_index", _body)); //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_index")); //match _response.test_index.mappings.type_1.properties: this.IsMatch(_response.test_index.mappings.type_1.properties, new {}); //do indices.get_settings this.Do(()=> _client.IndicesGetSettings("test_index")); //match _response.test_index.settings.index.number_of_replicas: this.IsMatch(_response.test_index.settings.index.number_of_replicas, 0); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("test_index")); //match _response.test_index.warmers.test_warmer.source.query.match_all: this.IsMatch(_response.test_index.warmers.test_warmer.source.query.match_all, new {}); //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias.search_routing: this.IsMatch(_response.test_index.aliases.test_blias.search_routing, @"b"); //match _response.test_index.aliases.test_blias.index_routing: this.IsMatch(_response.test_index.aliases.test_blias.index_routing, @"b"); } } } }
// // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /** * Namespace: System.Web.UI.WebControls * Class: TableItemStyle * * Author: Gaurav Vaish * Maintainer: gvaish@iitk.ac.in * Contact: <my_scripts2001@yahoo.com>, <gvaish@iitk.ac.in> * Implementation: yes * Status: 100% * * (C) Gaurav Vaish (2002) */ using System; using System.ComponentModel; using System.Web; using System.Web.UI; namespace System.Web.UI.WebControls { public class TableItemStyle: Style { private static int H_ALIGN = (0x01 << 16); private static int V_ALIGN = (0x01 << 17); private static int WRAP = (0x01 << 18); public TableItemStyle(): base() { } public TableItemStyle(StateBag bag): base(bag) { } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue(HorizontalAlign.NotSet)] [NotifyParentProperty(true)] [WebCategory("Layout")] [WebSysDescription("TableItemStyle_HorizontalAlign")] public virtual HorizontalAlign HorizontalAlign { get { if(IsSet(H_ALIGN)) return (HorizontalAlign)ViewState["HorizontalAlign"]; return HorizontalAlign.NotSet; } set { if(!Enum.IsDefined(typeof(HorizontalAlign), value)) { throw new ArgumentException(); } ViewState["HorizontalAlign"] = value; Set(H_ALIGN); } } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue(VerticalAlign.NotSet)] [NotifyParentProperty(true)] [WebCategory("Layout")] [WebSysDescription("TableItemStyle_VerticalAlign")] public virtual VerticalAlign VerticalAlign { get { if(IsSet(V_ALIGN)) return (VerticalAlign)ViewState["VerticalAlign"]; return VerticalAlign.NotSet; } set { if(!Enum.IsDefined(typeof(VerticalAlign), value)) { throw new ArgumentException(); } ViewState["VerticalAlign"] = value; Set(V_ALIGN); } } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue(VerticalAlign.NotSet)] [NotifyParentProperty(true)] [WebCategory("Layout")] [WebSysDescription("TableItemStyle_Wrap")] public virtual bool Wrap { get { if(IsSet(WRAP)) return (bool)ViewState["Wrap"]; return true; } set { ViewState["Wrap"] = value; Set(WRAP); } } public override void CopyFrom(Style s) { if(s!=null && !s.IsEmpty) { base.CopyFrom(s); if (!(s is TableItemStyle)) return; TableItemStyle from = (TableItemStyle)s; if(from.IsSet(H_ALIGN)) { HorizontalAlign = from.HorizontalAlign; } if(from.IsSet(V_ALIGN)) { VerticalAlign = from.VerticalAlign; } if(from.IsSet(WRAP)) { Wrap = from.Wrap; } } } public override void MergeWith(Style s) { if(s!=null && !s.IsEmpty) { if (IsEmpty) { CopyFrom (s); return; } base.MergeWith(s); if (!(s is TableItemStyle)) return; TableItemStyle with = (TableItemStyle)s; if(with.IsSet(H_ALIGN) && !IsSet(H_ALIGN)) { HorizontalAlign = with.HorizontalAlign; } if(with.IsSet(V_ALIGN) && !IsSet(V_ALIGN)) { VerticalAlign = with.VerticalAlign; } if(with.IsSet(WRAP) && !IsSet(WRAP)) { Wrap = with.Wrap; } } } public override void Reset() { if(IsSet(H_ALIGN)) ViewState.Remove("HorizontalAlign"); if(IsSet(V_ALIGN)) ViewState.Remove("VerticalAlign"); if(IsSet(WRAP)) ViewState.Remove("Wrap"); base.Reset(); } public override void AddAttributesToRender(HtmlTextWriter writer, WebControl owner) { base.AddAttributesToRender(writer, owner); if(!Wrap) { writer.AddAttribute(HtmlTextWriterAttribute.Nowrap, "nowrap"); } if(HorizontalAlign != HorizontalAlign.NotSet) { // Temporarily commented out. I'm having problems in cygwin. //writer.AddAttribute(HtmlTextWriterAttribute.Align, TypeDescriptor.GetConverter(typeof(HorizontalAlign)).ConvertToString(HorizontalAlign)); writer.AddAttribute(HtmlTextWriterAttribute.Align, HorizontalAlign.ToString ()); } if(VerticalAlign != VerticalAlign.NotSet) { // Temporarily commented out. I'm having problems in cygwin. //writer.AddAttribute(HtmlTextWriterAttribute.Valign, TypeDescriptor.GetConverter(typeof(VerticalAlign)).ConvertToString(VerticalAlign)); writer.AddAttribute(HtmlTextWriterAttribute.Valign, VerticalAlign.ToString ()); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using lmdp.Areas.HelpPage.ModelDescriptions; using lmdp.Areas.HelpPage.Models; namespace lmdp.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using OpenKh.Common; using OpenKh.Kh2.Ard; using System.Collections.Generic; using System.IO; using Xunit; using Xunit.Sdk; namespace OpenKh.Tests.kh2 { public class EventTests { [Fact] public void ParseProject() => AssertEvent<Event.SetProject>(); [Fact] public void ParseSetActor() => AssertEvent<Event.SetActor>(); [Fact] public void ParseSeqActorPosition() => AssertEvent<Event.SeqActorPosition>(); [Fact] public void ParseSetMap() => AssertEvent<Event.SetMap>(); [Fact] public void ParseSeqCamera() => AssertEvent<Event.SeqCamera>(); [Fact] public void ParseSetEndFrame() => AssertEvent<Event.SetEndFrame>(); [Fact] public void ParseSeqEffect() => AssertEvent<Event.SeqEffect>(); [Fact] public void ParseAttachEffect() => AssertEvent<Event.AttachEffect>(); [Fact] public void ParseUnk0C() => AssertEvent<Event.Unk0C>(); [Fact] public void ParseUnk0D() => AssertEvent(new Event.Unk0D { StartFrame = 123, EndFrame = 456, Unk = new short[] { 11, 22, 33, 44 } }); [Fact] public void ParseUnk0E() => AssertEvent<Event.Unk0E>(); [Fact] public void ParseSetupEvent() => AssertEvent<Event.SetupEvent>(); [Fact] public void ParseEventStart() => AssertEvent<Event.EventStart>(); [Fact] public void ParseSeqFade() => AssertEvent(new Event.SeqFade { FrameIndex = 123, Duration = 456, Type = Event.SeqFade.FadeType.FromWhiteVariant }); [Fact] public void ParseSetCameraData() => AssertEvent(new Event.SetCameraData { CameraId = 123, PositionX = new List<Event.SetCameraData.CameraKeys> { new Event.SetCameraData.CameraKeys { Interpolation = Kh2.Motion.Interpolation.Hermite, KeyFrame = 1234, Value = 1, TangentEaseIn = 3, TangentEaseOut = 4 }, new Event.SetCameraData.CameraKeys { Interpolation = Kh2.Motion.Interpolation.Linear, KeyFrame = 5678, Value = 5, TangentEaseIn = 7, TangentEaseOut = 8 }, }, PositionY = new List<Event.SetCameraData.CameraKeys>() { new Event.SetCameraData.CameraKeys { Interpolation = Kh2.Motion.Interpolation.Nearest, KeyFrame = 32767, Value = 11, TangentEaseIn = 33, TangentEaseOut = 44 }, }, PositionZ = new List<Event.SetCameraData.CameraKeys>(), LookAtX = new List<Event.SetCameraData.CameraKeys>(), LookAtY = new List<Event.SetCameraData.CameraKeys>(), LookAtZ = new List<Event.SetCameraData.CameraKeys>(), FieldOfView = new List<Event.SetCameraData.CameraKeys>(), Roll = new List<Event.SetCameraData.CameraKeys>(), }); [Fact] public void ParseEntryUnk14() => AssertEvent<Event.EntryUnk14>(); [Fact] public void ParseSeqSubtitle() => AssertEvent<Event.SeqSubtitle>(); [Fact] public void ParseEntryUnk16() => AssertEvent<Event.EntryUnk16>(); [Fact] public void ParseEntryUnk17() => AssertEvent<Event.EntryUnk17>(); [Fact] public void ParseEntryUnk18() => AssertEvent<Event.EntryUnk18>(); [Fact] public void ParseSeqTextureAnim() => AssertEvent<Event.SeqTextureAnim>(); [Fact] public void ParseEntryUnk1A() => AssertEvent<Event.SeqActorLeave>(); [Fact] public void ParseSeqCrossFade() => AssertEvent<Event.SeqCrossFade>(); [Fact] public void ParseEntryUnk1D() => AssertEvent<Event.EntryUnk1D>(); [Fact] public void ParseEntryUnk1E() => AssertEvent(new Event.Unk1E { Id = 123, UnkG = 456, UnkH = 789, Entries = new List<Event.Unk1E.Entry>() { Helpers.CreateDummyObject<Event.Unk1E.Entry>(), Helpers.CreateDummyObject<Event.Unk1E.Entry>(), Helpers.CreateDummyObject<Event.Unk1E.Entry>(), Helpers.CreateDummyObject<Event.Unk1E.Entry>(), Helpers.CreateDummyObject<Event.Unk1E.Entry>(), Helpers.CreateDummyObject<Event.Unk1E.Entry>(), Helpers.CreateDummyObject<Event.Unk1E.Entry>(), } }); [Fact] public void ParseEntryUnk1F() => AssertEvent<Event.Unk1F>(); [Fact] public void ParseSeqGameSpeed() => AssertEvent<Event.SeqGameSpeed>(); [Fact] public void ParseEntryUnk22() => AssertEvent<Event.EntryUnk22>(); [Fact] public void ParseSeqVoices() => AssertEvent(new Event.SeqVoices { Voices = new List<Event.SeqVoices.Voice> { new Event.SeqVoices.Voice { FrameStart = 123, Name = "first" }, new Event.SeqVoices.Voice { FrameStart = 456, Name = "second" }, } }); [Fact] public void ParseReadAssets() => AssertEvent(new Event.ReadAssets { FrameStart = 123, FrameEnd = 456, Unk06 = 789, Set = new List<Event.IEventEntry> { Helpers.CreateDummyObject<Event.ReadMotion>(), Helpers.CreateDummyObject<Event.ReadAudio>(), Helpers.CreateDummyObject<Event.ReadActor>(), Helpers.CreateDummyObject<Event.ReadEffect>(), Helpers.CreateDummyObject<Event.ReadLayout>(), } }); [Fact] public void ParseReadAnimation() => AssertEvent<Event.ReadMotion>(); [Fact] public void ParseReadAudio() => AssertEvent<Event.ReadAudio>(); [Fact] public void ParseSetRumble() => AssertEvent<Event.SetShake>(); [Fact] public void ParseEntryUnk2A() => AssertEvent<Event.EntryUnk2A>(); [Fact] public void ParseSeqPlayAudio() => AssertEvent<Event.SeqPlayAudio>(); [Fact] public void ParseSeqPlayAnimation() => AssertEvent<Event.SeqPlayAnimation>(); [Fact] public void ParseSeqDialog() => AssertEvent<Event.SeqDialog>(); [Fact] public void ParseSeqPlayBgm() => AssertEvent<Event.SeqPlayBgm>(); [Fact] public void ParseReadBgm() => AssertEvent<Event.ReadBgm>(); [Fact] public void ParseSetBgm() => AssertEvent<Event.SetBgm>(); [Fact] public void ParseEntryUnk36() => AssertEvent<Event.EntryUnk36>(); [Fact] public void ParseReadActor() => AssertEvent<Event.ReadActor>(); [Fact] public void ParseReadEffect() => AssertEvent<Event.ReadEffect>(); [Fact] public void ParseSeqLayout() => AssertEvent<Event.SeqLayout>(); [Fact] public void ParseReadLayout() => AssertEvent<Event.ReadLayout>(); [Fact] public void ParseStopEffect() => AssertEvent<Event.StopEffect>(); [Fact] public void ParseRunMovie() => AssertEvent<Event.RunMovie>(); [Fact] public void ParseUnk42() => AssertEvent<Event.Unk42>(); [Fact] public void ParseEntryUnk47() => AssertEvent<Event.EntryUnk47>(); [Fact] public void ParseHideObject() => AssertEvent<Event.SeqHideObject>(); private static void AssertEvent<T>() where T : class, Event.IEventEntry => AssertEvent(Helpers.CreateDummyObject<T>()); private static void AssertEvent<T>(T expected) where T : class, Event.IEventEntry { using var stream = new MemoryStream(); Event.Write(stream, new Event.IEventEntry[] { expected }); var actualLength = stream.Position - 2; if ((actualLength % 2) == 1) throw new AssertActualExpectedException( actualLength + 1, actualLength, "Offset is not aligned by 2"); stream.Position = 0; var eventSet = Event.Read(stream); var expectedLength = stream.Position; Assert.Single(eventSet); Assert.IsType<T>(eventSet[0]); if (expectedLength != actualLength) throw new AssertActualExpectedException( expectedLength, actualLength, "Stream length does not match"); var actual = eventSet[0]; foreach (var property in typeof(T).GetProperties()) { var expectedValue = property.GetValue(expected); var actualValue = property.GetValue(actual); if (expectedValue.ToString() != actualValue.ToString()) throw new AssertActualExpectedException( expectedValue, actualValue, $"Different values for '{property.Name}'"); } } } }
// 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; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { private sealed class CurlResponseMessage : HttpResponseMessage { internal readonly EasyRequest _easy; private readonly CurlResponseStream _responseStream; internal CurlResponseMessage(EasyRequest easy) { Debug.Assert(easy != null, "Expected non-null EasyRequest"); _easy = easy; _responseStream = new CurlResponseStream(easy); RequestMessage = easy._requestMessage; Content = new StreamContent(_responseStream); } internal CurlResponseStream ResponseStream { get { return _responseStream; } } } /// <summary> /// Provides a response stream that allows libcurl to transfer data asynchronously to a reader. /// When writing data to the response stream, either all or none of the data will be transferred, /// and if none, libcurl will pause the connection until a reader is waiting to consume the data. /// Readers consume the data via ReadAsync, which registers a read state with the stream, to be /// filled in by a pending write. Read is just a thin wrapper around ReadAsync, since the underlying /// mechanism must be asynchronous to prevent blocking libcurl's processing. /// </summary> private sealed class CurlResponseStream : Stream { /// <summary>A cached task storing the Int32 value 0.</summary> private static readonly Task<int> s_zeroTask = Task.FromResult(0); /// <summary> /// A sentinel object used in the <see cref="_completed"/> field to indicate that /// the stream completed successfully. /// </summary> private static readonly Exception s_completionSentinel = new Exception("s_completionSentinel"); /// <summary>A object used to synchronize all access to state on this response stream.</summary> private readonly object _lockObject = new object(); /// <summary>The associated EasyRequest.</summary> private readonly EasyRequest _easy; /// <summary>Stores whether Dispose has been called on the stream.</summary> private bool _disposed = false; /// <summary> /// Null if the Stream has not been completed, non-null if it has been completed. /// If non-null, it'll either be the <see cref="s_completionSentinel"/> object, meaning the stream completed /// successfully, or it'll be an Exception object representing the error that caused completion. /// That error will be transferred to any subsequent read requests. /// </summary> private Exception _completed; /// <summary> /// The state associated with a pending read request. When a reader requests data, it puts /// its state here for the writer to fill in when data is available. /// </summary> private ReadState _pendingReadRequest; /// <summary> /// When data is provided by libcurl, it must be consumed all or nothing: either all of the data is consumed, or /// we must pause the connection. Since a read could need to be satisfied with only some of the data provided, /// we store the rest here until all reads can consume it. If a subsequent write callback comes in to provide /// more data, the connection will then be paused until this buffer is entirely consumed. /// </summary> private byte[] _remainingData; /// <summary> /// The offset into <see cref="_remainingData"/> from which the next read should occur. /// </summary> private int _remainingDataOffset; /// <summary> /// The remaining number of bytes in <see cref="_remainingData"/> available to be read. /// </summary> private int _remainingDataCount; internal CurlResponseStream(EasyRequest easy) { Debug.Assert(easy != null, "Expected non-null associated EasyRequest"); _easy = easy; } public override bool CanRead { get { return !_disposed; } } public override bool CanWrite { get { return false; } } public override bool CanSeek { get { return false; } } public override long Length { get { CheckDisposed(); throw new NotSupportedException(); } } public override long Position { get { CheckDisposed(); throw new NotSupportedException(); } set { CheckDisposed(); throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); throw new NotSupportedException(); } public override void SetLength(long value) { CheckDisposed(); throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { CheckDisposed(); throw new NotSupportedException(); } public override void Flush() { // Nothing to do. } /// <summary> /// Writes the <paramref name="length"/> bytes starting at <paramref name="pointer"/> to the stream. /// </summary> /// <returns> /// <paramref name="length"/> if all of the data was written, or /// <see cref="Interop.libcurl.CURL_WRITEFUNC_PAUSE"/> if the data wasn't copied and the connection /// should be paused until a reader is available. /// </returns> internal ulong TransferDataToStream(IntPtr pointer, long length) { Debug.Assert(pointer != IntPtr.Zero, "Expected a non-null pointer"); Debug.Assert(length >= 0, "Expected a non-negative length"); EventSourceTrace("Length: {0}", length); CheckDisposed(); // If there's no data to write, consider everything transferred. if (length == 0) { return 0; } lock (_lockObject) { VerifyInvariants(); // If there's existing data in the remaining data buffer, or if there's no pending read request, // we need to pause until the existing data is consumed or until there's a waiting read. if (_remainingDataCount > 0) { EventSourceTrace("Pausing. Remaining bytes: {0}", _remainingDataCount); return Interop.Http.CURL_WRITEFUNC_PAUSE; } else if (_pendingReadRequest == null) { EventSourceTrace("Pausing. No pending read request"); return Interop.Http.CURL_WRITEFUNC_PAUSE; } // There's no data in the buffer and there is a pending read request. // Transfer as much data as we can to the read request, completing it. int numBytesForTask = (int)Math.Min(length, _pendingReadRequest._count); Debug.Assert(numBytesForTask > 0, "We must be copying a positive amount."); Marshal.Copy(pointer, _pendingReadRequest._buffer, _pendingReadRequest._offset, numBytesForTask); _pendingReadRequest.SetResult(numBytesForTask); ClearPendingReadRequest(); // If there's any data left, transfer it to our remaining buffer. libcurl does not support // partial transfers of data, so since we just took some of it to satisfy the read request // we must take the rest of it. (If libcurl then comes back to us subsequently with more data // before this buffered data has been consumed, at that point we won't consume any of the // subsequent offering and will ask libcurl to pause.) if (numBytesForTask < length) { IntPtr remainingPointer = pointer + numBytesForTask; _remainingDataCount = checked((int)(length - numBytesForTask)); _remainingDataOffset = 0; // Make sure our remaining data buffer exists and is big enough to hold the data if (_remainingData == null) { _remainingData = new byte[_remainingDataCount]; } else if (_remainingData.Length < _remainingDataCount) { _remainingData = new byte[Math.Max(_remainingData.Length * 2, _remainingDataCount)]; } // Copy the remaining data to the buffer Marshal.Copy(remainingPointer, _remainingData, 0, _remainingDataCount); } // All of the data from libcurl was consumed. return (ulong)length; } } public override int Read(byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (offset > buffer.Length - count) throw new ArgumentException(nameof(buffer)); CheckDisposed(); EventSourceTrace("Buffer: {0}, Offset: {1}, Count: {2}", buffer.Length, offset, count); // Check for cancellation if (cancellationToken.IsCancellationRequested) { EventSourceTrace("Canceled"); return Task.FromCanceled<int>(cancellationToken); } lock (_lockObject) { VerifyInvariants(); // If there's currently a pending read, fail this read, as we don't support concurrent reads. if (_pendingReadRequest != null) { EventSourceTrace("Failing due to existing pending read; concurrent reads not supported."); return Task.FromException<int>(new InvalidOperationException(SR.net_http_content_no_concurrent_reads)); } // If the stream was already completed with failure, complete the read as a failure. if (_completed != null && _completed != s_completionSentinel) { EventSourceTrace("Failing read with error: {0}", _completed); OperationCanceledException oce = _completed as OperationCanceledException; return (oce != null && oce.CancellationToken.IsCancellationRequested) ? Task.FromCanceled<int>(oce.CancellationToken) : Task.FromException<int>(MapToReadWriteIOException(_completed, isRead: true)); } // Quick check for if no data was actually requested. We do this after the check // for errors so that we can still fail the read and transfer the exception if we should. if (count == 0) { return s_zeroTask; } // If there's any data left over from a previous call, grab as much as we can. if (_remainingDataCount > 0) { int bytesToCopy = Math.Min(count, _remainingDataCount); Buffer.BlockCopy(_remainingData, _remainingDataOffset, buffer, offset, bytesToCopy); _remainingDataOffset += bytesToCopy; _remainingDataCount -= bytesToCopy; Debug.Assert(_remainingDataCount >= 0, "The remaining count should never go negative"); Debug.Assert(_remainingDataOffset <= _remainingData.Length, "The remaining offset should never exceed the buffer size"); return Task.FromResult(bytesToCopy); } // If the stream has already been completed, complete the read immediately. if (_completed == s_completionSentinel) { return s_zeroTask; } // Finally, the stream is still alive, and we want to read some data, but there's no data // in the buffer so we need to register ourself to get the next write. if (cancellationToken.CanBeCanceled) { // If the cancellation token is cancelable, then we need to register for cancellation. // We creat a special CancelableReadState that carries with it additional info: // the cancellation token and the registration with that token. When cancellation // is requested, we schedule a work item that tries to remove the read state // from being pending, canceling it in the process. This needs to happen under the // lock, which is why we schedule the operation to run asynchronously: if it ran // synchronously, it could deadlock due to code on another thread holding the lock // and calling Dispose on the registration concurrently with the call to Cancel // the cancellation token. Dispose on the registration won't return until the action // associated with the registration has completed, but if that action is currently // executing and is blocked on the lock that's held while calling Dispose... deadlock. var crs = new CancelableReadState(buffer, offset, count, this, cancellationToken); crs._registration = cancellationToken.Register(s1 => { ((CancelableReadState)s1)._stream.EventSourceTrace("Cancellation invoked. Queueing work item to cancel read state"); Task.Factory.StartNew(s2 => { var crsRef = (CancelableReadState)s2; Debug.Assert(crsRef._token.IsCancellationRequested, "We should only be here if cancellation was requested."); lock (crsRef._stream._lockObject) { if (crsRef._stream._pendingReadRequest == crsRef) { crsRef.TrySetCanceled(crsRef._token); crsRef._stream.ClearPendingReadRequest(); } } }, s1, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); }, crs); _pendingReadRequest = crs; } else { // The token isn't cancelable. Just create a normal read state. _pendingReadRequest = new ReadState(buffer, offset, count); } _easy._associatedMultiAgent.RequestUnpause(_easy); return _pendingReadRequest.Task; } } /// <summary>Notifies the stream that no more data will be written.</summary> internal void SignalComplete(Exception error = null) { lock (_lockObject) { VerifyInvariants(); // If we already completed, nothing more to do if (_completed != null) { return; } // Mark ourselves as being completed _completed = error != null ? error : s_completionSentinel; // If there's a pending read request, complete it, either with 0 bytes for success // or with the exception/CancellationToken for failure. if (_pendingReadRequest != null) { if (_completed == s_completionSentinel) { _pendingReadRequest.TrySetResult(0); } else { EventSourceTrace("Failing pending read task with error: {0}", _completed); OperationCanceledException oce = _completed as OperationCanceledException; if (oce != null) { _pendingReadRequest.TrySetCanceled(oce.CancellationToken); } else { _pendingReadRequest.TrySetException(MapToReadWriteIOException(_completed, isRead: true)); } } ClearPendingReadRequest(); } } } /// <summary>Clears a pending read request, making sure any cancellation registration is unregistered.</summary> private void ClearPendingReadRequest() { Debug.Assert(Monitor.IsEntered(_lockObject), "Lock object must be held to manipulate _pendingReadRequest"); Debug.Assert(_pendingReadRequest != null, "Should only be clearing the pending read request if there is one"); var crs = _pendingReadRequest as CancelableReadState; if (crs != null) { crs._registration.Dispose(); } _pendingReadRequest = null; } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; SignalComplete(); } base.Dispose(disposing); } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(formatMessage, arg0, agent: null, easy: _easy, memberName: memberName); } private void EventSourceTrace<TArg0, TArg1, TArg2>(string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(formatMessage, arg0, arg1, arg2, agent: null, easy: _easy, memberName: memberName); } private void EventSourceTrace(string message, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(message, agent: null, easy: _easy, memberName: memberName); } /// <summary>Verifies various invariants that must be true about our state.</summary> [Conditional("DEBUG")] private void VerifyInvariants() { Debug.Assert(Monitor.IsEntered(_lockObject), "Can only verify invariants while holding the lock"); Debug.Assert(_remainingDataCount >= 0, "Remaining data count should never be negative."); Debug.Assert(_remainingDataCount == 0 || _remainingData != null, "If there's remaining data, there must be a buffer to store it."); Debug.Assert(_remainingData == null || _remainingDataCount <= _remainingData.Length, "The buffer must be large enough for the data length."); Debug.Assert(_remainingData == null || _remainingDataOffset <= _remainingData.Length, "The offset must not walk off the buffer."); Debug.Assert(!((_remainingDataCount > 0) && (_pendingReadRequest != null)), "We can't have both remaining data and a pending request."); Debug.Assert(!((_completed != null) && (_pendingReadRequest != null)), "We can't both be completed and have a pending request."); Debug.Assert(_pendingReadRequest == null || !_pendingReadRequest.Task.IsCompleted, "A pending read request must not have been completed yet."); } /// <summary>State associated with a pending read request.</summary> private class ReadState : TaskCompletionSource<int> { internal readonly byte[] _buffer; internal readonly int _offset; internal readonly int _count; internal ReadState(byte[] buffer, int offset, int count) : base(TaskCreationOptions.RunContinuationsAsynchronously) { Debug.Assert(buffer != null, "Need non-null buffer"); Debug.Assert(offset >= 0, "Need non-negative offset"); Debug.Assert(count > 0, "Need positive count"); _buffer = buffer; _offset = offset; _count = count; } } /// <summary>State associated with a pending read request that's cancelable.</summary> private sealed class CancelableReadState : ReadState { internal readonly CurlResponseStream _stream; internal readonly CancellationToken _token; internal CancellationTokenRegistration _registration; internal CancelableReadState(byte[] buffer, int offset, int count, CurlResponseStream responseStream, CancellationToken cancellationToken) : base(buffer, offset, count) { _stream = responseStream; _token = cancellationToken; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Runtime; using Orleans.Streams.Core; namespace Orleans.Streams { internal class StreamConsumer<T> : IInternalAsyncObservable<T> { internal bool IsRewindable { get; private set; } private readonly StreamImpl<T> stream; private readonly string streamProviderName; [NonSerialized] private readonly IStreamProviderRuntime providerRuntime; [NonSerialized] private readonly IStreamPubSub pubSub; private StreamConsumerExtension myExtension; private IStreamConsumerExtension myGrainReference; [NonSerialized] private readonly AsyncLock bindExtLock; [NonSerialized] private readonly ILogger logger; public StreamConsumer( StreamImpl<T> stream, string streamProviderName, IStreamProviderRuntime runtime, IStreamPubSub pubSub, ILogger logger, bool isRewindable) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (runtime == null) throw new ArgumentNullException(nameof(runtime)); if (pubSub == null) throw new ArgumentNullException(nameof(pubSub)); if (logger == null) throw new ArgumentNullException(nameof(logger)); this.logger = logger; this.stream = stream; this.streamProviderName = streamProviderName; this.providerRuntime = runtime; this.pubSub = pubSub; this.IsRewindable = isRewindable; this.myExtension = null; this.myGrainReference = null; this.bindExtLock = new AsyncLock(); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer) { return SubscribeAsyncImpl(observer, null, null); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync( IAsyncObserver<T> observer, StreamSequenceToken token) { return SubscribeAsyncImpl(observer, null, token); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncBatchObserver<T> batchObserver) { return SubscribeAsyncImpl(null, batchObserver, null); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncBatchObserver<T> batchObserver, StreamSequenceToken token) { return SubscribeAsyncImpl(null, batchObserver, token); } private async Task<StreamSubscriptionHandle<T>> SubscribeAsyncImpl( IAsyncObserver<T> observer, IAsyncBatchObserver<T> batchObserver, StreamSequenceToken token) { if (token != null && !IsRewindable) throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncObservable."); if (observer is GrainReference) throw new ArgumentException("On-behalf subscription via grain references is not supported. Only passing of object references is allowed.", nameof(observer)); if (batchObserver is GrainReference) throw new ArgumentException("On-behalf subscription via grain references is not supported. Only passing of object references is allowed.", nameof(batchObserver)); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Subscribe Token={Token}", token); await BindExtensionLazy(); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Subscribe - Connecting to Rendezvous {0} My GrainRef={1} Token={2}", pubSub, myGrainReference, token); GuidId subscriptionId = pubSub.CreateSubscriptionId(stream.InternalStreamId, myGrainReference); // Optimistic Concurrency: // In general, we should first register the subsription with the pubsub (pubSub.RegisterConsumer) // and only if it succeeds store it locally (myExtension.SetObserver). // Basicaly, those 2 operations should be done as one atomic transaction - either both or none and isolated from concurrent reads. // BUT: there is a distributed race here: the first msg may arrive before the call is awaited // (since the pubsub notifies the producer that may immideately produce) // and will thus not find the subriptionHandle in the extension, basically violating "isolation". // Therefore, we employ Optimistic Concurrency Control here to guarantee isolation: // we optimisticaly store subscriptionId in the handle first before calling pubSub.RegisterConsumer // and undo it in the case of failure. // There is no problem with that we call myExtension.SetObserver too early before the handle is registered in pub sub, // since this subscriptionId is unique (random Guid) and no one knows it anyway, unless successfully subscribed in the pubsub. var subriptionHandle = myExtension.SetObserver(subscriptionId, stream, observer, batchObserver, token); try { await pubSub.RegisterConsumer(subscriptionId, stream.InternalStreamId, myGrainReference); return subriptionHandle; } catch (Exception) { // Undo the previous call myExtension.SetObserver. myExtension.RemoveObserver(subscriptionId); throw; } } public Task<StreamSubscriptionHandle<T>> ResumeAsync( StreamSubscriptionHandle<T> handle, IAsyncObserver<T> observer, StreamSequenceToken token = null) { return ResumeAsyncImpl(handle, observer, null, token); } public Task<StreamSubscriptionHandle<T>> ResumeAsync( StreamSubscriptionHandle<T> handle, IAsyncBatchObserver<T> batchObserver, StreamSequenceToken token = null) { return ResumeAsyncImpl(handle, null, batchObserver, token); } private async Task<StreamSubscriptionHandle<T>> ResumeAsyncImpl( StreamSubscriptionHandle<T> handle, IAsyncObserver<T> observer, IAsyncBatchObserver<T> batchObserver, StreamSequenceToken token = null) { StreamSubscriptionHandleImpl<T> oldHandleImpl = CheckHandleValidity(handle); if (token != null && !IsRewindable) throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncObservable."); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Resume Token={Token}", token); await BindExtensionLazy(); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Resume - Connecting to Rendezvous {0} My GrainRef={1} Token={2}", pubSub, myGrainReference, token); StreamSubscriptionHandle<T> newHandle = myExtension.SetObserver(oldHandleImpl.SubscriptionId, stream, observer, batchObserver, token); // On failure caller should be able to retry using the original handle, so invalidate old handle only if everything succeeded. oldHandleImpl.Invalidate(); return newHandle; } public async Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle) { await BindExtensionLazy(); StreamSubscriptionHandleImpl<T> handleImpl = CheckHandleValidity(handle); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Unsubscribe StreamSubscriptionHandle={0}", handle); myExtension.RemoveObserver(handleImpl.SubscriptionId); // UnregisterConsumer from pubsub even if does not have this handle localy, to allow UnsubscribeAsync retries. if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Unsubscribe - Disconnecting from Rendezvous {0} My GrainRef={1}", pubSub, myGrainReference); await pubSub.UnregisterConsumer(handleImpl.SubscriptionId, stream.InternalStreamId); handleImpl.Invalidate(); } public async Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptions() { await BindExtensionLazy(); List<StreamSubscription> subscriptions= await pubSub.GetAllSubscriptions(stream.InternalStreamId, myGrainReference); return subscriptions.Select(sub => new StreamSubscriptionHandleImpl<T>(GuidId.GetGuidId(sub.SubscriptionId), stream)) .ToList<StreamSubscriptionHandle<T>>(); } public async Task Cleanup() { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Cleanup() called"); if (myExtension == null) return; var allHandles = myExtension.GetAllStreamHandles<T>(); var tasks = new List<Task>(); foreach (var handle in allHandles) { myExtension.RemoveObserver(handle.SubscriptionId); tasks.Add(pubSub.UnregisterConsumer(handle.SubscriptionId, stream.InternalStreamId)); } try { await Task.WhenAll(tasks); } catch (Exception exc) { logger.Warn(ErrorCode.StreamProvider_ConsumerFailedToUnregister, "Ignoring unhandled exception during PubSub.UnregisterConsumer", exc); } myExtension = null; } // Used in test. internal bool InternalRemoveObserver(StreamSubscriptionHandle<T> handle) { return myExtension != null && myExtension.RemoveObserver(((StreamSubscriptionHandleImpl<T>)handle).SubscriptionId); } internal Task<int> DiagGetConsumerObserversCount() { return Task.FromResult(myExtension.DiagCountStreamObservers<T>(stream.InternalStreamId)); } private async Task BindExtensionLazy() { if (myExtension == null) { using (await bindExtLock.LockAsync()) { if (myExtension == null) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("BindExtensionLazy - Binding local extension to stream runtime={0}", providerRuntime); (myExtension, myGrainReference) = providerRuntime.BindExtension<StreamConsumerExtension, IStreamConsumerExtension>(() => new StreamConsumerExtension(providerRuntime)); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("BindExtensionLazy - Connected Extension={0} GrainRef={1}", myExtension, myGrainReference); } } } } private StreamSubscriptionHandleImpl<T> CheckHandleValidity(StreamSubscriptionHandle<T> handle) { if (handle == null) throw new ArgumentNullException("handle"); if (!handle.StreamId.Equals(stream.StreamId)) throw new ArgumentException("Handle is not for this stream.", "handle"); var handleImpl = handle as StreamSubscriptionHandleImpl<T>; if (handleImpl == null) throw new ArgumentException("Handle type not supported.", "handle"); if (!handleImpl.IsValid) throw new ArgumentException("Handle is no longer valid. It has been used to unsubscribe or resume.", "handle"); return handleImpl; } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Linq; using Glass.Mapper.Umb.Configuration; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Services; namespace Glass.Mapper.Umb { /// <summary> /// Class UmbracoService /// </summary> public class UmbracoService : AbstractService, IUmbracoService { /// <summary> /// Gets the content service. /// </summary> /// <value> /// The content service. /// </value> public IContentService ContentService { get; private set; } public bool PublishedOnly { get; set; } /// <summary> /// Initializes a new instance of the <see cref="UmbracoService"/> class. /// </summary> /// <param name="contentService">The content service.</param> /// <param name="contextName">Name of the context.</param> public UmbracoService(IContentService contentService, string contextName = "Default") :base(contextName) { ContentService = contentService; } /// <summary> /// Initializes a new instance of the <see cref="UmbracoService"/> class. /// </summary> /// <param name="contentService">The content service.</param> /// <param name="context">The context.</param> public UmbracoService(IContentService contentService, Context context) : base(context ?? Context.Default) { ContentService = contentService; } /// <summary> /// Gets the home item. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns></returns> public T GetHomeItem<T>(bool isLazy = false, bool inferType = false) where T : class { var item = ContentService.GetChildren(-1).FirstOrDefault(); return CreateType(typeof(T), item, isLazy, inferType) as T; } /// <summary> /// Gets the item. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id">The id.</param> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns></returns> public T GetItem<T>(int? id, bool isLazy = false, bool inferType = false) where T : class { if (id == null) { return null; } var item = PublishedOnly ? ContentService.GetPublishedVersion(id.Value) : ContentService.GetById(id.Value); return CreateType(typeof(T), item, isLazy, inferType) as T; } /// <summary> /// Gets the item. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id">The id.</param> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns></returns> public T GetItem<T>(Guid id, bool isLazy = false, bool inferType = false) where T : class { var item = ContentService.GetById(id); if (PublishedOnly) item = ContentService.GetPublishedVersion(item.Id); return CreateType(typeof(T), item, isLazy, inferType) as T; } /// <summary> /// Saves the specified target. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target">The target.</param> /// <exception cref="System.NullReferenceException">Can not save class, could not find configuration for {0}.Formatted(typeof(T).FullName)</exception> /// <exception cref="MapperException">Could not save class, conent not found</exception> public void Save<T>(T target) { //TODO: should this be a separate context // UmbracoTypeContext context = new UmbracoTypeContext(); //TODO: ME - this may not work with a proxy var config = GlassContext.GetTypeConfiguration<UmbracoTypeConfiguration>(target); if (config == null) throw new NullReferenceException("Can not save class, could not find configuration for {0}".Formatted(typeof(T).FullName)); var item = config.ResolveItem(target, ContentService); if (item == null) throw new MapperException("Could not save class, conent not found"); WriteToItem(target, item, config); } /// <summary> /// Creates the type. /// </summary> /// <param name="type">The type.</param> /// <param name="content">The content.</param> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <param name="constructorParameters">Parameters to pass to the constructor of the new class. Must be in the order specified on the consturctor.</param> /// <returns></returns> /// <exception cref="System.NotSupportedException">Maximum number of constructor parameters is 4</exception> public object CreateType(Type type, IContent content, bool isLazy, bool inferType, params object[] constructorParameters) { if (content == null) return null; if (constructorParameters != null && constructorParameters.Length > 4) throw new NotSupportedException("Maximum number of constructor parameters is 4"); var creationContext = new UmbracoTypeCreationContext { UmbracoService = this, RequestedType = type, ConstructorParameters = constructorParameters, Content = content, InferType = inferType, IsLazy = isLazy, PublishedOnly = PublishedOnly }; var obj = InstantiateObject(creationContext); return obj; } /// <summary> /// Creates a class from the specified item /// </summary> /// <typeparam name="T">The type to return</typeparam> /// <param name="content">The content to load data from</param> /// <param name="isLazy">If true creates a proxy for the class</param> /// <param name="inferType">Infer the type to be loaded from the template</param> /// <returns> /// The item as the specified type /// </returns> public T CreateType<T>(IContent content, bool isLazy = false, bool inferType = false) where T : class { return (T)CreateType(typeof(T), content, isLazy, inferType); } /// <summary> /// Creates a class from the specified item with a single constructor parameter /// </summary> /// <typeparam name="T">The type to return</typeparam> /// <typeparam name="K">The type of the first constructor parameter</typeparam> /// <param name="content">The content to load data from</param> /// <param name="param1">The value of the first parameter of the constructor</param> /// <param name="isLazy">If true creates a proxy for the class</param> /// <param name="inferType">Infer the type to be loaded from the template</param> /// <returns> /// The item as the specified type /// </returns> public T CreateType<T, K>(IContent content, K param1, bool isLazy = false, bool inferType = false) { return (T)CreateType(typeof(T), content, isLazy, inferType, param1); } /// <summary> /// Creates a class from the specified item with a two constructor parameter /// </summary> /// <typeparam name="T">The type to return</typeparam> /// <typeparam name="K">The type of the first constructor parameter</typeparam> /// <typeparam name="L">The type of the second constructor parameter</typeparam> /// <param name="content">The content to load data from</param> /// <param name="param1">The value of the first parameter of the constructor</param> /// <param name="param2">The value of the second parameter of the constructor</param> /// <param name="isLazy">If true creates a proxy for the class</param> /// <param name="inferType">Infer the type to be loaded from the template</param> /// <returns> /// The item as the specified type /// </returns> public T CreateType<T, K, L>(IContent content, K param1, L param2, bool isLazy = false, bool inferType = false) { return (T)CreateType(typeof(T), content, isLazy, inferType, param1, param2); } /// <summary> /// Creates a class from the specified item with a two constructor parameter /// </summary> /// <typeparam name="T">The type to return</typeparam> /// <typeparam name="K">The type of the first constructor parameter</typeparam> /// <typeparam name="L">The type of the second constructor parameter</typeparam> /// <typeparam name="M">The type of the third constructor parameter</typeparam> /// <param name="content">The content to load data from</param> /// <param name="param1">The value of the first parameter of the constructor</param> /// <param name="param2">The value of the second parameter of the constructor</param> /// <param name="param3">The value of the third parameter of the constructor</param> /// <param name="isLazy">If true creates a proxy for the class</param> /// <param name="inferType">Infer the type to be loaded from the template</param> /// <returns> /// The item as the specified type /// </returns> public T CreateType<T, K, L, M>(IContent content, K param1, L param2, M param3, bool isLazy = false, bool inferType = false) { return (T)CreateType(typeof(T), content, isLazy, inferType, param1, param2, param3); } /// <summary> /// Creates a class from the specified item with a two constructor parameter /// </summary> /// <typeparam name="T">The type to return</typeparam> /// <typeparam name="K">The type of the first constructor parameter</typeparam> /// <typeparam name="L">The type of the second constructor parameter</typeparam> /// <typeparam name="M">The type of the third constructor parameter</typeparam> /// <typeparam name="N">The type of the fourth constructor parameter</typeparam> /// <param name="content">The content to load data from</param> /// <param name="param1">The value of the first parameter of the constructor</param> /// <param name="param2">The value of the second parameter of the constructor</param> /// <param name="param3">The value of the third parameter of the constructor</param> /// <param name="param4">The value of the fourth parameter of the constructor</param> /// <param name="isLazy">If true creates a proxy for the class</param> /// <param name="inferType">Infer the type to be loaded from the template</param> /// <returns> /// The item as the specified type /// </returns> public T CreateType<T, K, L, M, N>(IContent content, K param1, L param2, M param3, N param4, bool isLazy = false, bool inferType = false) { return (T)CreateType(typeof(T), content, isLazy, inferType, param1, param2, param3, param4); } /// <summary> /// Creates a new Umbraco class. /// </summary> /// <typeparam name="T">The type of the new item to create. This type must have either a TemplateId or BranchId defined on the UmbracoClassAttribute or fluent equivalent</typeparam> /// <typeparam name="TParent"></typeparam> /// <param name="parent">The parent of the new item to create. Must have the UmbracoIdAttribute or fluent equivalent</param> /// <param name="newItem">New item to create, must have the attribute UmbracoInfoAttribute of type UmbracoInfoType.Name or the fluent equivalent</param> /// <returns></returns> /// <exception cref="MapperException"> /// Failed to find configuration for new item type {0}.Formatted(typeof(T).FullName) /// or /// Failed to find configuration for parent item type {0}.Formatted(typeof(int).FullName) /// or /// Could not find parent item /// or /// The type {0} does not have a property with attribute UmbracoInfo(UmbracoInfoType.Name).Formatted(newType.Type.FullName) /// or /// Failed to create item /// </exception> public T Create<T, TParent>(TParent parent, T newItem) where T : class where TParent : class { UmbracoTypeConfiguration newType; try { newType = GlassContext.GetTypeConfiguration<UmbracoTypeConfiguration>(newItem); } catch (Exception ex) { throw new MapperException("Failed to find configuration for new item type {0}".Formatted(typeof(T).FullName), ex); } UmbracoTypeConfiguration parentType; try { parentType = GlassContext.GetTypeConfiguration<UmbracoTypeConfiguration>(parent); } catch (Exception ex) { throw new MapperException("Failed to find configuration for parent item type {0}".Formatted(typeof(int).FullName), ex); } var pItem = parentType.ResolveItem(parent, ContentService); if (pItem == null) throw new MapperException("Could not find parent item"); var nameProperty = newType.Properties.Where(x => x is UmbracoInfoConfiguration) .Cast<UmbracoInfoConfiguration>().FirstOrDefault(x => x.Type == UmbracoInfoType.Name); if (nameProperty == null) throw new MapperException("The type {0} does not have a property with attribute UmbracoInfo(UmbracoInfoType.Name)".Formatted(newType.Type.FullName)); string tempName = Guid.NewGuid().ToString(); var content = ContentService.CreateContent(tempName, pItem, newType.ContentTypeAlias); if (content == null) throw new MapperException("Failed to create item"); //write new data to the item WriteToItem(newItem, content); //then read it back var typeContext = new UmbracoTypeCreationContext { Content = content, UmbracoService = this }; newType.MapPropertiesToObject(newItem, this, typeContext); return newItem; } /// <summary> /// Writes to item. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target">The target.</param> /// <param name="content">The content.</param> /// <param name="config">The config.</param> public void WriteToItem<T>(T target, IContent content, UmbracoTypeConfiguration config = null) { if (config == null) config = GlassContext.GetTypeConfiguration<UmbracoTypeConfiguration>(target); var savingContext = new UmbracoTypeSavingContext { Config = config, Content = content, Object = target }; //ME-an item with no versions should be null SaveObject(savingContext); } /// <summary> /// Deletes an item /// </summary> /// <param name="item"></param> /// <typeparam name="T"></typeparam> /// <exception cref="MapperException"></exception> public void Delete<T>(T item) where T : class { var type = GlassContext.GetTypeConfiguration <UmbracoTypeConfiguration>(item) as UmbracoTypeConfiguration; var umbItem = type.ResolveItem(item, ContentService); if (umbItem == null) throw new MapperException("Content not found"); ContentService.Delete(umbItem); } /// <summary> /// Saves the object. /// </summary> /// <param name="abstractTypeSavingContext">The abstract type saving context.</param> public override void SaveObject(AbstractTypeSavingContext abstractTypeSavingContext) { ContentService.Save(((UmbracoTypeSavingContext) abstractTypeSavingContext).Content); base.SaveObject(abstractTypeSavingContext); } /// <summary> /// Creates the data mapping context. /// </summary> /// <param name="abstractTypeCreationContext">The abstract type creation context.</param> /// <param name="obj">The obj.</param> /// <returns></returns> public override AbstractDataMappingContext CreateDataMappingContext(AbstractTypeCreationContext abstractTypeCreationContext, Object obj) { var umbTypeContext = abstractTypeCreationContext as UmbracoTypeCreationContext; return new UmbracoDataMappingContext(obj, umbTypeContext.Content, this, umbTypeContext.PublishedOnly); } /// <summary> /// Used to create the context used by DataMappers to map data from a class /// </summary> /// <param name="creationContext"></param> /// <returns></returns> public override AbstractDataMappingContext CreateDataMappingContext(AbstractTypeSavingContext creationContext) { var umbContext = creationContext as UmbracoTypeSavingContext; return new UmbracoDataMappingContext(umbContext.Object, umbContext.Content, this, umbContext.PublishedOnly); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Services.Base; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Services.InventoryService { /// <summary> /// Basically a hack to give us a Inventory library while we don't have a inventory server /// once the server is fully implemented then should read the data from that /// </summary> public class LibraryService : ServiceBase, ILibraryService { /// <summary> /// Holds the root library folder and all its descendents. This is really only used during inventory /// setup so that we don't have to repeatedly search the tree of library folders. /// </summary> protected Dictionary<UUID, InventoryFolderImpl> libraryFolders = new Dictionary<UUID, InventoryFolderImpl>(); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private UUID libOwner = new UUID("11111111-1111-0000-0000-000100bba000"); private InventoryFolderImpl m_LibraryRootFolder; public LibraryService(IConfigSource config) : base(config) { string pLibrariesLocation = Path.Combine("inventory", "Libraries.xml"); string pLibName = "OpenSim Library"; IConfig libConfig = config.Configs["LibraryService"]; if (libConfig != null) { pLibrariesLocation = libConfig.GetString("DefaultLibrary", pLibrariesLocation); pLibName = libConfig.GetString("LibraryName", pLibName); } m_log.Debug("[LIBRARY]: Starting library service..."); m_LibraryRootFolder = new InventoryFolderImpl(); m_LibraryRootFolder.Owner = libOwner; m_LibraryRootFolder.ID = new UUID("00000112-000f-0000-0000-000100bba000"); m_LibraryRootFolder.Name = pLibName; m_LibraryRootFolder.ParentID = UUID.Zero; m_LibraryRootFolder.Type = (short)8; m_LibraryRootFolder.Version = (ushort)1; libraryFolders.Add(m_LibraryRootFolder.ID, m_LibraryRootFolder); LoadLibraries(pLibrariesLocation); } private delegate void ConfigAction(IConfig config, string path); public InventoryFolderImpl LibraryRootFolder { get { return m_LibraryRootFolder; } } public InventoryItemBase CreateItem(UUID inventoryID, UUID assetID, string name, string description, int assetType, int invType, UUID parentFolderID) { InventoryItemBase item = new InventoryItemBase(); item.Owner = libOwner; item.CreatorId = libOwner.ToString(); item.ID = inventoryID; item.AssetID = assetID; item.Description = description; item.Name = name; item.AssetType = assetType; item.InvType = invType; item.Folder = parentFolderID; item.BasePermissions = 0x7FFFFFFF; item.EveryOnePermissions = 0x7FFFFFFF; item.CurrentPermissions = 0x7FFFFFFF; item.NextPermissions = 0x7FFFFFFF; return item; } /// <summary> /// Looks like a simple getter, but is written like this for some consistency with the other Request /// methods in the superclass /// </summary> /// <returns></returns> public Dictionary<UUID, InventoryFolderImpl> GetAllFolders() { Dictionary<UUID, InventoryFolderImpl> fs = new Dictionary<UUID, InventoryFolderImpl>(); fs.Add(m_LibraryRootFolder.ID, m_LibraryRootFolder); List<InventoryFolderImpl> fis = TraverseFolder(m_LibraryRootFolder); foreach (InventoryFolderImpl f in fis) { fs.Add(f.ID, f); } //return libraryFolders; return fs; } /// <summary> /// Use the asset set information at path to load assets /// </summary> /// <param name="path"></param> /// <param name="assets"></param> protected void LoadLibraries(string librariesControlPath) { m_log.InfoFormat("[LIBRARY INVENTORY]: Loading library control file {0}", librariesControlPath); LoadFromFile(librariesControlPath, "Libraries control", ReadLibraryFromConfig); } /// <summary> /// Read a library set from config /// </summary> /// <param name="config"></param> protected void ReadLibraryFromConfig(IConfig config, string path) { string basePath = Path.GetDirectoryName(path); string foldersPath = Path.Combine( basePath, config.GetString("foldersFile", String.Empty)); LoadFromFile(foldersPath, "Library folders", ReadFolderFromConfig); string itemsPath = Path.Combine( basePath, config.GetString("itemsFile", String.Empty)); LoadFromFile(itemsPath, "Library items", ReadItemFromConfig); } /// <summary> /// Load the given configuration at a path and perform an action on each Config contained within it /// </summary> /// <param name="path"></param> /// <param name="fileDescription"></param> /// <param name="action"></param> private static void LoadFromFile(string path, string fileDescription, ConfigAction action) { if (File.Exists(path)) { try { XmlConfigSource source = new XmlConfigSource(path); for (int i = 0; i < source.Configs.Count; i++) { action(source.Configs[i], path); } } catch (XmlException e) { m_log.ErrorFormat("[LIBRARY INVENTORY]: Error loading {0} : {1}", path, e); } } else { m_log.ErrorFormat("[LIBRARY INVENTORY]: {0} file {1} does not exist!", fileDescription, path); } } /// <summary> /// Read a library inventory folder from a loaded configuration /// </summary> /// <param name="source"></param> private void ReadFolderFromConfig(IConfig config, string path) { InventoryFolderImpl folderInfo = new InventoryFolderImpl(); folderInfo.ID = new UUID(config.GetString("folderID", m_LibraryRootFolder.ID.ToString())); folderInfo.Name = config.GetString("name", "unknown"); folderInfo.ParentID = new UUID(config.GetString("parentFolderID", m_LibraryRootFolder.ID.ToString())); folderInfo.Type = (short)config.GetInt("type", 8); folderInfo.Owner = libOwner; folderInfo.Version = 1; if (libraryFolders.ContainsKey(folderInfo.ParentID)) { InventoryFolderImpl parentFolder = libraryFolders[folderInfo.ParentID]; libraryFolders.Add(folderInfo.ID, folderInfo); parentFolder.AddChildFolder(folderInfo); // m_log.InfoFormat("[LIBRARY INVENTORY]: Adding folder {0} ({1})", folderInfo.name, folderInfo.folderID); } else { m_log.WarnFormat( "[LIBRARY INVENTORY]: Couldn't add folder {0} ({1}) since parent folder with ID {2} does not exist!", folderInfo.Name, folderInfo.ID, folderInfo.ParentID); } } /// <summary> /// Read a library inventory item metadata from a loaded configuration /// </summary> /// <param name="source"></param> private void ReadItemFromConfig(IConfig config, string path) { InventoryItemBase item = new InventoryItemBase(); item.Owner = libOwner; item.CreatorId = libOwner.ToString(); item.ID = new UUID(config.GetString("inventoryID", m_LibraryRootFolder.ID.ToString())); item.AssetID = new UUID(config.GetString("assetID", item.ID.ToString())); item.Folder = new UUID(config.GetString("folderID", m_LibraryRootFolder.ID.ToString())); item.Name = config.GetString("name", String.Empty); item.Description = config.GetString("description", item.Name); item.InvType = config.GetInt("inventoryType", 0); item.AssetType = config.GetInt("assetType", item.InvType); item.CurrentPermissions = (uint)config.GetLong("currentPermissions", (uint)PermissionMask.All); item.NextPermissions = (uint)config.GetLong("nextPermissions", (uint)PermissionMask.All); item.EveryOnePermissions = (uint)config.GetLong("everyonePermissions", (uint)PermissionMask.All - (uint)PermissionMask.Modify); item.BasePermissions = (uint)config.GetLong("basePermissions", (uint)PermissionMask.All); item.Flags = (uint)config.GetInt("flags", 0); if (libraryFolders.ContainsKey(item.Folder)) { InventoryFolderImpl parentFolder = libraryFolders[item.Folder]; try { parentFolder.Items.Add(item.ID, item); } catch (Exception) { m_log.WarnFormat("[LIBRARY INVENTORY] Item {1} [{0}] not added, duplicate item", item.ID, item.Name); } } else { m_log.WarnFormat( "[LIBRARY INVENTORY]: Couldn't add item {0} ({1}) since parent folder with ID {2} does not exist!", item.Name, item.ID, item.Folder); } } private List<InventoryFolderImpl> TraverseFolder(InventoryFolderImpl node) { List<InventoryFolderImpl> folders = node.RequestListOfFolderImpls(); List<InventoryFolderImpl> subs = new List<InventoryFolderImpl>(); foreach (InventoryFolderImpl f in folders) subs.AddRange(TraverseFolder(f)); folders.AddRange(subs); return folders; } } }
/* Copyright (c) 2007- DEVSENSE Copyright (c) 2003-2006 Martin Maly, Ladislav Prosek, Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Linq; using PHP.Core.AST; using FcnParam = System.Tuple<System.Collections.Generic.List<PHP.Core.AST.TypeRef>, System.Collections.Generic.List<PHP.Core.AST.ActualParam>, System.Collections.Generic.List<PHP.Core.AST.Expression>>; namespace PHP.Core.Parsers { #region Helpers /// <summary> /// Sink for specific language elements. /// Methods of this interface are called by the parser. /// In this way implementers are notified about declarations already during parsing, /// note root AST is not available at this time. /// </summary> public interface IReductionsSink { void InclusionReduced(Parser/*!*/ parser, IncludingEx/*!*/ decl); void FunctionDeclarationReduced(Parser/*!*/ parser, FunctionDecl/*!*/ decl); void TypeDeclarationReduced(Parser/*!*/ parser, TypeDecl/*!*/ decl); void GlobalConstantDeclarationReduced(Parser/*!*/ parser, GlobalConstantDecl/*!*/ decl); void NamespaceDeclReduced(Parser/*!*/ parser, NamespaceDecl/*!*/ decl); void LambdaFunctionReduced(Parser/*!*/ parser, LambdaFunctionExpr/*!*/ decl); } // Due to a MCS bug, it has to be in the other partial class in generated (Generated/Parser.cs) // .. uncomment the following once it is fixed! [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)] public partial struct SemanticValueType { public override string ToString() { if (Object != null) return Object.ToString(); if (Offset != 0) return String.Format("[{0}-{1}]", Offset, Integer); if (Double != 0.0) return Double.ToString(); return Integer.ToString(); } } #endregion public partial class Parser : ICommentsSink, IScannerHandler { #region Reductions Sinks private sealed class NullReductionsSink : IReductionsSink { void IReductionsSink.InclusionReduced(Parser/*!*/ parser, IncludingEx/*!*/ incl) { } void IReductionsSink.FunctionDeclarationReduced(Parser/*!*/ parser, FunctionDecl/*!*/ decl) { } void IReductionsSink.TypeDeclarationReduced(Parser/*!*/ parser, TypeDecl/*!*/ decl) { } void IReductionsSink.GlobalConstantDeclarationReduced(Parser/*!*/ parser, GlobalConstantDecl/*!*/ decl) { } void IReductionsSink.NamespaceDeclReduced(Parser parser, NamespaceDecl decl) { } void IReductionsSink.LambdaFunctionReduced(Parser parser, LambdaFunctionExpr decl) { } } public sealed class ReductionsCounter : IReductionsSink { public int InclusionCount { get { return _inclusionCount; } } private int _inclusionCount = 0; public int FunctionCount { get { return _functionCount; } } private int _functionCount = 0; public int TypeCount { get { return _typeCount; } } private int _typeCount = 0; public int ConstantCount { get { return _constantCount; } } private int _constantCount = 0; void IReductionsSink.InclusionReduced(Parser/*!*/ parser, IncludingEx/*!*/ incl) { _inclusionCount++; } void IReductionsSink.FunctionDeclarationReduced(Parser/*!*/ parser, FunctionDecl/*!*/ decl) { _functionCount++; } void IReductionsSink.TypeDeclarationReduced(Parser/*!*/ parser, TypeDecl/*!*/ decl) { _typeCount++; } void IReductionsSink.GlobalConstantDeclarationReduced(Parser/*!*/ parser, GlobalConstantDecl/*!*/ decl) { _constantCount++; } void IReductionsSink.NamespaceDeclReduced(Parser parser, NamespaceDecl decl) { } void IReductionsSink.LambdaFunctionReduced(Parser parser, LambdaFunctionExpr decl) { } } #endregion protected sealed override int EofToken { get { return (int)Tokens.EOF; } } protected sealed override int ErrorToken { get { return (int)Tokens.ERROR; } } protected override Text.Span CombinePositions(Text.Span first, Text.Span last) { if (last.IsValid) { if (first.IsValid) return Text.Span.Combine(first, last); else return last; } else return first; } protected override Text.Span InvalidPosition { get { return Text.Span.Invalid; } } private Scanner scanner; private LanguageFeatures features; public ErrorSink ErrorSink { get { return errors; } } private ErrorSink errors; public SourceUnit SourceUnit { get { return sourceUnit; } } private SourceUnit sourceUnit; private IReductionsSink/*!*/reductionsSink; private bool unicodeSemantics; private TextReader reader; private Scope currentScope; public bool AllowGlobalCode { get { return allowGlobalCode; } set { allowGlobalCode = value; } } private bool allowGlobalCode; /// <summary> /// The root of AST. /// </summary> private GlobalCode astRoot; private const int strBufSize = 100; private NamespaceDecl currentNamespace; private bool IsInGlobalNamespace { get { return currentNamespace == null || currentNamespace.QualifiedName.Namespaces.Length == 0; } } private string CurrentNamespaceName { get { return IsInGlobalNamespace ? string.Empty : currentNamespace.QualifiedName.ToString(); } } /// <summary> /// Special names not namespaced. These names will not be translated using aliases and current namespace. /// The list is dynamically extended during parsing with generic arguments. /// </summary> private readonly HashSet<string>/*!*/reservedTypeNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { Name.SelfClassName.Value, Name.StaticClassName.Value, Name.ParentClassName.Value, }; // stack of string buffers; used when processing encaps strings private readonly Stack<PhpStringBuilder> strBufStack = new Stack<PhpStringBuilder>(100); public Parser() { } private new bool Parse() { return false; } public GlobalCode Parse(SourceUnit/*!*/ sourceUnit, TextReader/*!*/ reader, ErrorSink/*!*/ errors, IReductionsSink reductionsSink, Lexer.LexicalStates initialLexicalState, LanguageFeatures features, int positionShift = 0) { Debug.Assert(reader != null && errors != null); // initialization: this.sourceUnit = sourceUnit; this.errors = errors; this.features = features; this.reader = reader; this.reductionsSink = reductionsSink ?? new NullReductionsSink(); InitializeFields(); this.scanner = new Scanner(reader, sourceUnit, errors, this, this, features, positionShift) { CurrentLexicalState = initialLexicalState }; this.scanner.CurrentLexicalState = initialLexicalState; this.currentScope = new Scope(1); // starts assigning scopes from 2 (1 is reserved for prepended inclusion) this.unicodeSemantics = (features & LanguageFeatures.UnicodeSemantics) != 0; base.Scanner = this.scanner; base.Parse(); GlobalCode result = astRoot; // clean and let GC collect unused AST and other stuff: ClearFields(); return result; } private void InitializeFields() { InitializeCommentSink(); strBufStack.Clear(); condLevel = 0; Debug.Assert(sourceUnit != null); if (sourceUnit.CurrentNamespace.HasValue && sourceUnit.CurrentNamespace.Value.Namespaces.Length > 0) { // J: inject current namespace from sourceUnit: this.currentNamespace = new AST.NamespaceDecl(default(Text.Span), sourceUnit.CurrentNamespace.Value.ToStringList(), true); // add aliases into the namespace: if (sourceUnit.Naming.Aliases != null) foreach (var alias in sourceUnit.Naming.Aliases) this.currentNamespace.Naming.AddAlias(alias.Key, alias.Value); } else { this.currentNamespace = null; } } private void ClearFields() { ClearCommentSink(); scanner = null; features = 0; errors = null; sourceUnit = null; reductionsSink = null; astRoot = null; reader = null; } #region Conditional Code, Scope private int condLevel; private void EnterConditionalCode() { condLevel++; } private void LeaveConditionalCode() { Debug.Assert(condLevel > 0); condLevel--; } public bool IsCurrentCodeConditional { get { return condLevel > 0; } } public bool IsCurrentCodeOneLevelConditional { get { return condLevel > 1; } } internal Scope GetScope() { currentScope.Increment(); return currentScope; } #endregion Conditional Code #region Complex Productions private Expression CreateConcatExOrStringLiteral(Text.Span p, List<Expression> exprs, bool trimEoln) { PhpStringBuilder encapsed_str = strBufStack.Pop(); if (trimEoln) encapsed_str.TrimEoln(); if (exprs.Count > 0) { if (encapsed_str.Length > 0) exprs.Add(encapsed_str.CreateLiteral()); return new ConcatEx(p, exprs); } else { return encapsed_str.CreateLiteral(); } } private VariableUse CreateStaticFieldUse(Text.Span span, CompoundVarUse/*!*/ className, CompoundVarUse/*!*/ field) { return CreateStaticFieldUse(span, new IndirectTypeRef(span, className, TypeRef.EmptyList), field); } private VariableUse CreateStaticFieldUse(Text.Span span, GenericQualifiedName/*!*/ className, Text.Span classNameSpan, CompoundVarUse/*!*/ field) { return CreateStaticFieldUse(span, DirectTypeRef.FromGenericQualifiedName(classNameSpan, className), field); } private VariableUse CreateStaticFieldUse(Text.Span span, TypeRef/*!*/ typeRef, CompoundVarUse/*!*/ field) { DirectVarUse dvu; IndirectVarUse ivu; if ((dvu = field as DirectVarUse) != null) { return new DirectStFldUse(span, typeRef, dvu.VarName, field.Span); } else if ((ivu = field as IndirectVarUse) != null) { return new IndirectStFldUse(span, typeRef, ivu.VarNameEx); } else { ItemUse iu = (ItemUse)field; iu.Array = CreateStaticFieldUse(iu.Array.Span, typeRef, (CompoundVarUse)iu.Array); return iu; } } private ForeachStmt/*!*/ CreateForeachStmt(Text.Span pos, Expression/*!*/ enumeree, ForeachVar/*!*/ var1, Text.Span pos1, ForeachVar var2, Statement/*!*/ body) { ForeachVar key, value; if (var2 != null) { key = var1; value = var2; if (key.Alias) { errors.Add(Errors.KeyAlias, SourceUnit, pos1); key.Alias = false; } } else { key = null; value = var1; } return new ForeachStmt(pos, enumeree, key, value, body); } private void CheckVariableUse(Text.Span span, object item) { if (item as VariableUse == null) { errors.Add(FatalErrors.CheckVarUseFault, SourceUnit, span); throw new CompilerException(); } } private FcnParam/*!*/ CreateFcnParam(FcnParam/*!*/fcnParam, Expression/*!*/arrayDereference) { var arrayKeyList = fcnParam.Item3; if (arrayKeyList == null) arrayKeyList = new List<Expression>(1); arrayKeyList.Add(arrayDereference); return new FcnParam(fcnParam.Item1, fcnParam.Item2, arrayKeyList); } private static VarLikeConstructUse/*!*/ CreateFcnArrayDereference(Text.Span pos, VarLikeConstructUse/*!*/varUse, List<Expression> arrayKeysExpression) { if (arrayKeysExpression != null && arrayKeysExpression.Count > 0) { // wrap fcnCall into ItemUse foreach (var keyExpr in arrayKeysExpression) varUse = new ItemUse(pos, varUse, keyExpr, true); } return varUse; } private static VarLikeConstructUse/*!*/ DereferenceFunctionArrayAccess(VarLikeConstructUse/*!*/varUse) { ItemUse itemUse; while ((itemUse = varUse as ItemUse) != null && itemUse.IsFunctionArrayDereferencing) varUse = itemUse.Array; return varUse; } private static VarLikeConstructUse/*!*/ CreateVariableUse(Text.Span pos, VarLikeConstructUse/*!*/ variable, VarLikeConstructUse/*!*/ property, FcnParam parameters, VarLikeConstructUse chain) { if (parameters != null) { if (property is ItemUse) { property.IsMemberOf = variable; property = new IndirectFcnCall(pos, property, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1); } else { DirectVarUse direct_use; if ((direct_use = property as DirectVarUse) != null) { QualifiedName method_name = new QualifiedName(new Name(direct_use.VarName.Value), Name.EmptyNames); property = new DirectFcnCall(pos, method_name, null, property.Span, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1); } else { IndirectVarUse indirect_use = (IndirectVarUse)property; property = new IndirectFcnCall(pos, indirect_use.VarNameEx, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1); } property.IsMemberOf = variable; } // wrap into ItemUse property = CreateFcnArrayDereference(pos, property, parameters.Item3); } else { property.IsMemberOf = variable; } if (chain != null) { // finds the first variable use in the chain and connects it to the property VarLikeConstructUse first_in_chain = chain; for (;;) { first_in_chain = DereferenceFunctionArrayAccess(first_in_chain); if (first_in_chain.IsMemberOf != null) first_in_chain = first_in_chain.IsMemberOf; else break; } first_in_chain.IsMemberOf = property; return chain; } else { return property; } } private static VarLikeConstructUse/*!*/ CreatePropertyVariable(Text.Span pos, CompoundVarUse/*!*/ property, FcnParam parameters) { if (parameters != null) { DirectVarUse direct_use; IndirectVarUse indirect_use; VarLikeConstructUse fcnCall; if ((direct_use = property as DirectVarUse) != null) { QualifiedName method_name = new QualifiedName(new Name(direct_use.VarName.Value), Name.EmptyNames); fcnCall = new DirectFcnCall(pos, method_name, null, property.Span, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1); } else if ((indirect_use = property as IndirectVarUse) != null) { fcnCall = new IndirectFcnCall(pos, indirect_use.VarNameEx, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1); } else { fcnCall = new IndirectFcnCall(pos, (ItemUse)property, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1); } // wrap fcnCall into ItemUse fcnCall = CreateFcnArrayDereference(pos, fcnCall, parameters.Item3); return fcnCall; } else { return property; } } private static VarLikeConstructUse/*!*/ CreatePropertyVariables(VarLikeConstructUse chain, VarLikeConstructUse/*!*/ member) { // dereference function array access: var element = DereferenceFunctionArrayAccess(member); // if (chain != null) { IndirectFcnCall ifc = element as IndirectFcnCall; if (ifc != null && ifc.NameExpr as ItemUse != null) { // we know that FcNAme is VLCU and not Expression, because chain is being parsed: ((VarLikeConstructUse)ifc.NameExpr).IsMemberOf = chain; } else { element.IsMemberOf = chain; } } else { element.IsMemberOf = null; } return member; } private DirectFcnCall/*!*/ CreateDirectFcnCall(Text.Span pos, QualifiedName qname, Text.Span qnamePosition, List<ActualParam> args, List<TypeRef> typeArgs) { QualifiedName? fallbackQName; TranslateFallbackQualifiedName(ref qname, out fallbackQName, this.CurrentNaming.FunctionAliases); return new DirectFcnCall(pos, qname, fallbackQName, qnamePosition, args, typeArgs); } private GlobalConstUse/*!*/ CreateGlobalConstUse(Text.Span pos, QualifiedName qname) { QualifiedName? fallbackQName; if (qname.IsSimpleName && (qname == QualifiedName.Null || qname == QualifiedName.True || qname == QualifiedName.False)) { // special global consts fallbackQName = null; qname.IsFullyQualifiedName = true; } else { TranslateFallbackQualifiedName(ref qname, out fallbackQName, this.CurrentNaming.ConstantAliases); } return new GlobalConstUse(pos, qname, fallbackQName); } /// <summary> /// Process <paramref name="qname"/>. Ensure <paramref name="qname"/> will be fully qualified. /// Outputs <paramref name="fallbackQName"/> which should be used if <paramref name="qname"/> does not refer to any existing entity. /// </summary> /// <param name="qname"></param> /// <param name="fallbackQName"></param> /// <remarks>Used for handling global function call and global constant use. /// <param name="aliases">Optional. Dictionary of aliases for the <paramref name="qname"/>.</param> /// In PHP entity in current namespace is tried first, then it falls back to global namespace.</remarks> private void TranslateFallbackQualifiedName(ref QualifiedName qname, out QualifiedName? fallbackQName, Dictionary<string, QualifiedName> aliases) { // aliasing QualifiedName tmp; if (qname.IsSimpleName && aliases != null && aliases.TryGetValue(qname.Name.Value, out tmp)) { qname = tmp; fallbackQName = null; return; } // qname = TranslateNamespace(qname); if (!qname.IsFullyQualifiedName && qname.IsSimpleName && !IsInGlobalNamespace && !sourceUnit.HasImportedNamespaces && !reservedTypeNames.Contains(qname.Name.Value)) { // "\foo" fallbackQName = new QualifiedName(qname.Name) { IsFullyQualifiedName = true }; // "namespace\foo" qname = new QualifiedName(qname.Name, currentNamespace.QualifiedName.Namespaces) { IsFullyQualifiedName = true }; } else { fallbackQName = null; qname.IsFullyQualifiedName = true; // just ensure } } private Expression/*!*/ CheckInitializer(Text.Span pos, Expression/*!*/ initializer) { if (initializer is ArrayEx) { errors.Add(Errors.ArrayInClassConstant, SourceUnit, pos); return new NullLiteral(pos); } return initializer; } private PhpMemberAttributes CheckPrivateType(Text.Span pos) { if (currentNamespace != null) { errors.Add(Errors.PrivateClassInGlobalNamespace, SourceUnit, pos); return PhpMemberAttributes.None; } return PhpMemberAttributes.Private; } private int CheckPartialType(Text.Span pos) { if (IsCurrentCodeConditional) { errors.Add(Errors.PartialConditionalDeclaration, SourceUnit, pos); return 0; } if (sourceUnit.IsTransient) { errors.Add(Errors.PartialTransientDeclaration, SourceUnit, pos); return 0; } if (!sourceUnit.IsPure) { errors.Add(Errors.PartialImpureDeclaration, SourceUnit, pos); return 0; } return 1; } private Statement/*!*/ CheckGlobalStatement(Statement/*!*/ statement) { if (sourceUnit.IsPure && !allowGlobalCode) { if (!statement.SkipInPureGlobalCode()) errors.Add(Errors.GlobalCodeInPureUnit, SourceUnit, statement.Span); return EmptyStmt.Skipped; } return statement; } /// <summary> /// Checks whether a reserved class name is used in generic qualified name. /// </summary> private void CheckReservedNamesAbsence(Tuple<GenericQualifiedName, Text.Span> genericName) { if (genericName != null) CheckReservedNamesAbsence(genericName.Item1, genericName.Item2); } private void CheckReservedNamesAbsence(GenericQualifiedName genericName, Text.Span span) { if (genericName.QualifiedName.IsReservedClassName) { errors.Add(Errors.CannotUseReservedName, SourceUnit, span, genericName.QualifiedName.Name); } if (genericName.GenericParams != null) CheckReservedNamesAbsence(genericName.GenericParams, span); } private void CheckReservedNamesAbsence(object[] staticTypeRefs, Text.Span span) { foreach (object static_type_ref in staticTypeRefs) if (static_type_ref is GenericQualifiedName) CheckReservedNamesAbsence((GenericQualifiedName)static_type_ref, span); } private void CheckReservedNamesAbsence(List<Tuple<GenericQualifiedName, Text.Span>> genericNames) { if (genericNames != null) { int count = genericNames.Count; for (int i = 0; i < count; i++) CheckReservedNamesAbsence(genericNames[i].Item1, genericNames[i].Item2); } } private bool CheckReservedNameAbsence(Name typeName, Text.Span span) { if (typeName.IsReservedClassName) { errors.Add(Errors.CannotUseReservedName, SourceUnit, span, typeName); return false; } return true; } private void CheckTypeNameInUse(Name typeName, Text.Span span) { var aliases = this.CurrentNaming.Aliases; if (reservedTypeNames.Contains(typeName.Value) || (aliases != null && aliases.ContainsKey(typeName.Value))) errors.Add(FatalErrors.ClassAlreadyInUse, SourceUnit, span, CurrentNamespaceName + typeName.Value); } /// <summary> /// Check is given <paramref name="declarerName"/> and its <paramref name="typeParams"/> are without duplicity. /// </summary> /// <param name="typeParams">Generic type parameters.</param> /// <param name="declarerName">Type name.</param> private void CheckTypeParameterNames(List<FormalTypeParam> typeParams, string/*!*/declarerName) { if (typeParams == null) return; var aliases = this.CurrentNaming.Aliases; for (int i = 0; i < typeParams.Count; i++) { if (typeParams[i].Name.Equals(declarerName)) { ErrorSink.Add(Errors.GenericParameterCollidesWithDeclarer, SourceUnit, typeParams[i].Span, declarerName); } else if (aliases != null && aliases.ContainsKey(typeParams[i].Name.Value)) { ErrorSink.Add(Errors.GenericAlreadyInUse, SourceUnit, typeParams[i].Span, typeParams[i].Name.Value); } else { for (int j = 0; j < i; j++) { if (typeParams[j].Name.Equals(typeParams[i].Name)) errors.Add(Errors.DuplicateGenericParameter, SourceUnit, typeParams[i].Span); } } } } private CustomAttribute.TargetSelectors IdentifierToTargetSelector(Text.Span span, string/*!*/ identifier) { if (identifier.EqualsOrdinalIgnoreCase("assembly")) return CustomAttribute.TargetSelectors.Assembly; if (identifier.EqualsOrdinalIgnoreCase("module")) return CustomAttribute.TargetSelectors.Module; if (identifier.EqualsOrdinalIgnoreCase("return")) return CustomAttribute.TargetSelectors.Return; errors.Add(Errors.InvalidAttributeTargetSelector, SourceUnit, span, identifier); return CustomAttribute.TargetSelectors.Default; } private List<CustomAttribute>/*!*/CustomAttributes(List<CustomAttribute>/*!*/ attrs, CustomAttribute.TargetSelectors targetSelector) { for (int i = 0; i < attrs.Count; i++) attrs[i].TargetSelector = targetSelector; return attrs; } #endregion //#region Imports ///// <summary> ///// Import of a particular type or function. ///// </summary> //public void AddImport(Position position, DeclarationKind kind, List<string>/*!*/ names, string aliasName) //{ // QualifiedName qn = new QualifiedName(names, true, true); // Name alias = (aliasName != null) ? new Name(aliasName) : qn.Name; // switch (kind) // { // case DeclarationKind.Type: // if (!sourceUnit.AddTypeAlias(qn, alias)) // errors.Add(Errors.ConflictingTypeAliases, SourceUnit, position); // break; // case DeclarationKind.Function: // if (!sourceUnit.AddFunctionAlias(qn, alias)) // errors.Add(Errors.ConflictingFunctionAliases, SourceUnit, position); // break; // case DeclarationKind.Constant: // if (!sourceUnit.AddConstantAlias(qn, alias)) // errors.Add(Errors.ConflictingConstantAliases, SourceUnit, position); // break; // } //} ///// <summary> ///// Import of a namespace with a qualified name. ///// </summary> //public void AddImport(List<string>/*!*/ namespaceNames) //{ // sourceUnit.AddImportedNamespace(new QualifiedName(namespaceNames, false, true)); //} ///// <summary> ///// Import of a namespace with a simple name. ///// </summary> //public void AddImport(string namespaceName) //{ // sourceUnit.AddImportedNamespace(new QualifiedName(Name.EmptyBaseName, new Name[] { new Name(namespaceName) })); //} public void AddImport(QualifiedName namespaceName) { if (sourceUnit.IsPure) { ErrorSink.Add(Warnings.ImportDeprecated, SourceUnit, this.yypos); // deprecated statement sourceUnit.ImportedNamespaces.Add(namespaceName); } else { ErrorSink.Add(Errors.ImportOnlyInPureMode, sourceUnit, this.yypos); // does actually not happen, since T_IMPORT is not recognized outside Pure mode at all } } //#endregion #region aliases (use_statement) /// <summary> /// Dictionary of PHP aliases for the current scope. /// </summary> private NamingContext/*!*/ CurrentNaming { get { return (currentNamespace != null) ? currentNamespace.Naming : this.sourceUnit.Naming; } } private void AddAliases(List<KeyValuePair<string, QualifiedName>>/*!*/list) { foreach (var pair in list) AddAlias(pair.Value, pair.Key); } private void AddFunctionAliases(List<KeyValuePair<string, QualifiedName>>/*!*/list) { foreach (var pair in list) AddFunctionAlias(pair.Value, pair.Key); } private void AddConstAliases(List<KeyValuePair<string, QualifiedName>>/*!*/list) { foreach (var pair in list) AddConstAlias(pair.Value, pair.Key); } /// <summary> /// Add PHP alias (through <c>use</c> keyword). /// </summary> /// <param name="fullQualifiedName">Fully qualified aliased name.</param> /// <param name="alias">If not null, represents the alias name. Otherwise the last component from <paramref name="fullQualifiedName"/> is used.</param> private void AddAlias(QualifiedName fullQualifiedName, string alias) { Debug.Assert(!string.IsNullOrEmpty(fullQualifiedName.Name.Value)); Debug.Assert(fullQualifiedName.IsFullyQualifiedName); // alias = alias ?? fullQualifiedName.Name.Value; // check if it aliases itself: QualifiedName qualifiedAlias = new QualifiedName( new Name(alias), (currentNamespace != null) ? currentNamespace.QualifiedName : new QualifiedName(Name.EmptyBaseName)); if (fullQualifiedName == qualifiedAlias) return; // ignore // add the alias: var naming = this.CurrentNaming; // check for alias duplicity and add the alias: // TODO: check if there is no conflict with some class declaration (this should be in runtime ... but this overriding looks like useful features) if (reservedTypeNames.Contains(alias) || !naming.AddAlias(alias, fullQualifiedName)) { errors.Add(FatalErrors.AliasAlreadyInUse, this.sourceUnit, this.yypos/*TODO: position of the alias itself*/, fullQualifiedName.NamespacePhpName, alias); } } private void AddFunctionAlias(QualifiedName qname, string alias) { alias = alias ?? qname.Name.Value; if (!this.CurrentNaming.AddFunctionAlias(alias, qname)) { errors.Add(FatalErrors.AliasAlreadyInUse, this.sourceUnit, this.yypos/*TODO: position of the alias itself*/, qname.NamespacePhpName, alias); } } private void AddConstAlias(QualifiedName qname, string alias) { alias = alias ?? qname.Name.Value; if (!this.CurrentNaming.AddConstantAlias(alias, qname)) { errors.Add(FatalErrors.AliasAlreadyInUse, this.sourceUnit, this.yypos/*TODO: position of the alias itself*/, qname.NamespacePhpName, alias); } } private void ReserveTypeNames(List<FormalTypeParam> typeParams) { if (typeParams == null) return; foreach (var param in typeParams) reservedTypeNames.Add(param.Name.Value); } private void UnreserveTypeNames(List<FormalTypeParam> typeParams) { if (typeParams == null) return; foreach (var param in typeParams) reservedTypeNames.Remove(param.Name.Value); } /// <summary> /// Transforms each item of <paramref name="qnameList"/> using <see cref="TranslateAny(QualifiedName)"/> function. /// </summary> /// <param name="qnameList">List of qualified names.</param> /// <returns>Reference to <paramref name="qnameList"/>.</returns> private List<QualifiedName> TranslateAny(List<QualifiedName> qnameList) { for (int i = 0; i < qnameList.Count; i++) qnameList[i] = TranslateAny(qnameList[i]); return qnameList; } /// <summary> /// Translate the name using defined aliases. Any first part of the <see cref="QualifiedName"/> will be translated. /// </summary> /// <param name="qname">The name to translate.</param> /// <returns>Translated qualified name.</returns> /// <remarks>Fully qualified names are not translated.</remarks> private QualifiedName TranslateAny(QualifiedName qname) { if (qname.IsFullyQualifiedName) return qname; // skip special names: if (qname.IsSimpleName) { if (reservedTypeNames.Contains(qname.Name.Value)) return qname; } // return the alias if found: return TranslateAlias(qname); } /// <summary> /// Translate the name using defined aliases. Only namespace part of the <see cref="QualifiedName"/> will be translated. The <see cref="QualifiedName.Name"/> part will not. /// </summary> /// <param name="qname">The name to translate.</param> /// <returns>Translated qualified name.</returns> /// <remarks>Fully qualified names are not translated.</remarks> private QualifiedName TranslateNamespace(QualifiedName qname) { if (qname.IsFullyQualifiedName) { return qname; } if (qname.IsSimpleName) { // no namespace part, return not fully qualified simple name (function or constant), has to be handled during analysis: return qname; } else { return TranslateAlias(qname); } } /// <summary> /// Translate first part of given <paramref name="qname"/> into aliased <see cref="QualifiedName"/>. /// If no such alias is found, return original <paramref name="qname"/>. /// </summary> /// <param name="qname">Name which first part has tobe translated.</param> /// <returns>Translated <see cref="QualifiedName"/>.</returns> /// <remarks>Always returns fully qualified name.</remarks> private QualifiedName TranslateAlias(QualifiedName qname) { Debug.Assert(!qname.IsFullyQualifiedName); return QualifiedName.TranslateAlias( qname, this.CurrentNaming.Aliases, (IsInGlobalNamespace || sourceUnit.HasImportedNamespaces) ? (QualifiedName?)null : currentNamespace.QualifiedName); // do not use current namespace, if there are imported namespace ... will be resolved later } #endregion #region Helpers private static readonly List<Tuple<GenericQualifiedName, Text.Span>> emptyGenericQualifiedNamePositionList = new List<Tuple<GenericQualifiedName, Text.Span>>(); private static readonly List<FormalParam> emptyFormalParamListIndex = new List<FormalParam>(); private static readonly List<ActualParam> emptyActualParamListIndex = new List<ActualParam>(); private static readonly List<Expression> emptyExpressionListIndex = new List<Expression>(); private static readonly List<Item> emptyItemListIndex = new List<Item>(); private static readonly List<NamedActualParam> emptyNamedActualParamListIndex = new List<NamedActualParam>(); private static readonly List<FormalTypeParam> emptyFormalTypeParamList = new List<FormalTypeParam>(); private static List<T>/*!*/ListAdd<T>(object list, object item) { Debug.Assert(list is List<T>); //Debug.Assert(item is T); var tlist = (List<T>)list; if (item is T) { tlist.Add((T)item); } else if (item != null) { Debug.Assert(item is List<T>); tlist.AddRange((List<T>)item); } return tlist; } private static object/*!*/StatementListAdd(object/*!*/listObj, object itemObj) { Debug.Assert(listObj is List<Statement>); if (!object.ReferenceEquals(itemObj, null)) { Debug.Assert(itemObj is Statement); var list = (List<Statement>)listObj; var stmt = (Statement)itemObj; NamespaceDecl nsitem; // little hack when appending statement after simple syntaxed namespace: // namespace A; // foo(); // <-- add this statement into namespace A if (list.Count != 0 && (nsitem = list.Last() as NamespaceDecl) != null && nsitem.IsSimpleSyntax && !(stmt is NamespaceDecl)) { // adding a statement after simple namespace declaration => add the statement into the namespace: StatementListAdd(nsitem.Statements, stmt); //nsitem.UpdatePosition(Text.Span.CombinePositions(nsitem.Span, ((Statement)item).Span)); } else { list.Add(stmt); } } // return listObj; } private List<Statement>/*!*/StmtList(Text.Span extentFrom, Text.Span extentTo, object/*!*/listObj) { return StmtList(CombinePositions(extentFrom, extentTo), listObj); } private List<Statement>/*!*/StmtList(Text.Span extent, object/*!*/listObj) { var list = (List<Statement>)listObj; _docList.Merge(extent, list); return list; } private T AnnotateDoc<T>(T declstmt) { _docList.Annotate((IDeclarationElement)declstmt); return declstmt; } private Text.Span Combine(Text.Span first, Text.Span second) { return Text.Span.Combine(first, second); } private Text.Span Combine(Text.Span start, Text.Span optEnd1, Text.Span optEnd2, Text.Span end) { if (optEnd1.IsValid) end = optEnd1; else if (optEnd2.IsValid) end = optEnd2; return Combine(start, end); } private static List<T>/*!*/NewList<T>(T item) { return new List<T>(1){ item }; } private static List<T>/*!*/NewList<T>(object item) { return NewList<T>((T)item); } private static int GetHeadingEnd(Text.Span lastNonBodySymbolPosition) { return lastNonBodySymbolPosition.End; } private static int GetBodyStart(Text.Span bodyPosition) { return bodyPosition.Start; } /// <summary> /// Handles token that is not valid PHP class/namespace name token in PHP, /// but can be used from referenced C# library. /// </summary> /// <param name="span">Token position.</param> /// <param name="token">Token text.</param> /// <returns>Text of the token.</returns> private string CSharpNameToken(Text.Span span, string token) { // TODO: move to scanner // get token string: //string token = this.scanner.GetTokenString(position); if (token == null) throw new ArgumentNullException("token"); // report syntax error if C# names are not allowed if ((this.features & LanguageFeatures.CSharpTypeNames) == 0) { this.ErrorSink.Add(FatalErrors.SyntaxError, this.SourceUnit, span, CoreResources.GetString("unexpected_token", token)); } // return token; } /// <summary> /// Gets formal parameter flags. /// </summary> /// <param name="byref">Whether the parameter is prefixed with <c>&amp;</c> character.</param> /// <param name="variadic">Whether the parameter is prefixed with <c>...</c>.</param> /// <returns>Parameter flags.</returns> private static FormalParam.Flags FormalParamFlags(bool byref, bool variadic) { FormalParam.Flags flags = FormalParam.Flags.Default; if (byref) flags |= FormalParam.Flags.IsByRef; if (variadic) flags |= FormalParam.Flags.IsVariadic; return flags; } #endregion #region Handling PHPDoc: ICommentsSink, IScannerHandler Members private ICommentsSink/*!*/_commentSink; private IScannerHandler/*!*/_scannerHandler; private DocCommentList/*!*/_docList; private void InitializeCommentSink() { _commentSink = ChainForwardCommentSink.ChainSinks(reductionsSink as ICommentsSink, sourceUnit as ICommentsSink); _scannerHandler = (sourceUnit as IScannerHandler) ?? new Scanner.NullScannerHandler(); _docList = new DocCommentList(); } private void ClearCommentSink() { _commentSink = null; _scannerHandler = null; _docList = null; } #region Nested class: ChainCommentsSink private abstract class ChainCommentsSink : ICommentsSink { readonly ICommentsSink/*!*/_next; protected ChainCommentsSink(ICommentsSink next) { _next = next ?? new Scanner.NullCommentsSink(); } #region ICommentsSink Members public virtual void OnLineComment(Scanner scanner, Text.TextSpan span) { _next.OnLineComment(scanner, span); } public virtual void OnComment(Scanner scanner, Text.TextSpan span) { _next.OnComment(scanner, span); } public virtual void OnPhpDocComment(Scanner scanner, PHPDocBlock phpDocBlock) { _next.OnPhpDocComment(scanner, phpDocBlock); } public virtual void OnOpenTag(Scanner scanner, Text.TextSpan span) { _next.OnOpenTag(scanner, span); } public virtual void OnCloseTag(Scanner scanner, Text.TextSpan span) { _next.OnCloseTag(scanner, span); } #endregion } private sealed class ChainForwardCommentSink : ChainCommentsSink { readonly ICommentsSink/*!*/_forward; private ChainForwardCommentSink(ICommentsSink/*!*/forward, ICommentsSink/*!*/next) : base(next) { _forward = forward; } public static ICommentsSink/*!*/ChainSinks(ICommentsSink first, ICommentsSink second) { if (first != null) { if (second != null) return new ChainForwardCommentSink(first, second); else return first; } // return second ?? new Scanner.NullCommentsSink(); } public override void OnLineComment(Scanner scanner, Text.TextSpan span) { _forward.OnLineComment(scanner, span); base.OnLineComment(scanner, span); } public override void OnComment(Scanner scanner, Text.TextSpan span) { _forward.OnComment(scanner, span); base.OnComment(scanner, span); } public override void OnPhpDocComment(Scanner scanner, PHPDocBlock phpDocBlock) { _forward.OnPhpDocComment(scanner, phpDocBlock); base.OnPhpDocComment(scanner, phpDocBlock); } public override void OnOpenTag(Scanner scanner, Text.TextSpan span) { _forward.OnOpenTag(scanner, span); base.OnOpenTag(scanner, span); } public override void OnCloseTag(Scanner scanner, Text.TextSpan span) { _forward.OnCloseTag(scanner, span); base.OnCloseTag(scanner, span); } } private sealed class HandleDocComment : IScannerHandler { readonly Parser _parser; readonly IScannerHandler _next; readonly PHPDocBlock _docComment; public HandleDocComment(Parser/*!*/parser, PHPDocBlock/*!*/phpDocBlock, IScannerHandler/*!*/next) { Debug.Assert(parser != null); Debug.Assert(phpDocBlock != null); Debug.Assert(next != null); _parser = parser; _docComment = phpDocBlock; _next = next; } #region IScannerHandler Members public void OnNextToken(Tokens token, char[] buffer, int tokenStart, int tokenLength) { if (token != Tokens.T_WHITESPACE) { // now we know all the whitespace after the DOC comment _parser._docList.AppendBlock(_docComment, _parser.Scanner.TokenPosition.Start); // remove this handler so it is not called on every IScannerHandler.OnNextToken Debug.Assert(_parser._scannerHandler == this); _parser._scannerHandler = _next; } _next.OnNextToken(token, buffer, tokenStart, tokenLength); } #endregion } #endregion void ICommentsSink.OnLineComment(Scanner scanner, Text.TextSpan span) { _commentSink.OnLineComment(scanner, span); } void ICommentsSink.OnComment(Scanner scanner, Text.TextSpan span) { _commentSink.OnComment(scanner, span); } void ICommentsSink.OnPhpDocComment(Scanner scanner, PHPDocBlock phpDocBlock) { // handle the next non-whitespace token so we'll know span of the DOC comment including the following whitespace _scannerHandler = new HandleDocComment(this, phpDocBlock, _scannerHandler); // _commentSink.OnPhpDocComment(scanner, phpDocBlock); } void ICommentsSink.OnOpenTag(Scanner scanner, Text.TextSpan span) { _commentSink.OnOpenTag(scanner, span); } void ICommentsSink.OnCloseTag(Scanner scanner, Text.TextSpan span) { _commentSink.OnCloseTag(scanner, span); } void IScannerHandler.OnNextToken(Tokens token, char[] buffer, int tokenStart, int tokenLength) { _scannerHandler.OnNextToken(token, buffer, tokenStart, tokenLength); } #endregion } }
/* * Keys.cs - Implementation of the * "System.Windows.Forms.Keys" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Windows.Forms { using System.Runtime.InteropServices; #if !ECMA_COMPAT && !CONFIG_COMPACT_FORMS [ComVisible(true)] //TODO [TypeConverter(typeof(KeysConverter))] #endif [Flags] public enum Keys { // No key specified. None = 0x00000000, // Letter keys. A = 0x00000041, B = 0x00000042, C = 0x00000043, D = 0x00000044, E = 0x00000045, F = 0x00000046, G = 0x00000047, H = 0x00000048, I = 0x00000049, J = 0x0000004A, K = 0x0000004B, L = 0x0000004C, M = 0x0000004D, N = 0x0000004E, O = 0x0000004F, P = 0x00000050, Q = 0x00000051, R = 0x00000052, S = 0x00000053, T = 0x00000054, U = 0x00000055, V = 0x00000056, W = 0x00000057, X = 0x00000058, Y = 0x00000059, Z = 0x0000005A, // Digit keys. D0 = 0x00000030, D1 = 0x00000031, D2 = 0x00000032, D3 = 0x00000033, D4 = 0x00000034, D5 = 0x00000035, D6 = 0x00000036, D7 = 0x00000037, D8 = 0x00000038, D9 = 0x00000039, // Number pad keys. NumPad0 = 0x00000060, NumPad1 = 0x00000061, NumPad2 = 0x00000062, NumPad3 = 0x00000063, NumPad4 = 0x00000064, NumPad5 = 0x00000065, NumPad6 = 0x00000066, NumPad7 = 0x00000067, NumPad8 = 0x00000068, NumPad9 = 0x00000069, // Function keys. F1 = 0x00000070, F2 = 0x00000071, F3 = 0x00000072, F4 = 0x00000073, F5 = 0x00000074, F6 = 0x00000075, F7 = 0x00000076, F8 = 0x00000077, F9 = 0x00000078, F10 = 0x00000079, F11 = 0x0000007A, F12 = 0x0000007B, F13 = 0x0000007C, F14 = 0x0000007D, F15 = 0x0000007E, F16 = 0x0000007F, F17 = 0x00000080, F18 = 0x00000081, F19 = 0x00000082, F20 = 0x00000083, F21 = 0x00000084, F22 = 0x00000085, F23 = 0x00000086, F24 = 0x00000087, // Buttons. LButton = 0x00000001, RButton = 0x00000002, MButton = 0x00000004, XButton1 = 0x00000005, XButton2 = 0x00000006, // Special keys. Cancel = 0x00000003, Back = 0x00000008, Tab = 0x00000009, LineFeed = 0x0000000A, Enter = 0x0000000D, Return = Enter, ShiftKey = 0x00000010, ControlKey = 0x00000011, Menu = 0x00000012, Clear = 0x00000012, Pause = 0x00000013, Capital = 0x00000014, CapsLock = Capital, Escape = 0x0000001B, Space = 0x00000020, Prior = 0x00000021, PageUp = Prior, Next = 0x00000022, PageDown = Next, End = 0x00000023, Home = 0x00000024, Left = 0x00000025, Up = 0x00000026, Right = 0x00000027, Down = 0x00000028, Select = 0x00000029, Print = 0x0000002A, Execute = 0x0000002B, PrintScreen = 0x0000002C, Snapshot = PrintScreen, Insert = 0x0000002D, Delete = 0x0000002E, Help = 0x0000002F, LWin = 0x0000005B, RWin = 0x0000005C, Apps = 0x0000005D, Multiply = 0x0000006A, Add = 0x0000006B, Separator = 0x0000006C, Subtract = 0x0000006D, Decimal = 0x0000006E, Divide = 0x0000006F, NumLock = 0x00000090, Scroll = 0x00000091, LShiftKey = 0x000000A0, RShiftKey = 0x000000A1, LControlKey = 0x000000A2, RControlKey = 0x000000A3, LMenu = 0x000000A4, RMenu = 0x000000A5, ProcessKey = 0x000000E5, Attn = 0x000000F6, Crsel = 0x000000F7, Exsel = 0x000000F8, EraseEof = 0x000000F9, Play = 0x000000FA, Zoom = 0x000000FB, NoName = 0x000000FC, Pa1 = 0x000000FD, OemClear = 0x000000FE, // Modifier keys. Shift = 0x00010000, Control = 0x00020000, Alt = 0x00040000, // Masks. KeyCode = 0x0000FFFF, Modifiers = unchecked((int)0xFFFF0000), #if !CONFIG_COMPACT_FORMS // Other keys. HangulMode = 0x00000015, HanguelMode = HangulMode, KanaMode = HangulMode, JunjaMode = 0x00000017, FinalMode = 0x00000018, HanjaMode = 0x00000019, KanjiMode = HanjaMode, IMEConvert = 0x0000001C, IMENonconvert = 0x0000001D, IMEAceept = 0x0000001E, IMEModeChange = 0x0000001F, BrowserBack = 0x000000A6, BrowserForward = 0x000000A7, BrowserRefresh = 0x000000A8, BrowserStop = 0x000000A9, BrowserSearch = 0x000000AA, BrowserFavorites = 0x000000AB, BrowserHome = 0x000000AC, VolumeMute = 0x000000AD, VolumeDown = 0x000000AE, VolumeUp = 0x000000AF, MediaNextTrack = 0x000000B0, MediaPreviousTrack = 0x000000B1, MediaStop = 0x000000B2, MediaPlayPause = 0x000000B3, LaunchMail = 0x000000B4, SelectMedia = 0x000000B5, LaunchApplication1 = 0x000000B6, LaunchApplication2 = 0x000000B7, OemSemicolon = 0x000000BA, Oemplus = 0x000000BB, Oemcomma = 0x000000BC, OemMinus = 0x000000BD, OemPeriod = 0x000000BE, OemQuestion = 0x000000BF, OemTilde = 0x000000C0, OemOpenBrackets = 0x000000DB, OemPipe = 0x000000DC, OemCloseBrackets = 0x000000DD, OemQuotes = 0x000000DE, Oem8 = 0x000000DF, OemBackslash = 0x000000E2, #endif // !CONFIG_COMPACT_FORMS }; // enum Keys }; // namespace System.Windows.Forms
// 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.27.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Google Cloud Natural Language API Version v1beta2 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://cloud.google.com/natural-language/'>Google Cloud Natural Language API</a> * <tr><th>API Version<td>v1beta2 * <tr><th>API Rev<td>20170619 (900) * <tr><th>API Docs * <td><a href='https://cloud.google.com/natural-language/'> * https://cloud.google.com/natural-language/</a> * <tr><th>Discovery Name<td>language * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Google Cloud Natural Language API can be found at * <a href='https://cloud.google.com/natural-language/'>https://cloud.google.com/natural-language/</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.CloudNaturalLanguage.v1beta2 { /// <summary>The CloudNaturalLanguage Service.</summary> public class CloudNaturalLanguageService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1beta2"; /// <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 CloudNaturalLanguageService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudNaturalLanguageService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { documents = new DocumentsResource(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 "language"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://language.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://language.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif /// <summary>Available OAuth 2.0 scopes for use with the Google Cloud Natural Language API.</summary> public class Scope { /// <summary>View and manage your data across Google Cloud Platform services</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } private readonly DocumentsResource documents; /// <summary>Gets the Documents resource.</summary> public virtual DocumentsResource Documents { get { return documents; } } } ///<summary>A base abstract class for CloudNaturalLanguage requests.</summary> public abstract class CloudNaturalLanguageBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new CloudNaturalLanguageBaseServiceRequest instance.</summary> protected CloudNaturalLanguageBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>OAuth bearer token.</summary> [Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string BearerToken { get; set; } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Pretty-print response.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Pp { 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.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudNaturalLanguage parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "bearer_token", new Google.Apis.Discovery.Parameter { Name = "bearer_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pp", new Google.Apis.Discovery.Parameter { Name = "pp", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "documents" collection of methods.</summary> public class DocumentsResource { private const string Resource = "documents"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public DocumentsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Finds named entities (currently proper names and common nouns) in the text along with entity types, /// salience, mentions for each entity, and other properties.</summary> /// <param name="body">The body of the request.</param> public virtual AnalyzeEntitiesRequest AnalyzeEntities(Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeEntitiesRequest body) { return new AnalyzeEntitiesRequest(service, body); } /// <summary>Finds named entities (currently proper names and common nouns) in the text along with entity types, /// salience, mentions for each entity, and other properties.</summary> public class AnalyzeEntitiesRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeEntitiesResponse> { /// <summary>Constructs a new AnalyzeEntities request.</summary> public AnalyzeEntitiesRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeEntitiesRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeEntitiesRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "analyzeEntities"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1beta2/documents:analyzeEntities"; } } /// <summary>Initializes AnalyzeEntities parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with each /// entity and its mentions.</summary> /// <param name="body">The body of the request.</param> public virtual AnalyzeEntitySentimentRequest AnalyzeEntitySentiment(Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeEntitySentimentRequest body) { return new AnalyzeEntitySentimentRequest(service, body); } /// <summary>Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with each /// entity and its mentions.</summary> public class AnalyzeEntitySentimentRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeEntitySentimentResponse> { /// <summary>Constructs a new AnalyzeEntitySentiment request.</summary> public AnalyzeEntitySentimentRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeEntitySentimentRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeEntitySentimentRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "analyzeEntitySentiment"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1beta2/documents:analyzeEntitySentiment"; } } /// <summary>Initializes AnalyzeEntitySentiment parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Analyzes the sentiment of the provided text.</summary> /// <param name="body">The body of the request.</param> public virtual AnalyzeSentimentRequest AnalyzeSentiment(Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeSentimentRequest body) { return new AnalyzeSentimentRequest(service, body); } /// <summary>Analyzes the sentiment of the provided text.</summary> public class AnalyzeSentimentRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeSentimentResponse> { /// <summary>Constructs a new AnalyzeSentiment request.</summary> public AnalyzeSentimentRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeSentimentRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeSentimentRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "analyzeSentiment"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1beta2/documents:analyzeSentiment"; } } /// <summary>Initializes AnalyzeSentiment parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part /// of speech tags, dependency trees, and other properties.</summary> /// <param name="body">The body of the request.</param> public virtual AnalyzeSyntaxRequest AnalyzeSyntax(Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeSyntaxRequest body) { return new AnalyzeSyntaxRequest(service, body); } /// <summary>Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part /// of speech tags, dependency trees, and other properties.</summary> public class AnalyzeSyntaxRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeSyntaxResponse> { /// <summary>Constructs a new AnalyzeSyntax request.</summary> public AnalyzeSyntaxRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeSyntaxRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnalyzeSyntaxRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "analyzeSyntax"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1beta2/documents:analyzeSyntax"; } } /// <summary>Initializes AnalyzeSyntax parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>A convenience method that provides all syntax, sentiment, entity, and classification features in /// one call.</summary> /// <param name="body">The body of the request.</param> public virtual AnnotateTextRequest AnnotateText(Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnnotateTextRequest body) { return new AnnotateTextRequest(service, body); } /// <summary>A convenience method that provides all syntax, sentiment, entity, and classification features in /// one call.</summary> public class AnnotateTextRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnnotateTextResponse> { /// <summary>Constructs a new AnnotateText request.</summary> public AnnotateTextRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnnotateTextRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1beta2.Data.AnnotateTextRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "annotateText"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1beta2/documents:annotateText"; } } /// <summary>Initializes AnnotateText parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.CloudNaturalLanguage.v1beta2.Data { /// <summary>The entity analysis request message.</summary> public class AnalyzeEntitiesRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The encoding type used by the API to calculate offsets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encodingType")] public virtual string EncodingType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The entity analysis response message.</summary> public class AnalyzeEntitiesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The recognized entities in the input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("entities")] public virtual System.Collections.Generic.IList<Entity> Entities { get; set; } /// <summary>The language of the text, which will be the same as the language specified in the request or, if /// not specified, the automatically-detected language. See Document.language field for more details.</summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The entity-level sentiment analysis request message.</summary> public class AnalyzeEntitySentimentRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The encoding type used by the API to calculate offsets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encodingType")] public virtual string EncodingType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The entity-level sentiment analysis response message.</summary> public class AnalyzeEntitySentimentResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The recognized entities in the input document with associated sentiments.</summary> [Newtonsoft.Json.JsonPropertyAttribute("entities")] public virtual System.Collections.Generic.IList<Entity> Entities { get; set; } /// <summary>The language of the text, which will be the same as the language specified in the request or, if /// not specified, the automatically-detected language. See Document.language field for more details.</summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The sentiment analysis request message.</summary> public class AnalyzeSentimentRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The encoding type used by the API to calculate sentence offsets for the sentence /// sentiment.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encodingType")] public virtual string EncodingType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The sentiment analysis response message.</summary> public class AnalyzeSentimentResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The overall sentiment of the input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("documentSentiment")] public virtual Sentiment DocumentSentiment { get; set; } /// <summary>The language of the text, which will be the same as the language specified in the request or, if /// not specified, the automatically-detected language. See Document.language field for more details.</summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary>The sentiment for all the sentences in the document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sentences")] public virtual System.Collections.Generic.IList<Sentence> Sentences { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The syntax analysis request message.</summary> public class AnalyzeSyntaxRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The encoding type used by the API to calculate offsets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encodingType")] public virtual string EncodingType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The syntax analysis response message.</summary> public class AnalyzeSyntaxResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The language of the text, which will be the same as the language specified in the request or, if /// not specified, the automatically-detected language. See Document.language field for more details.</summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary>Sentences in the input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sentences")] public virtual System.Collections.Generic.IList<Sentence> Sentences { get; set; } /// <summary>Tokens, along with their syntactic information, in the input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tokens")] public virtual System.Collections.Generic.IList<Token> Tokens { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The request message for the text annotation API, which can perform multiple analysis types (sentiment, /// entities, and syntax) in one call.</summary> public class AnnotateTextRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The encoding type used by the API to calculate offsets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encodingType")] public virtual string EncodingType { get; set; } /// <summary>The enabled features.</summary> [Newtonsoft.Json.JsonPropertyAttribute("features")] public virtual Features Features { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The text annotations response message.</summary> public class AnnotateTextResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The overall sentiment for the document. Populated if the user enables /// AnnotateTextRequest.Features.extract_document_sentiment.</summary> [Newtonsoft.Json.JsonPropertyAttribute("documentSentiment")] public virtual Sentiment DocumentSentiment { get; set; } /// <summary>Entities, along with their semantic information, in the input document. Populated if the user /// enables AnnotateTextRequest.Features.extract_entities.</summary> [Newtonsoft.Json.JsonPropertyAttribute("entities")] public virtual System.Collections.Generic.IList<Entity> Entities { get; set; } /// <summary>The language of the text, which will be the same as the language specified in the request or, if /// not specified, the automatically-detected language. See Document.language field for more details.</summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary>Sentences in the input document. Populated if the user enables /// AnnotateTextRequest.Features.extract_syntax.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sentences")] public virtual System.Collections.Generic.IList<Sentence> Sentences { get; set; } /// <summary>Tokens, along with their syntactic information, in the input document. Populated if the user /// enables AnnotateTextRequest.Features.extract_syntax.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tokens")] public virtual System.Collections.Generic.IList<Token> Tokens { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents dependency parse tree information for a token.</summary> public class DependencyEdge : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Represents the head of this token in the dependency tree. This is the index of the token which has /// an arc going to this token. The index is the position of the token in the array of tokens returned by the /// API method. If this token is a root token, then the `head_token_index` is its own index.</summary> [Newtonsoft.Json.JsonPropertyAttribute("headTokenIndex")] public virtual System.Nullable<int> HeadTokenIndex { get; set; } /// <summary>The parse label for the token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("label")] public virtual string Label { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>################################################################ # /// /// Represents the input to API methods.</summary> public class Document : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The content of the input in string format.</summary> [Newtonsoft.Json.JsonPropertyAttribute("content")] public virtual string Content { get; set; } /// <summary>The Google Cloud Storage URI where the file content is located. This URI must be of the form: /// gs://bucket_name/object_name. For more details, see https://cloud.google.com/storage/docs/reference-uris. /// NOTE: Cloud Storage object versioning is not supported.</summary> [Newtonsoft.Json.JsonPropertyAttribute("gcsContentUri")] public virtual string GcsContentUri { get; set; } /// <summary>The language of the document (if not specified, the language is automatically detected). Both ISO /// and BCP-47 language codes are accepted. [Language Support](/natural-language/docs/languages) lists currently /// supported languages for each API method. If the language (either specified by the caller or automatically /// detected) is not supported by the called API method, an `INVALID_ARGUMENT` error is returned.</summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary>Required. If the type is not set or is `TYPE_UNSPECIFIED`, returns an `INVALID_ARGUMENT` /// error.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents a phrase in the text that is a known entity, such as a person, an organization, or location. /// The API associates information, such as salience and mentions, with entities.</summary> public class Entity : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The mentions of this entity in the input document. The API currently supports proper noun /// mentions.</summary> [Newtonsoft.Json.JsonPropertyAttribute("mentions")] public virtual System.Collections.Generic.IList<EntityMention> Mentions { get; set; } /// <summary>Metadata associated with the entity. /// /// Currently, Wikipedia URLs and Knowledge Graph MIDs are provided, if available. The associated keys are /// "wikipedia_url" and "mid", respectively.</summary> [Newtonsoft.Json.JsonPropertyAttribute("metadata")] public virtual System.Collections.Generic.IDictionary<string,string> Metadata { get; set; } /// <summary>The representative name for the entity.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The salience score associated with the entity in the [0, 1.0] range. /// /// The salience score for an entity provides information about the importance or centrality of that entity to /// the entire document text. Scores closer to 0 are less salient, while scores closer to 1.0 are highly /// salient.</summary> [Newtonsoft.Json.JsonPropertyAttribute("salience")] public virtual System.Nullable<float> Salience { get; set; } /// <summary>For calls to AnalyzeEntitySentiment or if AnnotateTextRequest.Features.extract_entity_sentiment is /// set to true, this field will contain the aggregate sentiment expressed for this entity in the provided /// document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sentiment")] public virtual Sentiment Sentiment { get; set; } /// <summary>The entity type.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents a mention for an entity in the text. Currently, proper noun mentions are /// supported.</summary> public class EntityMention : Google.Apis.Requests.IDirectResponseSchema { /// <summary>For calls to AnalyzeEntitySentiment or if AnnotateTextRequest.Features.extract_entity_sentiment is /// set to true, this field will contain the sentiment expressed for this mention of the entity in the provided /// document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sentiment")] public virtual Sentiment Sentiment { get; set; } /// <summary>The mention text.</summary> [Newtonsoft.Json.JsonPropertyAttribute("text")] public virtual TextSpan Text { get; set; } /// <summary>The type of the entity mention.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>All available features for sentiment, syntax, and semantic analysis. Setting each one to true will /// enable that specific analysis for the input.</summary> public class Features : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Extract document-level sentiment.</summary> [Newtonsoft.Json.JsonPropertyAttribute("extractDocumentSentiment")] public virtual System.Nullable<bool> ExtractDocumentSentiment { get; set; } /// <summary>Extract entities.</summary> [Newtonsoft.Json.JsonPropertyAttribute("extractEntities")] public virtual System.Nullable<bool> ExtractEntities { get; set; } /// <summary>Extract entities and their associated sentiment.</summary> [Newtonsoft.Json.JsonPropertyAttribute("extractEntitySentiment")] public virtual System.Nullable<bool> ExtractEntitySentiment { get; set; } /// <summary>Extract syntax information.</summary> [Newtonsoft.Json.JsonPropertyAttribute("extractSyntax")] public virtual System.Nullable<bool> ExtractSyntax { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents part of speech information for a token.</summary> public class PartOfSpeech : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The grammatical aspect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("aspect")] public virtual string Aspect { get; set; } /// <summary>The grammatical case.</summary> [Newtonsoft.Json.JsonPropertyAttribute("case")] public virtual string Case__ { get; set; } /// <summary>The grammatical form.</summary> [Newtonsoft.Json.JsonPropertyAttribute("form")] public virtual string Form { get; set; } /// <summary>The grammatical gender.</summary> [Newtonsoft.Json.JsonPropertyAttribute("gender")] public virtual string Gender { get; set; } /// <summary>The grammatical mood.</summary> [Newtonsoft.Json.JsonPropertyAttribute("mood")] public virtual string Mood { get; set; } /// <summary>The grammatical number.</summary> [Newtonsoft.Json.JsonPropertyAttribute("number")] public virtual string Number { get; set; } /// <summary>The grammatical person.</summary> [Newtonsoft.Json.JsonPropertyAttribute("person")] public virtual string Person { get; set; } /// <summary>The grammatical properness.</summary> [Newtonsoft.Json.JsonPropertyAttribute("proper")] public virtual string Proper { get; set; } /// <summary>The grammatical reciprocity.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reciprocity")] public virtual string Reciprocity { get; set; } /// <summary>The part of speech tag.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tag")] public virtual string Tag { get; set; } /// <summary>The grammatical tense.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tense")] public virtual string Tense { get; set; } /// <summary>The grammatical voice.</summary> [Newtonsoft.Json.JsonPropertyAttribute("voice")] public virtual string Voice { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents a sentence in the input document.</summary> public class Sentence : Google.Apis.Requests.IDirectResponseSchema { /// <summary>For calls to AnalyzeSentiment or if AnnotateTextRequest.Features.extract_document_sentiment is set /// to true, this field will contain the sentiment for the sentence.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sentiment")] public virtual Sentiment Sentiment { get; set; } /// <summary>The sentence text.</summary> [Newtonsoft.Json.JsonPropertyAttribute("text")] public virtual TextSpan Text { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents the feeling associated with the entire text or entities in the text.</summary> public class Sentiment : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A non-negative number in the [0, +inf) range, which represents the absolute magnitude of sentiment /// regardless of score (positive or negative).</summary> [Newtonsoft.Json.JsonPropertyAttribute("magnitude")] public virtual System.Nullable<float> Magnitude { get; set; } /// <summary>Sentiment score between -1.0 (negative sentiment) and 1.0 (positive sentiment).</summary> [Newtonsoft.Json.JsonPropertyAttribute("score")] public virtual System.Nullable<float> Score { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The `Status` type defines a logical error model that is suitable for different programming /// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model /// is designed to be: /// /// - Simple to use and understand for most users - Flexible enough to meet unexpected needs /// /// # Overview /// /// The `Status` message contains three pieces of data: error code, error message, and error details. The error code /// should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error /// message should be a developer-facing English message that helps developers *understand* and *resolve* the error. /// If a localized user-facing error message is needed, put the localized message in the error details or localize /// it in the client. The optional error details may contain arbitrary information about the error. There is a /// predefined set of error detail types in the package `google.rpc` that can be used for common error conditions. /// /// # Language mapping /// /// The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire /// format. When the `Status` message is exposed in different client libraries and different wire protocols, it can /// be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped /// to some error codes in C. /// /// # Other uses /// /// The error model and the `Status` message can be used in a variety of environments, either with or without APIs, /// to provide a consistent developer experience across different environments. /// /// Example uses of this error model include: /// /// - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the /// normal response to indicate the partial errors. /// /// - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error /// reporting. /// /// - Batch operations. If a client uses batch request and batch response, the `Status` message should be used /// directly inside batch response, one for each error sub-response. /// /// - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of /// those operations should be represented directly using the `Status` message. /// /// - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any /// stripping needed for security/privacy reasons.</summary> public class Status : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The status code, which should be an enum value of google.rpc.Code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("code")] public virtual System.Nullable<int> Code { get; set; } /// <summary>A list of messages that carry the error details. There will be a common set of message types for /// APIs to use.</summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; } /// <summary>A developer-facing error message, which should be in English. Any user-facing error message should /// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary> [Newtonsoft.Json.JsonPropertyAttribute("message")] public virtual string Message { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents an output piece of text.</summary> public class TextSpan : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The API calculates the beginning offset of the content in the original document according to the /// EncodingType specified in the API request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("beginOffset")] public virtual System.Nullable<int> BeginOffset { get; set; } /// <summary>The content of the output text.</summary> [Newtonsoft.Json.JsonPropertyAttribute("content")] public virtual string Content { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents the smallest syntactic building block of the text.</summary> public class Token : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Dependency tree parse for this token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dependencyEdge")] public virtual DependencyEdge DependencyEdge { get; set; } /// <summary>[Lemma](https://en.wikipedia.org/wiki/Lemma_%28morphology%29) of the token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lemma")] public virtual string Lemma { get; set; } /// <summary>Parts of speech tag for this token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("partOfSpeech")] public virtual PartOfSpeech PartOfSpeech { get; set; } /// <summary>The token text.</summary> [Newtonsoft.Json.JsonPropertyAttribute("text")] public virtual TextSpan Text { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Reflection; using Glass.Mapper.Pipelines.DataMapperResolver; using NUnit.Framework; using Glass.Mapper.Configuration; using Glass.Mapper.Diagnostics; using Glass.Mapper.IoC; using Glass.Mapper.Pipelines.ObjectConstruction; using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CreateInterface; using NSubstitute; namespace Glass.Mapper.Tests { [TestFixture] public class ContextFixture { [TearDown] public void TearDown() { Context.Clear(); } [SetUp] public void Setup() { } #region Create [Test] public void Create_CreateContext_CanGetContextFromContextDictionary() { //Assign string contextName = "testContext"; bool isDefault = false; Context.Clear(); //Act Context.Create(Substitute.For<IDependencyResolver>(), contextName, isDefault); //Assert Assert.IsTrue(Context.Contexts.ContainsKey(contextName)); Assert.IsNotNull(Context.Contexts[contextName]); Assert.IsNull(Context.Default); } [Test] public void Create_LoadContextAsDefault_CanGetContextFromContextDictionary() { //Assign string contextName = "testContext"; bool isDefault = true; //Act Context.Create(Substitute.For<IDependencyResolver>(), contextName, isDefault); //Assert Assert.IsTrue(Context.Contexts.ContainsKey(contextName)); Assert.IsNotNull(Context.Contexts[contextName]); Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[contextName], Context.Default); } [Test] public void Create_LoadContextAsDefault_CanGetContextFromContextDictionaryUsingDefault() { //Assign //Act Context.Create(Substitute.For<IDependencyResolver>()); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); } #endregion #region Load [Test] public void Load_LoadContextWithTypeConfigs_CanGetTypeConfigsFromContext() { //Assign var loader1 = Substitute.For<IConfigurationLoader>(); var config1 = Substitute.For<AbstractTypeConfiguration>(); config1.Type = typeof (StubClass1); loader1.Load().Returns(new[]{config1}); var loader2 = Substitute.For<IConfigurationLoader>(); var config2 = Substitute.For<AbstractTypeConfiguration>(); config2.Type = typeof(StubClass2); loader2.Load().Returns(new[] { config2 }); //Act var context = Context.Create(Substitute.For<IDependencyResolver>()); context.Config = new Config(); context.Load(loader1, loader2); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); Assert.AreEqual(config1, Context.Default.TypeConfigurations[config1.Type]); Assert.AreEqual(config2, Context.Default.TypeConfigurations[config2.Type]); } /// <summary> /// From issue https://github.com/mikeedwards83/Glass.Mapper/issues/85 /// </summary> [Test] public void Load_LoadContextWithGenericType_CanGetTypeConfigsFromContext() { //Assign var loader1 = Substitute.For<IConfigurationLoader>(); var config1 = Substitute.For<AbstractTypeConfiguration>(); config1.Type = typeof(Sample); loader1.Load().Returns(new[] { config1 }); //Act var context = Context.Create(Substitute.For<IDependencyResolver>()); context.Config = new Config(); context.Load(loader1); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); Assert.AreEqual(config1, Context.Default.TypeConfigurations[config1.Type]); } /// <summary> /// From issue https://github.com/mikeedwards83/Glass.Mapper/issues/85 /// </summary> [Test] public void Load_LoadContextGenericType_GenericTypeNotCreated() { //Assign var loader1 = Substitute.For<IConfigurationLoader>(); var config1 = new StubAbstractTypeConfiguration(); config1.Type = typeof(Generic<>); config1.AutoMap = true; loader1.Load().Returns(new[] { config1 }); //Act var context = Context.Create(Substitute.For<IDependencyResolver>()); context.Config = new Config(); context.Load(loader1); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); Assert.IsFalse(Context.Default.TypeConfigurations.ContainsKey(config1.Type)); } /// <summary> /// From issue https://github.com/mikeedwards83/Glass.Mapper/issues/85 /// </summary> [Test] public void Load_LoadContextDerivedFromGenericType_CanGetTypeConfigsFromContext() { //Assign var loader1 = Substitute.For<IConfigurationLoader>(); var config1 = new StubAbstractTypeConfiguration(); config1.Type = typeof(Sample); config1.AutoMap = true; loader1.Load().Returns(new[] { config1 }); var resolver = Substitute.For<IDependencyResolver>(); //Act var context = Context.Create(resolver); context.Config = new Config(); context.Load(loader1); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); Assert.IsTrue(Context.Default.TypeConfigurations.ContainsKey(config1.Type)); } #endregion #region Indexers [Test] public void Indexer_UseTypeIndexerWithValidConfig_ReturnsTypeConfiguration() { //Assign var loader1 = Substitute.For<IConfigurationLoader>(); var config1 = Substitute.For<AbstractTypeConfiguration>(); config1.Type = typeof(StubClass1); loader1.Load().Returns(new[] { config1 }); //Act var context = Context.Create(Substitute.For<IDependencyResolver>()); context.Config = new Config(); context.Load(loader1); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); Assert.AreEqual(config1, Context.Default[config1.Type]); } [Test] public void Indexer_UseTypeIndexerWithInvalidConfig_ReturnsNull() { //Assign var loader1 = Substitute.For<IConfigurationLoader>(); //Act var context = Context.Create(Substitute.For<IDependencyResolver>()); context.Config = new Config(); context.Load(loader1); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); Assert.IsNull( Context.Default[typeof(StubClass1)]); } #endregion #region GetTypeConfiguration [Test] public void GetTypeConfiguration_BaseTypeNullForInterface_AutoLoadsConfig() { //Arrange string contextName = "testContext"; bool isDefault = true; var type = typeof (IStubInterface1); Context.Create(Substitute.For<IDependencyResolver>(), contextName, isDefault); var context = Context.Contexts[contextName]; context.Config = new Config(); //Act var config = context.GetTypeConfigurationFromType<StubAbstractTypeConfiguration>(type); //Assert Assert.IsNotNull(config); } [Test] public void GetTypeConfiguration_TwoInterfacesWithTheSameNameUsingCastleProxy_ReturnsEachCorrectly() { //Arrange string contextName = "testContext"; bool isDefault = true; var type = typeof (NS1.ProxyTest1); var service = Substitute.For<IAbstractService>(); var task = new CreateInterfaceTask(new LazyLoadingHelper()); #region CreateTypes Context context = Context.Create(Substitute.For<IDependencyResolver>()); context.Config = new Config(); AbstractTypeCreationContext abstractTypeCreationContext1 = new TestTypeCreationContext(); abstractTypeCreationContext1.Options = new TestGetOptions() { Type = typeof(NS1.ProxyTest1) }; var configuration1 = Substitute.For<AbstractTypeConfiguration>(); configuration1.Type = typeof(NS1.ProxyTest1); ObjectConstructionArgs args1 = new ObjectConstructionArgs(context, abstractTypeCreationContext1, configuration1, service); AbstractTypeCreationContext abstractTypeCreationContext2 = new TestTypeCreationContext(); abstractTypeCreationContext2.Options = new TestGetOptions() { Type = typeof(NS2.ProxyTest1) }; var configuration2 = Substitute.For<AbstractTypeConfiguration>(); configuration2.Type = typeof(NS2.ProxyTest1); ObjectConstructionArgs args2 = new ObjectConstructionArgs(context, abstractTypeCreationContext2, configuration2, service); //Act task.Execute(args1); task.Execute(args2); #endregion context.GetTypeConfigurationFromType<StubAbstractTypeConfiguration>(typeof(NS1.ProxyTest1)); context.GetTypeConfigurationFromType<StubAbstractTypeConfiguration>(typeof(NS2.ProxyTest1)); //Act var config1 = context.GetTypeConfigurationFromType<StubAbstractTypeConfiguration>(args1.Result.GetType()); var config2 = context.GetTypeConfigurationFromType<StubAbstractTypeConfiguration>(args2.Result.GetType()); //Assert Assert.AreEqual(typeof(NS1.ProxyTest1), config1.Type); Assert.AreEqual(typeof(NS2.ProxyTest1), config2.Type); } #endregion #region Stubs public class StubAbstractDataMappingContext : AbstractDataMappingContext { public StubAbstractDataMappingContext(object obj, GetOptions options) : base(obj, options) { } } public class TestTypeCreationContext : AbstractTypeCreationContext { public override bool CacheEnabled { get; } public override AbstractDataMappingContext CreateDataMappingContext(object obj) { return new StubAbstractDataMappingContext(obj, Options); } } public interface IStubInterface1 { } public class StubClass1 { } public class StubClass2 { } #region ISSUE 85 public class ItemBase { public virtual Guid ItemId { get; set; } } public abstract class Generic<T> : ItemBase { public T Value { get; set; } public string Text { get; set; } } public class Sample : Generic<string> { public string Title { get; set; } } #endregion public class StubAbstractDataMapper : AbstractDataMapper { public Func<AbstractPropertyConfiguration, bool> CanHandleFunction { get; set; } public override bool CanHandle(AbstractPropertyConfiguration configuration, Context context) { return CanHandleFunction(configuration); } public override void MapToCms(AbstractDataMappingContext mappingContext) { throw new NotImplementedException(); } public override object MapToProperty(AbstractDataMappingContext mappingContext) { throw new NotImplementedException(); } public override void Setup(DataMapperResolverArgs args) { throw new NotImplementedException(); } } public class StubAbstractTypeConfiguration : AbstractTypeConfiguration { protected override AbstractPropertyConfiguration AutoMapProperty(PropertyInfo property) { var config = new StubAbstractPropertyConfiguration(); config.PropertyInfo = property; config.Mapper = new StubAbstractDataMapper(); return config; } } public class StubAbstractPropertyConfiguration : AbstractPropertyConfiguration { protected override AbstractPropertyConfiguration CreateCopy() { throw new NotImplementedException(); } } #endregion } namespace NS1 { public interface ProxyTest1 { } } namespace NS2 { public interface ProxyTest1 { } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages client side native call lifecycle. /// </summary> internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse> { Channel channel; // Completion of a pending unary response if not null. TaskCompletionSource<TResponse> unaryResponseTcs; // Set after status is received. Used for both unary and streaming response calls. ClientSideStatus? finishedStatus; bool readObserverCompleted; // True if readObserver has already been completed. public AsyncCall(Func<TRequest, byte[]> serializer, Func<byte[], TResponse> deserializer) : base(serializer, deserializer) { } public void Initialize(Channel channel, CompletionQueueSafeHandle cq, string methodName) { this.channel = channel; var call = CallSafeHandle.Create(channel.Handle, channel.CompletionRegistry, cq, methodName, channel.Target, Timespec.InfFuture); channel.Environment.DebugStats.ActiveClientCalls.Increment(); InitializeInternal(call); } // TODO: this method is not Async, so it shouldn't be in AsyncCall class, but // it is reusing fair amount of code in this class, so we are leaving it here. // TODO: for other calls, you need to call Initialize, this methods calls initialize // on its own, so there's a usage inconsistency. /// <summary> /// Blocking unary request - unary response call. /// </summary> public TResponse UnaryCall(Channel channel, string methodName, TRequest msg, Metadata headers) { using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.Create()) { byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); lock (myLock) { Initialize(channel, cq, methodName); started = true; halfcloseRequested = true; readingDone = true; } using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { using (var ctx = BatchContextSafeHandle.Create()) { call.StartUnary(payload, ctx, metadataArray); var ev = cq.Pluck(ctx.Handle); bool success = (ev.success != 0); try { HandleUnaryResponse(success, ctx); } catch (Exception e) { Console.WriteLine("Exception occured while invoking completion delegate: " + e); } } } try { // Once the blocking call returns, the result should be available synchronously. return unaryResponseTcs.Task.Result; } catch (AggregateException ae) { throw ExceptionHelper.UnwrapRpcException(ae); } } } /// <summary> /// Starts a unary request - unary response call. /// </summary> public Task<TResponse> UnaryCallAsync(TRequest msg, Metadata headers) { lock (myLock) { Preconditions.CheckNotNull(call); started = true; halfcloseRequested = true; readingDone = true; byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartUnary(payload, HandleUnaryResponse, metadataArray); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a streamed request - unary response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public Task<TResponse> ClientStreamingCallAsync(Metadata headers) { lock (myLock) { Preconditions.CheckNotNull(call); started = true; readingDone = true; unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartClientStreaming(HandleUnaryResponse, metadataArray); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a unary request - streamed response call. /// </summary> public void StartServerStreamingCall(TRequest msg, Metadata headers) { lock (myLock) { Preconditions.CheckNotNull(call); started = true; halfcloseRequested = true; halfclosed = true; // halfclose not confirmed yet, but it will be once finishedHandler is called. byte[] payload = UnsafeSerialize(msg); using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartServerStreaming(payload, HandleFinished, metadataArray); } } } /// <summary> /// Starts a streaming request - streaming response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public void StartDuplexStreamingCall(Metadata headers) { lock (myLock) { Preconditions.CheckNotNull(call); started = true; using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartDuplexStreaming(HandleFinished, metadataArray); } } } /// <summary> /// Sends a streaming request. Only one pending send action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartSendMessage(TRequest msg, AsyncCompletionDelegate<object> completionDelegate) { StartSendMessageInternal(msg, completionDelegate); } /// <summary> /// Receives a streaming response. Only one pending read action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartReadMessage(AsyncCompletionDelegate<TResponse> completionDelegate) { StartReadMessageInternal(completionDelegate); } /// <summary> /// Sends halfclose, indicating client is done with streaming requests. /// Only one pending send action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartSendCloseFromClient(AsyncCompletionDelegate<object> completionDelegate) { lock (myLock) { Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckSendingAllowed(); call.StartSendCloseFromClient(HandleHalfclosed); halfcloseRequested = true; sendCompletionDelegate = completionDelegate; } } /// <summary> /// Gets the resulting status if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Status GetStatus() { lock (myLock) { Preconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished."); return finishedStatus.Value.Status; } } /// <summary> /// Gets the trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Metadata GetTrailers() { lock (myLock) { Preconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished."); return finishedStatus.Value.Trailers; } } /// <summary> /// On client-side, we only fire readCompletionDelegate once all messages have been read /// and status has been received. /// </summary> protected override void ProcessLastRead(AsyncCompletionDelegate<TResponse> completionDelegate) { if (completionDelegate != null && readingDone && finishedStatus.HasValue) { bool shouldComplete; lock (myLock) { shouldComplete = !readObserverCompleted; readObserverCompleted = true; } if (shouldComplete) { var status = finishedStatus.Value.Status; if (status.StatusCode != StatusCode.OK) { FireCompletion(completionDelegate, default(TResponse), new RpcException(status)); } else { FireCompletion(completionDelegate, default(TResponse), null); } } } } protected override void OnReleaseResources() { channel.Environment.DebugStats.ActiveClientCalls.Decrement(); } /// <summary> /// Handler for unary response completion. /// </summary> private void HandleUnaryResponse(bool success, BatchContextSafeHandle ctx) { var fullStatus = ctx.GetReceivedStatusOnClient(); lock (myLock) { finished = true; finishedStatus = fullStatus; halfclosed = true; ReleaseResourcesIfPossible(); } if (!success) { unaryResponseTcs.SetException(new RpcException(new Status(StatusCode.Internal, "Internal error occured."))); return; } var status = fullStatus.Status; if (status.StatusCode != StatusCode.OK) { unaryResponseTcs.SetException(new RpcException(status)); return; } // TODO: handle deserialization error TResponse msg; TryDeserialize(ctx.GetReceivedMessage(), out msg); unaryResponseTcs.SetResult(msg); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleFinished(bool success, BatchContextSafeHandle ctx) { var fullStatus = ctx.GetReceivedStatusOnClient(); AsyncCompletionDelegate<TResponse> origReadCompletionDelegate = null; lock (myLock) { finished = true; finishedStatus = fullStatus; origReadCompletionDelegate = readCompletionDelegate; ReleaseResourcesIfPossible(); } ProcessLastRead(origReadCompletionDelegate); } } }
using System; using UnityEditor; using UnityEngine; using System.IO; using UnityEngine.Networking; namespace Polyglot { [CustomEditor(typeof(Localization))] public class LocalizationInspector : Editor { private const string PathPrefs = "polyglotpath"; private const string DefaultPolyglotPath = "Assets/Polyglot/Localization/PolyglotGameDev - Master.txt"; private const string CustomPathPrefs = "polyglotcustompath"; private const string CustomDocsIdPrefs = "polyglotcustomdocsid"; private const string CustomSheetIdPrefs = "polyglotcustomsheetid"; //https://docs.google.com/spreadsheets/d/17f0dQawb-s_Fd7DHgmVvJoEGDMH_yoSd8EYigrb0zmM/edit?usp=sharing private const string OfficialSheet = "17f0dQawb-s_Fd7DHgmVvJoEGDMH_yoSd8EYigrb0zmM"; private const string OfficialGId = "296134756"; private const string MenuItemPath = "Window/Polyglot Localization/"; private const string LocalizationAssetName = "Localization"; private const string LocalizationAssetPath = "Assets/Polyglot/Resources/"+LocalizationAssetName+".asset"; private static LocalizationAsset masterSheet; private static LocalizationAsset customSheet; [SerializeField] private string myField; public string MyField { get { return myField; } set { myField = value; } } [MenuItem(MenuItemPath + "Configurate", false, 0)] public static void Configurate() { var asset = Resources.Load<Localization>(LocalizationAssetName); if (asset == null) { asset = CreateInstance<Localization>(); var assetPathAndName = AssetDatabase.GenerateUniqueAssetPath (LocalizationAssetPath); AssetDatabase.CreateAsset(asset, assetPathAndName); } Selection.activeObject = asset; } #region Prefs private static string GetPrefsString(string key, string defaultString = null) { return EditorPrefs.GetString(Application.productName + "." + key, defaultString); } private static void SetPrefsString(string key, string value) { EditorPrefs.SetString(Application.productName + "." + key, value); } private static int GetPrefsInt(string key, int defaultInt = 0) { return EditorPrefs.GetInt(Application.productName + "." + key, defaultInt); } private static void SetPrefsInt(string key, int value) { EditorPrefs.SetInt(Application.productName + "." + key, value); } private static bool HasPrefsKey(string key) { return EditorPrefs.HasKey(Application.productName + "." + key); } private static void DeletePrefsKey(string key) { EditorPrefs.DeleteKey(Application.productName + "." + key); } #endregion private static void DeletePath(string key, int index) { var defaultPath = string.Empty; if (Localization.Instance.InputFiles.Count > index) { defaultPath = AssetDatabase.GetAssetPath(Localization.Instance.InputFiles[index].TextAsset); } EditorGUILayout.BeginHorizontal(); EditorGUI.BeginDisabledGroup(true); EditorGUILayout.TextField(GetPrefsString(key, defaultPath)); EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(!HasPrefsKey(key)); if (GUILayout.Button("Clear")) { DeletePrefsKey(key); } EditorGUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); } public override void OnInspectorGUI() { if (refresh) { LocalizationImporter.Refresh(); refresh = false; } EditorGUI.BeginChangeCheck(); serializedObject.Update(); EditorGUILayout.LabelField("Polyglot Localization Settings", (GUIStyle)"IN TitleText"); var polyglotPath = GetPrefsString(PathPrefs); if (string.IsNullOrEmpty(polyglotPath)) { polyglotPath = DefaultPolyglotPath; } var changed = false; if (UpdateTextAsset("polyglotDocument", masterSheet)) { changed = true; masterSheet = null; } DisplayDocsAndSheetId("Official Polyglot Master", true, false, masterSheet, serializedObject.FindProperty("polyglotDocument"), OfficialSheet, OfficialGId, polyglotPath, DownloadMasterSheet); EditorGUILayout.Space(); if (UpdateTextAsset("customDocument", customSheet)) { changed = true; customSheet = null; } DisplayDocsAndSheetId("Custom Sheet", false, !ValidateDownloadCustomSheet(), customSheet, serializedObject.FindProperty("customDocument"), GetPrefsString(CustomDocsIdPrefs), GetPrefsString(CustomSheetIdPrefs), GetPrefsString(CustomPathPrefs), DownloadCustomSheet); EditorGUILayout.Space(); EditorGUILayout.LabelField("Localization Settings", (GUIStyle)"IN TitleText"); var iterator = serializedObject.GetIterator(); for (bool enterChildren = true; iterator.NextVisible(enterChildren); enterChildren = false) { if(iterator.propertyPath.Contains("Document")) continue; #if !ARABSUPPORT_ENABLED if (iterator.propertyPath == "Localize") { using (new EditorGUI.DisabledGroupScope(true)) { EditorGUILayout.Space(); EditorGUILayout.LabelField("Arabic Support", (GUIStyle)"BoldLabel"); EditorGUILayout.HelpBox("Enable Arabic Support with ARABSUPPORT_ENABLED post processor flag", MessageType.Info); EditorGUILayout.Toggle(new GUIContent("Show Tashkeel", "Enable Arabic Support with ARABSUPPORT_ENABLED post processor flag"), true); EditorGUILayout.Toggle(new GUIContent("Use Hindu Numbers", "Enable Arabic Support with ARABSUPPORT_ENABLED post processor flag"), false); } } #endif using (new EditorGUI.DisabledScope("m_Script" == iterator.propertyPath)) EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]); } #if !ARABSUPPORT_ENABLED #endif serializedObject.ApplyModifiedProperties(); if (changed || EditorGUI.EndChangeCheck()) { refresh = true; } } private static bool refresh = false; private bool UpdateTextAsset(string documentProperty, LocalizationAsset localizationAsset) { if (localizationAsset == null) return false; var document = serializedObject.FindProperty(documentProperty); var textAssetProps = document.FindPropertyRelative("textAsset"); if (textAssetProps.objectReferenceValue == null) { textAssetProps.objectReferenceValue = localizationAsset.TextAsset; } var filesList = serializedObject.FindProperty("inputFiles"); var found = false; for (int i = 0; i < filesList.arraySize; i++) { var inputFile = filesList.GetArrayElementAtIndex(i); var textAssetProp = inputFile.FindPropertyRelative("textAsset"); var formatProp = inputFile.FindPropertyRelative("format"); if (textAssetProp.objectReferenceValue == localizationAsset.TextAsset && formatProp.enumValueIndex == (int) localizationAsset.Format) { found = true; break; } } if (!found) { var lastIndex = filesList.arraySize; filesList.InsertArrayElementAtIndex(lastIndex); var inputFile = filesList.GetArrayElementAtIndex(lastIndex); var textAssetProp = inputFile.FindPropertyRelative("textAsset"); textAssetProp.objectReferenceValue = localizationAsset.TextAsset; var formatProp = inputFile.FindPropertyRelative("format"); formatProp.enumValueIndex = (int) localizationAsset.Format; return true; } return false; } private static void DisplayDocsAndSheetId(string title, bool disableId, bool disableOpen, LocalizationAsset sheet, SerializedProperty document, string defaultDocs, string defaultSheet, string defaultTextAssetPath, Action download) { EditorGUILayout.BeginVertical("Box"); EditorGUILayout.LabelField(title, (GUIStyle)"IN TitleText"); EditorGUI.BeginDisabledGroup(disableId); var docsIdProp = document.FindPropertyRelative("docsId"); if (string.IsNullOrEmpty(docsIdProp.stringValue)) { docsIdProp.stringValue = defaultDocs; } EditorGUILayout.PropertyField(docsIdProp); var sheetIdProps = document.FindPropertyRelative("sheetId"); if (string.IsNullOrEmpty(sheetIdProps.stringValue)) { sheetIdProps.stringValue = defaultSheet; } EditorGUILayout.PropertyField(sheetIdProps); var textAssetProps = document.FindPropertyRelative("textAsset"); if (textAssetProps.objectReferenceValue == null && !string.IsNullOrEmpty(defaultTextAssetPath)) { textAssetProps.objectReferenceValue = AssetDatabase.LoadAssetAtPath<TextAsset>(defaultTextAssetPath); } EditorGUILayout.PropertyField(textAssetProps); EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(disableOpen); var downloadOnstartProps = document.FindPropertyRelative("downloadOnStart"); EditorGUILayout.PropertyField(downloadOnstartProps); var formatProps = document.FindPropertyRelative("format"); EditorGUILayout.PropertyField(formatProps); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(string.Empty); if(GUILayout.Button("Open")) { var url = string.Format("https://docs.google.com/spreadsheets/d/{0}/edit#gid={1}", docsIdProp.stringValue, sheetIdProps.stringValue); Application.OpenURL(url); } if(GUILayout.Button("Download")) { download(); } EditorGUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); EditorGUILayout.EndVertical(); } [MenuItem(MenuItemPath + "Download Polyglot Mastersheet", false, 30)] private static void DownloadMasterSheet() { var doc = Localization.Instance.PolyglotDocument; DownloadGoogleSheet(doc); masterSheet = new LocalizationAsset {TextAsset = doc.TextAsset, Format = doc.Format}; } [MenuItem(MenuItemPath + "Download Custom Sheet", true, 30)] private static bool ValidateDownloadCustomSheet() { var doc = Localization.Instance.CustomDocument; return !string.IsNullOrEmpty(doc.DocsId) && !string.IsNullOrEmpty(doc.SheetId); } [MenuItem(MenuItemPath + "Download Custom Sheet", false, 30)] public static void DownloadCustomSheet() { var doc = Localization.Instance.CustomDocument; DownloadGoogleSheet(doc); customSheet = new LocalizationAsset {TextAsset = doc.TextAsset, Format = doc.Format}; } private static void DownloadGoogleSheet(LocalizationDocument doc) { EditorUtility.DisplayCancelableProgressBar("Download", "Downloading...", 0); var iterator = GoogleDownload.DownloadSheet(doc.DocsId, doc.SheetId, t => DownloadComplete(t, doc), doc.Format, DisplayDownloadProgressbar); while(iterator.MoveNext()) {} } private static void DownloadComplete(string text, LocalizationDocument doc) { if (string.IsNullOrEmpty(text)) { Debug.LogError("Could not download google sheet"); return; } var path = doc.TextAsset != null ? AssetDatabase.GetAssetPath(doc.TextAsset) : null; if (string.IsNullOrEmpty(path)) { path = EditorUtility.SaveFilePanelInProject("Save Localization", "", "txt", "Please enter a file name to save the csv to", path); } if (string.IsNullOrEmpty(path)) { return; } File.WriteAllText(path, text); AssetDatabase.ImportAsset(path); doc.TextAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(path); EditorUtility.SetDirty(doc.TextAsset); AssetDatabase.SaveAssets(); } private static bool DisplayDownloadProgressbar(float progress) { if(progress < 1) { return EditorUtility.DisplayCancelableProgressBar("Download Localization", "Downloading...", progress); } EditorUtility.ClearProgressBar(); return false; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using MVCServer.Areas.HelpPage.ModelDescriptions; using MVCServer.Areas.HelpPage.Models; namespace MVCServer.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.Design; using Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization; namespace Microsoft.MultiverseInterfaceStudio.FrameXml.Controls { public class FrameDesigner : BaseControlDesigner { private const string enableMovingDisplay = "Make frame movable"; private const string disableMovingDisplay = "Make frame fixed"; const string startMoveScript = "self:StartMoving();"; const string stopMoveScript = "self:StopMovingOrSizing();"; private DesignerActionListCollection actionLists; /// <summary> /// Gets the design-time action lists supported by the component associated with the designer. /// </summary> /// <value></value> /// <returns>The design-time action lists supported by the component associated with the designer.</returns> public override DesignerActionListCollection ActionLists { get { BaseControl baseControl = this.Component as BaseControl; if (actionLists == null && baseControl != null && baseControl.HasActions) { actionLists = new DesignerActionListCollection(); FrameDesignerActionList actionList = new FrameDesignerActionList(baseControl); actionList.ComponentChanged += new EventHandler(OnComponentChanged); actionLists.Add(actionList); } return actionLists; } } /// <summary> /// Creates a method signature in the source code file for the default event on the component and navigates the user's cursor to that location. /// </summary> /// <exception cref="T:System.ComponentModel.Design.CheckoutException">An attempt to check out a file that is checked into a source code management program failed.</exception> public override void DoDefaultAction() { base.DoDefaultAction(); BaseControl baseControl = this.Component as BaseControl; if (baseControl == null) return; if (baseControl.Inherited) return; if (baseControl.DefaultEventChoice.HasValue) { FrameType frameType = baseControl.SerializationObject as FrameType; if (frameType == null) return; if (frameType.Scripts.Count == 0) frameType.Scripts.Add(new ScriptsType()); IDictionary<EventChoice, string> events = frameType.Scripts[0].Events; EventChoice eventChoice = baseControl.DefaultEventChoice.Value; string eventHandlerName; if (events.ContainsKey(eventChoice)) { eventHandlerName = events[eventChoice].Trim().TrimEnd(';').TrimEnd(')').TrimEnd('('); } else { eventHandlerName = String.Format("{0}_{1}", frameType.name, eventChoice); events.Add(eventChoice, eventHandlerName + "();"); } //LuaInterface luaInterface = new LuaInterface(baseControl.DesignerLoader); //luaInterface.CreateShowFunction(eventHandlerName); } } private void OnComponentChanged(object sender, EventArgs e) { this.RaiseComponentChanged(null, null, null); } private class FrameDesignerActionList : DesignerActionList { private DesignerActionUIService designerActionUIService; private BaseControl control; /// <summary> /// Raised when the component changed. /// </summary> public event EventHandler ComponentChanged; /// <summary> /// Initializes a new instance of the <see cref="FrameDesignerActionList"/> class. /// </summary> /// <param name="control">The base control.</param> public FrameDesignerActionList(BaseControl control) : base(control) { if (control == null) throw new ArgumentNullException("control"); this.control = control; // Get the Designer Action UI service this.designerActionUIService = GetService(typeof(DesignerActionUIService)) as DesignerActionUIService; } /// <summary> /// Returns the collection of <see cref="T:System.ComponentModel.Design.DesignerActionItem"/> objects contained in the list. /// </summary> /// <returns> /// A <see cref="T:System.ComponentModel.Design.DesignerActionItem"/> array that contains the items in this list. /// </returns> public override DesignerActionItemCollection GetSortedActionItems() { // Don't add action to inherited controls if (!this.control.Inherited) { // TODO: refreshing action item display name //bool isMovingEnabled = this.IsMovingEnabled(); //string methodName = (isMovingEnabled) ? "DisableMoving" : "EnableMoving"; //string displayName = (isMovingEnabled) ? FrameDesigner.disableMovingDisplay : enableMovingDisplay; return new DesignerActionItemCollection { //new DesignerActionMethodItem(this, methodName, displayName, true) }; } return null; } /// <summary> /// Makes the frame movable. /// </summary> public void EnableMoving() { FrameType frameType = control.SerializationObject as FrameType; if (frameType != null) { //frameType.movable = true; ScriptsType scripts = GetScripts(frameType, true); if (scripts != null) { // Retrieve current OnMouseDown event string currentOnDown = (scripts.Events.ContainsKey(EventChoice.OnMouseDown)) ? scripts.Events[EventChoice.OnMouseDown] : String.Empty; // Append start move script, if not found if (!currentOnDown.Contains(FrameDesigner.startMoveScript)) currentOnDown += FrameDesigner.startMoveScript; // Set the event handler scripts.Events[EventChoice.OnMouseDown] = currentOnDown; // Retrieve current OnMouseUp event string currentOnUp = (scripts.Events.ContainsKey(EventChoice.OnMouseUp)) ? scripts.Events[EventChoice.OnMouseUp] : String.Empty; // APpend stop move script, if not found if (!currentOnUp.Contains(FrameDesigner.stopMoveScript)) currentOnUp += FrameDesigner.stopMoveScript; // Set the event handler scripts.Events[EventChoice.OnMouseUp] = currentOnUp; } // Raise ComponentChangedEvent this.OnComponentChanged(EventArgs.Empty); // Refresh the Designer Action UI designerActionUIService.Refresh(this.Component); } } /// <summary> /// Makes the frame fixed. /// </summary> public void DisableMoving() { FrameType frameType = control.SerializationObject as FrameType; if (frameType != null) { //frameType.movable = false; ScriptsType scripts = FrameDesigner.FrameDesignerActionList.GetScripts(frameType, false); if (scripts != null) { if (scripts.Events.ContainsKey(EventChoice.OnMouseDown)) { // Retrieve current OnMouseDown event string currentDown = scripts.Events[EventChoice.OnMouseDown] ?? String.Empty; // Remove the start move snippet from the event handler script currentDown = currentDown.Replace(FrameDesigner.startMoveScript, String.Empty); // If there is no code left, remove the event handler script altogether, update otherwise if (String.IsNullOrEmpty(currentDown)) scripts.Events.Remove(EventChoice.OnMouseDown); else scripts.Events[EventChoice.OnMouseDown] = currentDown; } if (scripts.Events.ContainsKey(EventChoice.OnMouseUp)) { // Retrieve current OnMouseUp event string currentUp = (scripts.Events[EventChoice.OnMouseUp] ?? String.Empty); // Remvoe the stop move snippet from the event handler sciprt currentUp = currentUp.Replace(FrameDesigner.stopMoveScript, String.Empty); // If there is no code left, remove the event handler script altogether, update otherwise if (String.IsNullOrEmpty(currentUp)) scripts.Events.Remove(EventChoice.OnMouseUp); else scripts.Events[EventChoice.OnMouseUp] = currentUp; } // Remove the <Scripts> element if no events have handlers now if (scripts.Events.Count == 0) frameType.Scripts.Remove(scripts); } // Raise ComponentChangedEvent this.OnComponentChanged(EventArgs.Empty); // Refresh the Designer Action UI designerActionUIService.Refresh(this.Component); } } private static bool MergeScripts(ScriptsType from, ScriptsType to, EventChoice eventChoice) { if (from.Events.ContainsKey(eventChoice)) { if (to == null) { to = from; return false; } else { // Retrieve current event handler script string currentScript = to.Events.ContainsKey(eventChoice) && to.Events[eventChoice] != null ? to.Events[eventChoice] : String.Empty; // Append script to be merged currentScript += from.Events[eventChoice] ?? String.Empty; // Update event handler script to.Events[eventChoice] = currentScript; return true; } } return false; } private static ScriptsType GetScripts(FrameType frame, bool createOnNull) { ScriptsType result = null; if (frame.Scripts.Count == 0) { if (createOnNull) { result = new ScriptsType(); frame.Scripts.Add(result); } } else { for (int index = frame.Scripts.Count - 1; index >= 0; index--) { ScriptsType scripts = frame.Scripts[index]; if (MergeScripts(scripts, result, EventChoice.OnMouseDown) || MergeScripts(scripts, result, EventChoice.OnMouseUp)) { frame.Scripts.Remove(scripts); } } if (result == null) result = frame.Scripts[0]; } return result; } private bool IsMovingEnabled() { FrameType frame = control.SerializationObject as FrameType; if (frame == null) return false; ScriptsType scripts = GetScripts(frame, false); return frame.movable && scripts != null && scripts.Events.ContainsKey(EventChoice.OnMouseDown) && scripts.Events.ContainsKey(EventChoice.OnMouseUp); } /// <summary> /// Raises the <see cref="ComponentChanged"/> event. /// </summary> /// <param name="e"></param> protected void OnComponentChanged(EventArgs e) { if (ComponentChanged != null) ComponentChanged(this, e); } } } }
using System; using CoreGraphics; using UIKit; using Toggl.Phoebe.Net; using XPlatUtils; using Toggl.Ross.Data; using Toggl.Ross.Theme; namespace Toggl.Ross.ViewControllers { public class NavigationMenuController { private UIViewController controller; private UIView containerView; private UIView menuView; private UIButton logButton; private UIButton reportsButton; private UIButton settingsButton; private UIButton feedbackButton; private UIButton signOutButton; private UIButton[] menuButtons; private UIView[] separators; private bool menuShown; private bool isAnimating; private TogglWindow window; public void Attach (UIViewController controller) { this.controller = controller; window = AppDelegate.TogglWindow; window.OnHitTest += OnTogglWindowHit; controller.NavigationItem.LeftBarButtonItem = new UIBarButtonItem ( Image.IconNav.ImageWithRenderingMode (UIImageRenderingMode.AlwaysOriginal), UIBarButtonItemStyle.Plain, OnNavigationButtonTouched); } public void Detach () { if (window != null) { window.OnHitTest -= OnTogglWindowHit; } window = null; } private void OnTogglWindowHit (UIView view) { if (menuShown) { bool hitInsideMenu = IsSubviewOfMenu (view); if (!hitInsideMenu) { ToggleMenu (); } } } private bool IsSubviewOfMenu (UIView other) { if (menuView == null) { return false; } var enumerator = menuView.Subviews.GetEnumerator (); while (enumerator.MoveNext ()) { if (enumerator.Current == other) { return true; } } return false; } private void EnsureViews () { if (containerView != null) { return; } var navController = controller.NavigationController; if (navController == null) { return; } containerView = new UIView () { ClipsToBounds = true, }; menuView = new UIView ().Apply (Style.NavMenu.Background); menuButtons = new[] { (logButton = new UIButton ()), (reportsButton = new UIButton ()), (settingsButton = new UIButton ()), (feedbackButton = new UIButton ()), (signOutButton = new UIButton ()), }; logButton.SetTitle ("NavMenuLog".Tr (), UIControlState.Normal); reportsButton.SetTitle ("NavMenuReports".Tr (), UIControlState.Normal); settingsButton.SetTitle ("NavMenuSettings".Tr (), UIControlState.Normal); feedbackButton.SetTitle ("NavMenuFeedback".Tr (), UIControlState.Normal); signOutButton.SetTitle ("NavMenuSignOut".Tr (), UIControlState.Normal); foreach (var menuButton in menuButtons) { if (menuButton == logButton && controller is LogViewController) { menuButton.Apply (Style.NavMenu.HighlightedItem); } else { menuButton.Apply (Style.NavMenu.NormalItem); } menuButton.TouchUpInside += OnMenuButtonTouchUpInside; } separators = new UIView[menuButtons.Length - 1]; for (var i = 0; i < separators.Length; i++) { separators [i] = new UIView ().Apply (Style.NavMenu.Separator); } menuView.AddSubviews (separators); menuView.AddSubviews (menuButtons); containerView.AddSubview (menuView); // Layout items: nfloat offsetY = 15f; var sepIdx = 0; foreach (var menuButton in menuButtons) { menuButton.SizeToFit (); var frame = menuButton.Frame; frame.Width = navController.View.Frame.Width; frame.Y = offsetY; menuButton.Frame = frame; offsetY += frame.Height; // Position separator if (sepIdx < separators.Length) { var separator = separators [sepIdx]; var rightMargin = menuButton.ContentEdgeInsets.Right; separator.Frame = new CGRect ( x: rightMargin, y: offsetY, width: navController.View.Frame.Width - rightMargin, height: 1f ); sepIdx += 1; offsetY += separator.Frame.Height; } } offsetY += 15f; containerView.Frame = new CGRect ( x: 0, y: navController.NavigationBar.Frame.Bottom, width: navController.View.Frame.Width, height: offsetY ); menuView.Frame = new CGRect ( x: 0, y: -containerView.Frame.Height, width: containerView.Frame.Width, height: containerView.Frame.Height ); return; } private void OnMenuButtonTouchUpInside (object sender, EventArgs e) { if (sender == logButton && ! (controller is LogViewController)) { ServiceContainer.Resolve<SettingsStore> ().PreferredStartView = "log"; var navController = controller.NavigationController; navController.SetViewControllers (new[] { new LogViewController () }, true); } else if (sender == reportsButton ) { var navController = controller.NavigationController; navController.PushViewController (new ReportsViewController (), true); } else if (sender == settingsButton) { var navController = controller.NavigationController; navController.PushViewController (new SettingsViewController (), true); } else if (sender == feedbackButton) { var navController = controller.NavigationController; navController.PushViewController (new FeedbackViewController (), true); } else if (sender == signOutButton) { ServiceContainer.Resolve<AuthManager> ().Forget (); } ToggleMenu (); } private void OnNavigationButtonTouched (object sender, EventArgs e) { ToggleMenu (); } private void ToggleMenu () { if (isAnimating) { return; } EnsureViews (); if (containerView == null) { return; } isAnimating = true; if (menuShown) { UIView.Animate ( 0.4, 0, UIViewAnimationOptions.BeginFromCurrentState | UIViewAnimationOptions.CurveEaseIn, delegate { menuView.Frame = new CGRect ( x: 0, y: -containerView.Frame.Height, width: containerView.Frame.Width, height: containerView.Frame.Height ); }, delegate { if (!menuShown) { // Remove from subview containerView.RemoveFromSuperview (); } isAnimating = false; }); } else { UIView.Animate ( 0.4, 0, UIViewAnimationOptions.BeginFromCurrentState | UIViewAnimationOptions.CurveEaseOut, delegate { menuView.Frame = new CGRect ( x: 0, y: 0, width: containerView.Frame.Width, height: containerView.Frame.Height ); }, delegate { isAnimating = false; }); // Make sure that the containerView has been added the the view hiearchy if (containerView.Superview == null) { var navController = controller.NavigationController; if (navController != null) { navController.View.AddSubview (containerView); } } } menuShown = !menuShown; containerView.UserInteractionEnabled = menuShown; } } }
// <copyright file="SparseVectorTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // 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. // </copyright> using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Complex32; using MathNet.Numerics.LinearAlgebra.Storage; using NUnit.Framework; using System; using System.Collections.Generic; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32 { using Numerics; /// <summary> /// Sparse vector tests. /// </summary> public class SparseVectorTest : VectorTests { /// <summary> /// Creates a new instance of the Vector class. /// </summary> /// <param name="size">The size of the <strong>Vector</strong> to construct.</param> /// <returns>The new <c>Vector</c>.</returns> protected override Vector<Complex32> CreateVector(int size) { return new SparseVector(size); } /// <summary> /// Creates a new instance of the Vector class. /// </summary> /// <param name="data">The array to create this vector from.</param> /// <returns>The new <c>Vector</c>.</returns> protected override Vector<Complex32> CreateVector(IList<Complex32> data) { var vector = new SparseVector(data.Count); for (var index = 0; index < data.Count; index++) { vector[index] = data[index]; } return vector; } /// <summary> /// Can create a sparse vector form array. /// </summary> [Test] public void CanCreateSparseVectorFromArray() { var data = new Complex32[Data.Length]; Array.Copy(Data, data, Data.Length); var vector = SparseVector.OfEnumerable(data); for (var i = 0; i < data.Length; i++) { Assert.AreEqual(data[i], vector[i]); } } /// <summary> /// Can create a sparse vector from another sparse vector. /// </summary> [Test] public void CanCreateSparseVectorFromAnotherSparseVector() { var vector = SparseVector.OfEnumerable(Data); var other = SparseVector.OfVector(vector); Assert.AreNotSame(vector, other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a sparse vector from another vector. /// </summary> [Test] public void CanCreateSparseVectorFromAnotherVector() { var vector = (Vector<Complex32>) SparseVector.OfEnumerable(Data); var other = SparseVector.OfVector(vector); Assert.AreNotSame(vector, other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a sparse vector from user defined vector. /// </summary> [Test] public void CanCreateSparseVectorFromUserDefinedVector() { var vector = new UserDefinedVector(Data); var other = SparseVector.OfVector(vector); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a sparse matrix. /// </summary> [Test] public void CanCreateSparseMatrix() { var vector = new SparseVector(3); var matrix = Matrix<Complex32>.Build.SameAs(vector, 2, 3); Assert.IsInstanceOf<SparseMatrix>(matrix); Assert.AreEqual(2, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); } /// <summary> /// Can convert a sparse vector to an array. /// </summary> [Test] public void CanConvertSparseVectorToArray() { var vector = SparseVector.OfEnumerable(Data); var array = vector.ToArray(); Assert.IsInstanceOf(typeof (Complex32[]), array); CollectionAssert.AreEqual(vector, array); } /// <summary> /// Can convert an array to a sparse vector. /// </summary> [Test] public void CanConvertArrayToSparseVector() { var array = new[] {new Complex32(1, 1), new Complex32(2, 1), new Complex32(3, 1), new Complex32(4, 1)}; var vector = SparseVector.OfEnumerable(array); Assert.IsInstanceOf(typeof (SparseVector), vector); CollectionAssert.AreEqual(array, array); } /// <summary> /// Can multiply a sparse vector by a Complex using "*" operator. /// </summary> [Test] public void CanMultiplySparseVectorByComplexUsingOperators() { var vector = SparseVector.OfEnumerable(Data); vector = vector*new Complex32(2.0f, 1); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex32(2.0f, 1), vector[i]); } vector = vector*1.0f; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex32(2.0f, 1), vector[i]); } vector = SparseVector.OfEnumerable(Data); vector = new Complex32(2.0f, 1)*vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex32(2.0f, 1), vector[i]); } vector = 1.0f*vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex32(2.0f, 1), vector[i]); } } /// <summary> /// Can divide a sparse vector by a Complex using "/" operator. /// </summary> [Test] public void CanDivideSparseVectorByComplexUsingOperators() { var vector = SparseVector.OfEnumerable(Data); vector = vector/new Complex32(2.0f, 1); for (var i = 0; i < Data.Length; i++) { AssertHelpers.AlmostEqualRelative(Data[i]/new Complex32(2.0f, 1), vector[i], 6); } vector = vector/1.0f; for (var i = 0; i < Data.Length; i++) { AssertHelpers.AlmostEqualRelative(Data[i]/new Complex32(2.0f, 1), vector[i], 6); } } /// <summary> /// Can calculate an outer product for a sparse vector. /// </summary> [Test] public void CanCalculateOuterProductForSparseVector() { var vector1 = CreateVector(Data); var vector2 = CreateVector(Data); var m = Vector<Complex32>.OuterProduct(vector1, vector2); for (var i = 0; i < vector1.Count; i++) { for (var j = 0; j < vector2.Count; j++) { Assert.AreEqual(m[i, j], vector1[i]*vector2[j]); } } } /// <summary> /// Check sparse mechanism by setting values. /// </summary> [Test] public void CheckSparseMechanismBySettingValues() { var vector = new SparseVector(10000); var storage = (SparseVectorStorage<Complex32>) vector.Storage; // Add non-zero elements vector[200] = new Complex32(1.5f, 1); Assert.AreEqual(new Complex32(1.5f, 1), vector[200]); Assert.AreEqual(1, storage.ValueCount); vector[500] = new Complex32(3.5f, 1); Assert.AreEqual(new Complex32(3.5f, 1), vector[500]); Assert.AreEqual(2, storage.ValueCount); vector[800] = new Complex32(5.5f, 1); Assert.AreEqual(new Complex32(5.5f, 1), vector[800]); Assert.AreEqual(3, storage.ValueCount); vector[0] = new Complex32(7.5f, 1); Assert.AreEqual(new Complex32(7.5f, 1), vector[0]); Assert.AreEqual(4, storage.ValueCount); // Remove non-zero elements vector[200] = Complex32.Zero; Assert.AreEqual(Complex32.Zero, vector[200]); Assert.AreEqual(3, storage.ValueCount); vector[500] = Complex32.Zero; Assert.AreEqual(Complex32.Zero, vector[500]); Assert.AreEqual(2, storage.ValueCount); vector[800] = Complex32.Zero; Assert.AreEqual(Complex32.Zero, vector[800]); Assert.AreEqual(1, storage.ValueCount); vector[0] = Complex32.Zero; Assert.AreEqual(Complex32.Zero, vector[0]); Assert.AreEqual(0, storage.ValueCount); } /// <summary> /// Check sparse mechanism by zero multiply. /// </summary> [Test] public void CheckSparseMechanismByZeroMultiply() { var vector = new SparseVector(10000); // Add non-zero elements vector[200] = new Complex32(1.5f, 1); vector[500] = new Complex32(3.5f, 1); vector[800] = new Complex32(5.5f, 1); vector[0] = new Complex32(7.5f, 1); // Multiply by 0 vector *= 0; var storage = (SparseVectorStorage<Complex32>) vector.Storage; Assert.AreEqual(Complex32.Zero, vector[200]); Assert.AreEqual(Complex32.Zero, vector[500]); Assert.AreEqual(Complex32.Zero, vector[800]); Assert.AreEqual(Complex32.Zero, vector[0]); Assert.AreEqual(0, storage.ValueCount); } /// <summary> /// Can calculate a dot product of two sparse vectors. /// </summary> [Test] public void CanDotProductOfTwoSparseVectors() { var vectorA = new SparseVector(10000); vectorA[200] = 1; vectorA[500] = 3; vectorA[800] = 5; vectorA[100] = 7; vectorA[900] = 9; var vectorB = new SparseVector(10000); vectorB[300] = 3; vectorB[500] = 5; vectorB[800] = 7; Assert.AreEqual(new Complex32(50.0f, 0), vectorA.DotProduct(vectorB)); } /// <summary> /// Can pointwise multiple a sparse vector. /// </summary> [Test] public void CanPointwiseMultiplySparseVector() { var zeroArray = new[] {Complex32.Zero, new Complex32(1.0f, 1), Complex32.Zero, new Complex32(1.0f, 1), Complex32.Zero}; var vector1 = SparseVector.OfEnumerable(Data); var vector2 = SparseVector.OfEnumerable(zeroArray); var result = new SparseVector(vector1.Count); vector1.PointwiseMultiply(vector2, result); for (var i = 0; i < vector1.Count; i++) { Assert.AreEqual(Data[i]*zeroArray[i], result[i]); } var resultStorage = (SparseVectorStorage<Complex32>) result.Storage; Assert.AreEqual(2, resultStorage.ValueCount); } /// <summary> /// Test for issues #52. When setting previous non-zero values to zero, /// DoMultiply would copy non-zero values to the result, but use the /// length of nonzerovalues instead of NonZerosCount. /// </summary> [Test] public void CanScaleAVectorWhenSettingPreviousNonzeroElementsToZero() { var vector = new SparseVector(20); vector[10] = 1.0f; vector[11] = 2.0f; vector[11] = 0.0f; var scaled = new SparseVector(20); vector.Multiply(3.0f, scaled); Assert.AreEqual(3.0f, scaled[10].Real); Assert.AreEqual(0.0f, scaled[11].Real); } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (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/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // #pragma warning disable 1587,0414 #region Header /// /// JsonReader.cs /// Stream-like access to JSON text. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace ThirdParty.Json.LitJson { public enum JsonToken { None, ObjectStart, PropertyName, ObjectEnd, ArrayStart, ArrayEnd, Int, Long, Double, String, Boolean, Null } public class JsonReader { #region Fields private Stack<JsonToken> depth = new Stack<JsonToken>(); private int current_input; private int current_symbol; private bool end_of_json; private bool end_of_input; private Lexer lexer; private bool parser_in_string; private bool parser_return; private bool read_started; private TextReader reader; private bool reader_is_owned; private object token_value; private JsonToken token; #endregion #region Public Properties public bool AllowComments { get { return lexer.AllowComments; } set { lexer.AllowComments = value; } } public bool AllowSingleQuotedStrings { get { return lexer.AllowSingleQuotedStrings; } set { lexer.AllowSingleQuotedStrings = value; } } public bool EndOfInput { get { return end_of_input; } } public bool EndOfJson { get { return end_of_json; } } public JsonToken Token { get { return token; } } public object Value { get { return token_value; } } #endregion #region Constructors public JsonReader (string json_text) : this (new StringReader (json_text), true) { } public JsonReader (TextReader reader) : this (reader, false) { } private JsonReader (TextReader reader, bool owned) { if (reader == null) throw new ArgumentNullException ("reader"); parser_in_string = false; parser_return = false; read_started = false; lexer = new Lexer (reader); end_of_input = false; end_of_json = false; this.reader = reader; reader_is_owned = owned; } #endregion #region Private Methods private void ProcessNumber (string number) { if (number.IndexOf ('.') != -1 || number.IndexOf ('e') != -1 || number.IndexOf ('E') != -1) { double n_double; if (Double.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_double)) { token = JsonToken.Double; token_value = n_double; return; } } int n_int32; if (Int32.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_int32)) { token = JsonToken.Int; token_value = n_int32; return; } long n_int64; if (Int64.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_int64)) { token = JsonToken.Long; token_value = n_int64; return; } // Shouldn't happen, but just in case, return something token = JsonToken.Int; token_value = 0; } private void ProcessSymbol () { if (current_symbol == '[') { token = JsonToken.ArrayStart; parser_return = true; } else if (current_symbol == ']') { token = JsonToken.ArrayEnd; parser_return = true; } else if (current_symbol == '{') { token = JsonToken.ObjectStart; parser_return = true; } else if (current_symbol == '}') { token = JsonToken.ObjectEnd; parser_return = true; } else if (current_symbol == '"') { if (parser_in_string) { parser_in_string = false; parser_return = true; } else { if (token == JsonToken.None) token = JsonToken.String; parser_in_string = true; } } else if (current_symbol == (int) ParserToken.CharSeq) { token_value = lexer.StringValue; } else if (current_symbol == (int) ParserToken.False) { token = JsonToken.Boolean; token_value = false; parser_return = true; } else if (current_symbol == (int) ParserToken.Null) { token = JsonToken.Null; parser_return = true; } else if (current_symbol == (int) ParserToken.Number) { ProcessNumber (lexer.StringValue); parser_return = true; } else if (current_symbol == (int) ParserToken.Pair) { token = JsonToken.PropertyName; } else if (current_symbol == (int) ParserToken.True) { token = JsonToken.Boolean; token_value = true; parser_return = true; } } private bool ReadToken () { if (end_of_input) return false; lexer.NextToken (); if (lexer.EndOfInput) { Close (); return false; } current_input = lexer.Token; return true; } #endregion public void Close () { if (end_of_input) return; end_of_input = true; end_of_json = true; reader = null; } public bool Read() { if (end_of_input) return false; if (end_of_json) { end_of_json = false; } token = JsonToken.None; parser_in_string = false; parser_return = false; // Check if the first read call. If so then do an extra ReadToken because Read assumes that the previous // call to Read has already called ReadToken. if (!read_started) { read_started = true; if (!ReadToken()) return false; } do { current_symbol = current_input; ProcessSymbol(); if (parser_return) { if (this.token == JsonToken.ObjectStart || this.token == JsonToken.ArrayStart) { depth.Push(this.token); } else if (this.token == JsonToken.ObjectEnd || this.token == JsonToken.ArrayEnd) { // Clear out property name if is on top. This could happen if the value for the property was null. if (depth.Peek() == JsonToken.PropertyName) depth.Pop(); // Pop the opening token for this closing token. Make sure it is of the right type otherwise // the document is invalid. var opening = depth.Pop(); if (this.token == JsonToken.ObjectEnd && opening != JsonToken.ObjectStart) throw new JsonException("Error: Current token is ObjectEnd which does not match the opening " + opening.ToString()); if (this.token == JsonToken.ArrayEnd && opening != JsonToken.ArrayStart) throw new JsonException("Error: Current token is ArrayEnd which does not match the opening " + opening.ToString()); // If that last element is popped then we reached the end of the JSON object. if (depth.Count == 0) { end_of_json = true; } } // If the top of the stack is an object start and the next read is a string then it must be a property name // to add to the stack. else if (depth.Count > 0 && depth.Peek() != JsonToken.PropertyName && this.token == JsonToken.String && depth.Peek() == JsonToken.ObjectStart) { this.token = JsonToken.PropertyName; depth.Push(this.token); } if ( (this.token == JsonToken.ObjectEnd || this.token == JsonToken.ArrayEnd || this.token == JsonToken.String || this.token == JsonToken.Boolean || this.token == JsonToken.Double || this.token == JsonToken.Int || this.token == JsonToken.Long || this.token == JsonToken.Null || this.token == JsonToken.String )) { // If we found a value but we are not in an array or object then the document is an invalid json document. if (depth.Count == 0) { if (this.token != JsonToken.ArrayEnd && this.token != JsonToken.ObjectEnd) { throw new JsonException("Value without enclosing object or array"); } } // The valud of the property has been processed so pop the property name from the stack. else if (depth.Peek() == JsonToken.PropertyName) { depth.Pop(); } } // Read the next token that will be processed the next time the Read method is called. // This is done ahead of the next read so we can detect if we are at the end of the json document. // Otherwise EndOfInput would not return true until an attempt to read was made. if (!ReadToken() && depth.Count != 0) throw new JsonException("Incomplete JSON Document"); return true; } } while (ReadToken()); // If we reached the end of the document but there is still elements left in the depth stack then // the document is invalid JSON. if (depth.Count != 0) throw new JsonException("Incomplete JSON Document"); end_of_input = true; return false; } } } #pragma warning restore 1587,0414
/* Copyright 2010 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. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using Newtonsoft.Json; using NUnit.Framework; using Google.Apis.Discovery; using Google.Apis.Json; using Google.Apis.Requests; using Google.Apis.Testing; using Google.Apis.Util; namespace Google.Apis.Tests.Apis.Discovery { /// <summary> Test for the "BaseService" class. </summary> [TestFixture] public class BaseServiceTest { private class ConcreteClass : BaseService { public ConcreteClass(JsonDictionary js) : base(ServiceFactory.Default, js, new ConcreteFactoryParameters()) { } public new string ServerUrl { get { return base.ServerUrl; } set { base.ServerUrl = value; } } public new string BasePath { get { return base.BasePath; } set { base.BasePath = value; } } #region Nested type: ConcreteFactoryParameters private class ConcreteFactoryParameters : FactoryParameters { public ConcreteFactoryParameters() : base("http://test/", "testService/") { } } #endregion } #region Test Helper methods private IService CreateService(DiscoveryVersion version) { return version == DiscoveryVersion.Version_0_3 ? CreateLegacyV03Service() : CreateV1Service(); } private IService CreateV1Service() { var dict = new JsonDictionary(); dict.Add("name", "TestName"); dict.Add("version", "v1"); return new ConcreteClass(dict); } private IService CreateLegacyV03Service() { var dict = new JsonDictionary(); dict.Add("name", "TestName"); dict.Add("version", "v1"); dict.Add("features", new[] { Features.LegacyDataResponse.GetStringValue() }); return new ConcreteClass(dict); } #endregion /// <summary> /// This test confirms that the BaseService will not crash on non-existent, optional fields /// within the JSON document. /// </summary> [Test] public void TestNoThrowOnFieldsMissing() { IService impl = CreateV1Service(); Assert.AreEqual("v1", impl.Version); Assert.IsNull(impl.Id); Assert.IsNotNull(impl.Labels); MoreAsserts.IsEmpty(impl.Labels); Assert.AreEqual("TestName", impl.Name); Assert.IsNull(impl.Protocol); Assert.IsNull(impl.Title); } /// <summary> /// The test targets the more basic properties of the BaseService. /// It should ensure that all properties return the values assigned to them within the JSON document. /// </summary> [Test] public void TestSimpleGetters() { var dict = new JsonDictionary(); dict.Add("name", "TestName"); dict.Add("version", "v1"); dict.Add("description", "Test Description"); dict.Add("documentationLink", "https://www.google.com/"); dict.Add("features", new List<object> { "feature1", "feature2" }); dict.Add("labels", new List<object> { "label1", "label2" }); dict.Add("id", "TestId"); dict.Add("title", "Test API"); IService impl = new ConcreteClass(dict); Assert.AreEqual("Test Description", impl.Description); Assert.AreEqual("https://www.google.com/", impl.DocumentationLink); MoreAsserts.ContentsEqualAndInOrder(new List<string> { "feature1", "feature2" }, impl.Features); MoreAsserts.ContentsEqualAndInOrder(new List<string> { "label1", "label2" }, impl.Labels); Assert.AreEqual("TestId", impl.Id); Assert.AreEqual("Test API", impl.Title); } /// <summary> /// Confirms that OAuth2 scopes can be parsed correctly. /// </summary> [Test] public void TestOAuth2Scopes() { var scopes = new JsonDictionary(); scopes.Add("https://www.example.com/auth/one", new Scope() { ID = "https://www.example.com/auth/one" }); scopes.Add("https://www.example.com/auth/two", new Scope() { ID = "https://www.example.com/auth/two" }); var oauth2 = new JsonDictionary() { { "scopes", scopes } }; var auth = new JsonDictionary() { { "oauth2", oauth2 } }; var dict = new JsonDictionary() { { "auth", auth }, { "name", "TestName" }, { "version", "v1" } }; IService impl = new ConcreteClass(dict); Assert.IsNotNull(impl.Scopes); Assert.AreEqual(2, impl.Scopes.Count); Assert.IsTrue(impl.Scopes.ContainsKey("https://www.example.com/auth/one")); Assert.IsTrue(impl.Scopes.ContainsKey("https://www.example.com/auth/two")); } /// <summary> /// Test that the Parameters property is initialized. /// </summary> [Test] public void TestCommonParameters() { const string testJson = @"{ 'fields': { 'type': 'string', 'description': 'Selector specifying which fields to include in a partial response.', 'location': 'query' }, 'prettyPrint': { 'type': 'boolean', 'description': 'Returns response with indentations and line breaks.', 'default': 'true', 'location': 'query' }, }"; var paramDict = Google.Apis.Json.JsonReader.Parse(testJson.Replace('\'', '\"')) as JsonDictionary; var dict = new JsonDictionary() { { "parameters", paramDict}, { "name", "TestName" }, { "version", "v1" } }; var impl = new ConcreteClass(dict); Assert.That(impl.Parameters.Count, Is.EqualTo(2)); Assert.That(impl.Parameters.Keys, Is.EquivalentTo(new string[] { "fields", "prettyPrint" })); var prettyPrint = impl.Parameters["prettyPrint"]; Assert.That(prettyPrint.Description, Is.EqualTo("Returns response with indentations and line breaks.")); Assert.That(prettyPrint.ValueType, Is.EqualTo("boolean")); } /// <summary> /// Test a service with empty parameters. /// </summary> [Test] public void TestCommonParametersEmpty() { var paramDict = new JsonDictionary(); var dict = new JsonDictionary() { { "parameters", paramDict }, { "name", "TestName" }, { "version", "v1" } }; var impl = new ConcreteClass(dict); Assert.That(impl.Parameters, Is.Not.Null); Assert.That(impl.Parameters.Count, Is.EqualTo(0)); } /// <summary> /// Test a service with no parameters /// </summary> [Test] public void TestCommonParametersMissing() { var paramDict = new JsonDictionary(); var dict = new JsonDictionary() { { "name", "TestName" }, { "version", "v1" } }; var impl = new ConcreteClass(dict); Assert.That(impl.Parameters, Is.Not.Null); Assert.That(impl.Parameters.Count, Is.EqualTo(0)); } /// <summary> /// Confirms that methods, which are directly on the service, are supported /// </summary> [Test] public void TestMethodsOnService() { var testMethod = new JsonDictionary(); testMethod.Add("id", "service.testMethod"); testMethod.Add("path", "service/testMethod"); testMethod.Add("httpMethod", "GET"); var methods = new JsonDictionary() { { "testMethod", testMethod } }; var dict = new JsonDictionary() { { "methods", methods }, { "name", "TestName" }, { "version", "v1" } }; IService impl = new ConcreteClass(dict); Assert.IsNotNull(impl.Methods); Assert.AreEqual(1, impl.Methods.Count); Assert.AreEqual("testMethod", impl.Methods["testMethod"].Name); } [Test] public void TestBaseUri() { ConcreteClass instance = (ConcreteClass)CreateV1Service(); instance.BasePath = "/test/"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); instance.BasePath = "test/"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); instance.BasePath = "/test/"; instance.ServerUrl = "https://www.test.value"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); instance.BasePath = "test/"; instance.ServerUrl = "https://www.test.value"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); // Mono's Uri class strips double forward slashes so this test will not work. // Only run for MS.Net if (Google.Apis.Util.Utilities.IsMonoRuntime() == false) { instance.BasePath = "//test/"; instance.ServerUrl = "https://www.test.value"; Assert.AreEqual("https://www.test.value//test/", instance.BaseUri.ToString()); instance.BasePath = "//test/"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value//test/", instance.BaseUri.ToString()); instance.BasePath = "test/"; instance.ServerUrl = "https://www.test.value//"; Assert.AreEqual("https://www.test.value//test/", instance.BaseUri.ToString()); instance.BasePath = "/test//"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value/test//", instance.BaseUri.ToString()); } } [Test] public void RemoveAnnotations() { string json = @" { 'schemas': { 'Event': { 'id': 'Event', 'type': 'object', 'properties': { 'description': { 'type': 'string', 'description': 'Description of the event. Optional.' }, 'end': { '$ref': 'EventDateTime', 'description': 'The (exclusive) end time of the event. For a recurring event, this is the end time of the first instance.', 'annotations': { 'required': [ 'calendar.events.import', 'calendar.events.insert', 'calendar.events.update' ] } }, } } } }"; JsonDictionary js = Google.Apis.Json.JsonReader.Parse(json) as JsonDictionary; var end = AssertNode(js, "schemas", "Event", "properties", "end"); Assert.That(end.Count, Is.EqualTo(3)); Assert.That(end.ContainsKey("annotations"), Is.True); BaseService.RemoveAnnotations(js, 0); Assert.That(end.Count, Is.EqualTo(2)); Assert.That(end.ContainsKey("annotations"), Is.False); } private JsonDictionary AssertNode(JsonDictionary dict, params string[] nodes) { JsonDictionary cur = dict; for (int i = 0; i < nodes.Length; i++) { Assert.That(cur.ContainsKey(nodes[i])); Assert.That(cur[nodes[i]], Is.TypeOf(typeof(JsonDictionary))); cur = cur[nodes[i]] as JsonDictionary; } return cur; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedNodeGroupsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNodeGroupRequest request = new GetNodeGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NodeGroup = "node_groupa42a295a", }; NodeGroup expectedResponse = new NodeGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = "status5444cb9a", MaintenanceWindow = new NodeGroupMaintenanceWindow(), AutoscalingPolicy = new NodeGroupAutoscalingPolicy(), Fingerprint = "fingerprint009e6052", NodeTemplate = "node_template118e38ae", LocationHint = "location_hint666f366c", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", MaintenancePolicy = "maintenance_policy80cc92a6", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); NodeGroup response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNodeGroupRequest request = new GetNodeGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NodeGroup = "node_groupa42a295a", }; NodeGroup expectedResponse = new NodeGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = "status5444cb9a", MaintenanceWindow = new NodeGroupMaintenanceWindow(), AutoscalingPolicy = new NodeGroupAutoscalingPolicy(), Fingerprint = "fingerprint009e6052", NodeTemplate = "node_template118e38ae", LocationHint = "location_hint666f366c", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", MaintenancePolicy = "maintenance_policy80cc92a6", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NodeGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); NodeGroup responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); NodeGroup responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNodeGroupRequest request = new GetNodeGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NodeGroup = "node_groupa42a295a", }; NodeGroup expectedResponse = new NodeGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = "status5444cb9a", MaintenanceWindow = new NodeGroupMaintenanceWindow(), AutoscalingPolicy = new NodeGroupAutoscalingPolicy(), Fingerprint = "fingerprint009e6052", NodeTemplate = "node_template118e38ae", LocationHint = "location_hint666f366c", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", MaintenancePolicy = "maintenance_policy80cc92a6", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); NodeGroup response = client.Get(request.Project, request.Zone, request.NodeGroup); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNodeGroupRequest request = new GetNodeGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NodeGroup = "node_groupa42a295a", }; NodeGroup expectedResponse = new NodeGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = "status5444cb9a", MaintenanceWindow = new NodeGroupMaintenanceWindow(), AutoscalingPolicy = new NodeGroupAutoscalingPolicy(), Fingerprint = "fingerprint009e6052", NodeTemplate = "node_template118e38ae", LocationHint = "location_hint666f366c", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", MaintenancePolicy = "maintenance_policy80cc92a6", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NodeGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); NodeGroup responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.NodeGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); NodeGroup responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.NodeGroup, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyNodeGroupRequest request = new GetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyNodeGroupRequest request = new GetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyNodeGroupRequest request = new GetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request.Project, request.Zone, request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyNodeGroupRequest request = new GetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyNodeGroupRequest request = new SetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyNodeGroupRequest request = new SetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyNodeGroupRequest request = new SetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyNodeGroupRequest request = new SetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNodeGroupRequest request = new TestIamPermissionsNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNodeGroupRequest request = new TestIamPermissionsNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNodeGroupRequest request = new TestIamPermissionsNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNodeGroupRequest request = new TestIamPermissionsNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.EntityState.Marking { /// <summary> /// Enumeration values for ArmyMarkingHighLevelUnitFor1stCavalry (es.markingtext.cctt.1cavunit, Byte 3 - High Level Unit (Byte 2 = 1 - 1st Cavalry), /// section 4.5.1) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public enum ArmyMarkingHighLevelUnitFor1stCavalry : byte { /// <summary> /// 1-7CAV. unit: 1-7 Cavalry. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("1-7CAV. unit: 1-7 Cavalry.")] _17CAVUnit17Cavalry = 1, /// <summary> /// 2-5CAV. unit: 2-5 Cavalry. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("2-5CAV. unit: 2-5 Cavalry.")] _25CAVUnit25Cavalry = 2, /// <summary> /// 2-8CAV. unit: 2-8 Cavalry. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("2-8CAV. unit: 2-8 Cavalry.")] _28CAVUnit28Cavalry = 3, /// <summary> /// 3-32AR. unit: 3-32 Armor Reg. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("3-32AR. unit: 3-32 Armor Reg.")] _332ARUnit332ArmorReg = 4, /// <summary> /// 1-5CAV. unit: 1-5 Cavalry. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("1-5CAV. unit: 1-5 Cavalry.")] _15CAVUnit15Cavalry = 5, /// <summary> /// 1-8CAV. unit: 1-8 Cavalry. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("1-8CAV. unit: 1-8 Cavalry.")] _18CAVUnit18Cavalry = 6, /// <summary> /// 1-32AR. unit: 1-32 Armor Reg. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("1-32AR. unit: 1-32 Armor Reg.")] _132ARUnit132ArmorReg = 7, /// <summary> /// 1-67AR. unit: 1-67 Armor Reg. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("1-67AR. unit: 1-67 Armor Reg.")] _167ARUnit167ArmorReg = 8, /// <summary> /// 3-67AR. unit: 3-67 Armor Reg. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("3-67AR. unit: 3-67 Armor Reg.")] _367ARUnit367ArmorReg = 9, /// <summary> /// 3-41INF. unit: 3-41 Infantry. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("3-41INF. unit: 3-41 Infantry.")] _341INFUnit341Infantry = 10, /// <summary> /// 1-82F. unit: 1-82 Field Art. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("1-82F. unit: 1-82 Field Art.")] _182FUnit182FieldArt = 20, /// <summary> /// 3-82F. unit: 3-82 Field Art. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("3-82F. unit: 3-82 Field Art.")] _382FUnit382FieldArt = 21, /// <summary> /// 1-3F. unit: 1-3 Field Art. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("1-3F. unit: 1-3 Field Art.")] _13FUnit13FieldArt = 22, /// <summary> /// 21F. unit: 21 Field Art. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("21F. unit: 21 Field Art.")] _21FUnit21FieldArt = 23, /// <summary> /// 92F. unit: 92 Field Art. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("92F. unit: 92 Field Art.")] _92FUnit92FieldArt = 24, /// <summary> /// 8E. unit: 8 Engineer. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("8E. unit: 8 Engineer.")] _8EUnit8Engineer = 30, /// <summary> /// 20E. unit: 20 Engineer. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("20E. unit: 20 Engineer.")] _20EUnit20Engineer = 31, /// <summary> /// 91E. unit: 91 Engineer. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("91E. unit: 91 Engineer.")] _91EUnit91Engineer = 32, /// <summary> /// 1-227AVN. unit: 1-227 Aviation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("1-227AVN. unit: 1-227 Aviation.")] _1227AVNUnit1227Aviation = 34, /// <summary> /// 4-227AVN. unit: 4-227 Aviation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("4-227AVN. unit: 4-227 Aviation.")] _4227AVNUnit4227Aviation = 35, /// <summary> /// F-227AVN. unit: F-227 Aviation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("F-227AVN. unit: F-227 Aviation.")] F227AVNUnitF227Aviation = 36, /// <summary> /// 4-5ADA. unit: 4-5 Air Def Art. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("4-5ADA. unit: 4-5 Air Def Art.")] _45ADAUnit45AirDefArt = 37, /// <summary> /// 15MSB. unit: 15 Main Supp. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("15MSB. unit: 15 Main Supp.")] _15MSBUnit15MainSupp = 40, /// <summary> /// 27FSB. unit: 27 Forward Supp. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("27FSB. unit: 27 Forward Supp.")] _27FSBUnit27ForwardSupp = 41, /// <summary> /// 115FSB. unit: 115 Forward Supp. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("115FSB. unit: 115 Forward Supp.")] _115FSBUnit115ForwardSupp = 42, /// <summary> /// 215FSB. unit: 215 Forward Supp. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("215FSB. unit: 215 Forward Supp.")] _215FSBUnit215ForwardSupp = 43, /// <summary> /// 312MI. unit: 312 Mil Intell.. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("312MI. unit: 312 Mil Intell..")] _312MIUnit312MilIntell = 45, /// <summary> /// 13S. unit: 13 Signal. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("13S. unit: 13 Signal.")] _13SUnit13Signal = 46, /// <summary> /// 545MP. unit: 545 Mil Police. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("545MP. unit: 545 Mil Police.")] _545MPUnit545MilPolice = 47, /// <summary> /// 68CML. unit: 68 Chemical. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("68CML. unit: 68 Chemical.")] _68CMLUnit68Chemical = 48, /// <summary> /// 1CAV. unit: HHC 1st Cavalry. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("1CAV. unit: HHC 1st Cavalry.")] _1CAVUnitHHC1stCavalry = 50, /// <summary> /// HHC 1 BDE /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("HHC 1 BDE")] HHC_1_BDE = 51, /// <summary> /// HHC 2 BDE /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("HHC 2 BDE")] HHC_2_BDE = 52, /// <summary> /// HHC 3 BDE /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("HHC 3 BDE")] HHC_3_BDE = 53, /// <summary> /// HHC 4 BDE /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("HHC 4 BDE")] HHC_4_BDE = 54, /// <summary> /// AVNBDE. unit: HHC AVN BDE. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("AVNBDE. unit: HHC AVN BDE.")] AVNBDEUnitHHCAVNBDE = 55, /// <summary> /// E. unit: HHD EN BDE. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("E. unit: HHD EN BDE.")] EUnitHHDENBDE = 56, /// <summary> /// F. unit: HHB DIVARTY. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("F. unit: HHB DIVARTY.")] FUnitHHBDIVARTY = 57, /// <summary> /// DSC. unit: DISCOM. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("DSC. unit: DISCOM.")] DSCUnitDISCOM = 58 } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using Apache.Ignite.Core.Binary; /// <summary> /// Resolves types by name. /// </summary> internal class TypeResolver { /** Assemblies loaded in ReflectionOnly mode. */ private readonly Dictionary<string, Assembly> _reflectionOnlyAssemblies = new Dictionary<string, Assembly>(); /// <summary> /// Resolve type by name. /// </summary> /// <param name="typeName">Name of the type.</param> /// <param name="assemblyName">Optional, name of the assembly.</param> /// <param name="nameMapper">The name mapper.</param> /// <returns> /// Resolved type. /// </returns> public Type ResolveType(string typeName, string assemblyName = null, IBinaryNameMapper nameMapper = null) { Debug.Assert(!string.IsNullOrEmpty(typeName)); // Fully-qualified name can be resolved with system mechanism. var type = Type.GetType(typeName, false); if (type != null) { return type; } var parsedType = TypeNameParser.Parse(typeName); // Partial names should be resolved by scanning assemblies. return ResolveType(assemblyName, parsedType, AppDomain.CurrentDomain.GetAssemblies(), nameMapper) ?? ResolveTypeInReferencedAssemblies(assemblyName, parsedType, nameMapper); } /// <summary> /// Resolve type by name in specified assembly set. /// </summary> /// <param name="assemblyName">Name of the assembly.</param> /// <param name="typeName">Name of the type.</param> /// <param name="assemblies">Assemblies to look in.</param> /// <param name="nameMapper">The name mapper.</param> /// <returns> /// Resolved type. /// </returns> private static Type ResolveType(string assemblyName, TypeNameParser typeName, ICollection<Assembly> assemblies, IBinaryNameMapper nameMapper) { var type = ResolveNonGenericType(assemblyName, typeName.GetNameWithNamespace(), assemblies, nameMapper); if (type == null) { return null; } if (type.IsGenericTypeDefinition && typeName.Generics != null) { var genArgs = typeName.Generics .Select(x => ResolveType(assemblyName, x, assemblies, nameMapper)).ToArray(); if (genArgs.Any(x => x == null)) { return null; } type = type.MakeGenericType(genArgs); } return MakeArrayType(type, typeName.GetArray()); } /// <summary> /// Makes the array type according to spec, e.g. "[,][]". /// </summary> private static Type MakeArrayType(Type type, string arraySpec) { if (arraySpec == null) { return type; } int? rank = null; foreach (var c in arraySpec) { switch (c) { case '[': rank = null; break; case ',': rank = rank == null ? 2 : rank + 1; break; case '*': rank = 1; break; case ']': type = rank == null ? type.MakeArrayType() : type.MakeArrayType(rank.Value); break; } } return type; } /// <summary> /// Resolves non-generic type by searching provided assemblies. /// </summary> /// <param name="assemblyName">Name of the assembly.</param> /// <param name="typeName">Name of the type.</param> /// <param name="assemblies">The assemblies.</param> /// <param name="nameMapper">The name mapper.</param> /// <returns>Resolved type, or null.</returns> private static Type ResolveNonGenericType(string assemblyName, string typeName, ICollection<Assembly> assemblies, IBinaryNameMapper nameMapper) { // Fully-qualified name can be resolved with system mechanism. var type = Type.GetType(typeName, false); if (type != null) { return type; } if (!string.IsNullOrEmpty(assemblyName)) { assemblies = assemblies .Where(x => x.FullName == assemblyName || x.GetName().Name == assemblyName).ToArray(); } if (!assemblies.Any()) { return null; } return assemblies.Select(a => FindType(a, typeName, nameMapper)).FirstOrDefault(x => x != null); } /// <summary> /// Resolve type by name in non-loaded referenced assemblies. /// </summary> /// <param name="assemblyName">Name of the assembly.</param> /// <param name="typeName">Name of the type.</param> /// <param name="nameMapper">The name mapper.</param> /// <returns> /// Resolved type. /// </returns> private Type ResolveTypeInReferencedAssemblies(string assemblyName, TypeNameParser typeName, IBinaryNameMapper nameMapper) { ResolveEventHandler resolver = (sender, args) => GetReflectionOnlyAssembly(args.Name); AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolver; try { var result = ResolveType(assemblyName, typeName, GetNotLoadedReferencedAssemblies().ToArray(), nameMapper); if (result == null) return null; // result is from ReflectionOnly assembly, load it properly into current domain var asm = AppDomain.CurrentDomain.Load(result.Assembly.GetName()); return FindType(asm, result.FullName, nameMapper); } finally { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolver; } } /// <summary> /// Gets the reflection only assembly. /// </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private Assembly GetReflectionOnlyAssembly(string fullName) { Assembly result; if (!_reflectionOnlyAssemblies.TryGetValue(fullName, out result)) { try { result = Assembly.ReflectionOnlyLoad(fullName); } catch (Exception) { // Some assemblies may fail to load result = null; } _reflectionOnlyAssemblies[fullName] = result; } return result; } /// <summary> /// Recursively gets all referenced assemblies for current app domain, excluding those that are loaded. /// </summary> private IEnumerable<Assembly> GetNotLoadedReferencedAssemblies() { var roots = new Stack<Assembly>(AppDomain.CurrentDomain.GetAssemblies()); var visited = new HashSet<string>(); var loaded = new HashSet<string>(roots.Select(x => x.FullName)); while (roots.Any()) { var asm = roots.Pop(); if (visited.Contains(asm.FullName)) continue; if (!loaded.Contains(asm.FullName)) yield return asm; visited.Add(asm.FullName); foreach (var refAsm in asm.GetReferencedAssemblies() .Where(x => !visited.Contains(x.FullName)) .Where(x => !loaded.Contains(x.FullName)) .Select(x => GetReflectionOnlyAssembly(x.FullName)) .Where(x => x != null)) roots.Push(refAsm); } } /// <summary> /// Finds the type within assembly. /// </summary> private static Type FindType(Assembly asm, string typeName, IBinaryNameMapper mapper) { if (mapper == null) { return asm.GetType(typeName); } return GetAssemblyTypesSafe(asm).FirstOrDefault(x => mapper.GetTypeName(x.FullName) == typeName); } /// <summary> /// Safely gets all assembly types. /// </summary> private static IEnumerable<Type> GetAssemblyTypesSafe(Assembly asm) { try { return asm.GetTypes(); } catch (ReflectionTypeLoadException ex) { // Handle the situation where some assembly dependencies are not available. return ex.Types.Where(x => x != null); } } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class ClassDefinition : TypeDefinition { [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public ClassDefinition CloneNode() { return (ClassDefinition)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public ClassDefinition CleanClone() { return (ClassDefinition)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.ClassDefinition; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnClassDefinition(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( ClassDefinition)node; if (_modifiers != other._modifiers) return NoMatch("ClassDefinition._modifiers"); if (_name != other._name) return NoMatch("ClassDefinition._name"); if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("ClassDefinition._attributes"); if (!Node.AllMatch(_members, other._members)) return NoMatch("ClassDefinition._members"); if (!Node.AllMatch(_baseTypes, other._baseTypes)) return NoMatch("ClassDefinition._baseTypes"); if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("ClassDefinition._genericParameters"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_attributes != null) { Attribute item = existing as Attribute; if (null != item) { Attribute newItem = (Attribute)newNode; if (_attributes.Replace(item, newItem)) { return true; } } } if (_members != null) { TypeMember item = existing as TypeMember; if (null != item) { TypeMember newItem = (TypeMember)newNode; if (_members.Replace(item, newItem)) { return true; } } } if (_baseTypes != null) { TypeReference item = existing as TypeReference; if (null != item) { TypeReference newItem = (TypeReference)newNode; if (_baseTypes.Replace(item, newItem)) { return true; } } } if (_genericParameters != null) { GenericParameterDeclaration item = existing as GenericParameterDeclaration; if (null != item) { GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode; if (_genericParameters.Replace(item, newItem)) { return true; } } } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { ClassDefinition clone = (ClassDefinition)FormatterServices.GetUninitializedObject(typeof(ClassDefinition)); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); clone._modifiers = _modifiers; clone._name = _name; if (null != _attributes) { clone._attributes = _attributes.Clone() as AttributeCollection; clone._attributes.InitializeParent(clone); } if (null != _members) { clone._members = _members.Clone() as TypeMemberCollection; clone._members.InitializeParent(clone); } if (null != _baseTypes) { clone._baseTypes = _baseTypes.Clone() as TypeReferenceCollection; clone._baseTypes.InitializeParent(clone); } if (null != _genericParameters) { clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection; clone._genericParameters.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _attributes) { _attributes.ClearTypeSystemBindings(); } if (null != _members) { _members.ClearTypeSystemBindings(); } if (null != _baseTypes) { _baseTypes.ClearTypeSystemBindings(); } if (null != _genericParameters) { _genericParameters.ClearTypeSystemBindings(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using JoinRpg.Data.Interfaces; using JoinRpg.Domain; using JoinRpg.Portal.Infrastructure.Authorization; using JoinRpg.Services.Interfaces; using JoinRpg.Services.Interfaces.Projects; using JoinRpg.Web.Models; using JoinRpg.Web.Models.Accommodation; using Microsoft.AspNetCore.Mvc; namespace JoinRpg.Portal.Controllers { [MasterAuthorize()] [Route("{projectId}/rooms/[action]")] public class AccommodationTypeController : Common.ControllerGameBase { private IAccommodationRepository AccommodationRepository { get; } private readonly IAccommodationService _accommodationService; public AccommodationTypeController( IProjectRepository projectRepository, IProjectService projectService, IAccommodationService accommodationService, IAccommodationRepository accommodationRepository, IUserRepository userRepository) : base(projectRepository, projectService, userRepository) { AccommodationRepository = accommodationRepository; _accommodationService = accommodationService; } /// <summary> /// Shows list of registered room types /// </summary> [HttpGet("~/{projectId}/rooms/")] public async Task<ActionResult> Index(int projectId) { var project = await ProjectRepository.GetProjectWithDetailsAsync(projectId); if (project == null) { return NotFound($"Project {projectId} not found"); } if (!project.Details.EnableAccommodation) { return RedirectToAction("Edit", "Game"); } return View(new AccommodationListViewModel(project, await AccommodationRepository.GetRoomTypesForProject(projectId), CurrentUserId)); } /// <summary> /// Shows "Add room type" form /// </summary> [MasterAuthorize(Permission.CanManageAccommodation)] [HttpGet] public async Task<ActionResult> AddRoomType(int projectId) { return View(new RoomTypeViewModel( await ProjectRepository.GetProjectAsync(projectId), CurrentUserId)); } /// <summary> /// Shows "Edit room type" form /// </summary> [HttpGet("~/{projectId}/rooms/{roomTypeId}/edit")] public async Task<ActionResult> EditRoomType(int projectId, int roomTypeId) { var entity = await _accommodationService.GetRoomTypeAsync(roomTypeId).ConfigureAwait(false); if (entity == null || entity.ProjectId != projectId) { return Forbid(); } return View(new RoomTypeViewModel(entity, CurrentUserId)); } /// <summary> /// Shows "Edit room type" form /// </summary> [MasterAuthorize(Permission.CanSetPlayersAccommodations)] [HttpGet("~/{projectId}/rooms/{roomTypeId}/details")] public async Task<ActionResult> EditRoomTypeRooms(int projectId, int roomTypeId) { var entity = await _accommodationService.GetRoomTypeAsync(roomTypeId); if (entity == null || entity.ProjectId != projectId) { return Forbid(); } return View(new RoomTypeViewModel(entity, CurrentUserId)); } /// <summary> /// Saves room type. /// If data are valid, redirects to Index /// If not, returns to edit mode /// </summary> [MasterAuthorize(Permission.CanManageAccommodation)] [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> SaveRoomType(RoomTypeViewModel model) { if (!ModelState.IsValid) { if (model.Id == 0) { return View("AddRoomType", model); } return View("EditRoomType", model); } _ = await _accommodationService.SaveRoomTypeAsync(model.ToEntity()).ConfigureAwait(false); return RedirectToAction("Index", new { projectId = model.ProjectId }); } /// <summary> /// Removes room type /// </summary> [MasterAuthorize(Permission.CanManageAccommodation)] [HttpGet] public async Task<ActionResult> DeleteRoomType(int roomTypeId, int projectId) { await _accommodationService.RemoveRoomType(roomTypeId).ConfigureAwait(false); return RedirectToAction("Index", new { ProjectId = projectId }); } [MasterAuthorize(Permission.CanSetPlayersAccommodations)] [HttpPost("~/{projectId}/rooms/occupyroom")] public async Task<ActionResult> OccupyRoom(int projectId, int roomTypeId, int room, string reqId) { try { IReadOnlyCollection<int> ids = reqId.Split(',') .Select(s => int.TryParse(s, out var val) ? val : 0) .Where(val => val > 0) .ToList(); if (ids.Count > 0) { await _accommodationService.OccupyRoom(new OccupyRequest() { AccommodationRequestIds = ids, ProjectId = projectId, RoomId = room, }); return Ok(); } } catch (Exception e) when (e is ArgumentException || e is JoinRpgEntityNotFoundException) { } catch { return StatusCode(500); } return BadRequest(); } [MasterAuthorize(Permission.CanSetPlayersAccommodations)] [HttpGet] public async Task<ActionResult> OccupyAll(int projectId) { var project = await ProjectRepository.GetProjectWithDetailsAsync(projectId); if (project == null) { return NotFound($"Project {projectId} not found"); } if (!project.Details.EnableAccommodation) { return RedirectToAction("Edit", "Game"); } //TODO: Implement mass occupation return RedirectToAction("Index"); } [MasterAuthorize(Permission.CanSetPlayersAccommodations)] [HttpGet] public async Task<ActionResult> UnOccupyAll(int projectId) { var project = await ProjectRepository.GetProjectWithDetailsAsync(projectId); if (project == null) { return NotFound($"Project {projectId} not found"); } if (!project.Details.EnableAccommodation) { return RedirectToAction("Edit", "Game"); } await _accommodationService.UnOccupyAll(projectId); return RedirectToAction("Index"); } [MasterAuthorize(Permission.CanSetPlayersAccommodations)] [HttpPost("~/{projectId}/rooms/unoccupyroom")] public async Task<ActionResult> UnOccupyRoom(int projectId, int roomTypeId, int room, int reqId) { try { await _accommodationService.UnOccupyRoom(new UnOccupyRequest() { ProjectId = projectId, AccommodationRequestId = reqId, }); return Ok(); } catch (Exception e) when (e is ArgumentException || e is JoinRpgEntityNotFoundException) { } catch { return StatusCode(500); } return BadRequest(); } [MasterAuthorize(Permission.CanSetPlayersAccommodations)] [HttpGet] public async Task<ActionResult> UnOccupyRoom(int projectId, int roomTypeId) { try { await _accommodationService.UnOccupyRoomType(projectId, roomTypeId); return RedirectToAction("EditRoomTypeRooms", "AccommodationType", new { ProjectId = projectId, RoomTypeId = roomTypeId }); } catch (Exception e) when (e is ArgumentException || e is JoinRpgEntityNotFoundException) { } catch { return StatusCode(500); } return BadRequest(); } /// <summary> /// Removes room /// </summary> [MasterAuthorize(Permission.CanManageAccommodation)] [HttpDelete] public async Task<ActionResult> DeleteRoom(int projectId, int roomTypeId, int roomId) { try { await _accommodationService.DeleteRoom(roomId, projectId, roomTypeId).ConfigureAwait(false); return Ok(); } catch (Exception e) when (e is ArgumentException || e is JoinRpgEntityNotFoundException) { } catch { return StatusCode(500); } return BadRequest(); } [MasterAuthorize(Permission.CanManageAccommodation)] [HttpPost("~/{projectId}/rooms/addroom")] public async Task<ActionResult> AddRoom(int projectId, int roomTypeId, string name) { try { //TODO: Implement room names checking //TODO: Implement new rooms HTML returning _ = await _accommodationService.AddRooms(projectId, roomTypeId, name); return StatusCode(201); } catch (Exception e) when (e is ArgumentException || e is JoinRpgEntityNotFoundException) { } catch { return StatusCode(500); } return BadRequest(); } /// <summary> /// Applies new name to a room or adds a new room(s) /// </summary> [MasterAuthorize(Permission.CanManageAccommodation)] [HttpPost("~/{projectId}/rooms/editroom")] public async Task<ActionResult> EditRoom(int projectId, int roomTypeId, string room, string name) { try { if (int.TryParse(room, out var roomId)) { await _accommodationService.EditRoom(roomId, name, projectId, roomTypeId); return Ok(); } } catch (Exception e) when (e is ArgumentException || e is JoinRpgEntityNotFoundException) { } catch { return StatusCode(500); } return BadRequest(); } } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Dialog; using System.Web; #if __UNIFIED__ using Foundation; using UIKit; using CoreLocation; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreLocation; using System.Drawing; using CGRect = global::System.Drawing.RectangleF; using CGSize = global::System.Drawing.SizeF; using CGPoint = global::System.Drawing.PointF; using nfloat = global::System.Single; using nint = global::System.Int32; using nuint = global::System.UInt32; #endif using Facebook.CoreKit; using Facebook.LoginKit; using Facebook.ShareKit; namespace FacebookiOSSample { public partial class DVCActions : DialogViewController, ISharingDelegate, IAppInviteDialogDelegate { ProfilePictureView pictureView; bool isHelloPosted = false; string helloId = null; bool isXamarinShared = false; string sharedId = null; // So you can share your Facebook app, you need to create an AppLink: // https://developers.facebook.com/docs/app-invites/ios#app_links NSUrl appLinkUrl = new NSUrl ("https://fb.me/1057737077589334"); NSUrl previewImageUrl = new NSUrl ("http://colegiokolbe.com/wp-content/uploads/2014/09/facebook.png"); public DVCActions () : base (UITableViewStyle.Grouped, null, true) { pictureView = new ProfilePictureView (new CGRect (120, 0, 80, 80)); // Create menu options with Monotouch.Dialog Root = new RootElement ("Menu") { new Section (){ new UIViewElement ("", pictureView, true) { Flags = UIViewElement.CellFlags.DisableSelection | UIViewElement.CellFlags.Transparent, } }, new Section () { new StringElement (Profile.CurrentProfile.Name) { Alignment = UITextAlignment.Center } }, new Section ("Actions") { new CustomStringElement ("Share Xamarin.com", ShareUrl) { Alignment = UITextAlignment.Center, Value = "ShareDialog Sample" }, new CustomStringElement ("Delete Shared Xamarin.com", DeleteSharedPost, 13) { Alignment = UITextAlignment.Center, Value = "GraphRequest Sample" }, new CustomStringElement ("Post \"Hello\"", PostHello) { Alignment = UITextAlignment.Center, Value = "GraphRequest Sample" }, new CustomStringElement ("Delete \"Hello\"", DeleteHelloPost) { Alignment = UITextAlignment.Center, Value = "GraphRequest Sample" }, new CustomStringElement ("Invite some friends", InviteFriends) { Alignment = UITextAlignment.Center, Value = "AppInviteDialog Sample" }, } }; } // Share a Xamarin.com link into user wall void ShareUrl () { // Create the content of what will be shared var content = new ShareLinkContent { ContentTitle = "Xamarin - cross platform that works", ContentDescription = "Create iOS, Android, Mac and Windows apps in C#" }; content.SetContentUrl (new NSUrl ("https://xamarin.com")); // Show your share post, automatically chooses the best way to share ShareDialog.Show (this, content, this); } // Delete the last Xamarin.com shared void DeleteSharedPost () { if (!isXamarinShared) { new UIAlertView ("Error", "Please Share \"Xamarin.com\" to your wall first", null, "Ok", null).Show(); return; } // Use GraphRequest to delete the last shared post var request = new GraphRequest (sharedId, null, AccessToken.CurrentAccessToken.TokenString, null, "DELETE"); var requestConnection = new GraphRequestConnection (); // Handle the result of the request requestConnection.AddRequest (request, (connection, result, error) => { if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } sharedId = ""; new UIAlertView ("Success!!", "Deleted your last share from your wall", null, "Ok", null).Show (); isXamarinShared = false; }); // Start all your request that you have added requestConnection.Start (); } // Post a "Hello!" into user wall void PostHello () { if (isHelloPosted) { InvokeOnMainThread (() => new UIAlertView ("Error", "Hello already posted on your wall", null, "Ok", null).Show ()); return; } // Verify if you have permissions to post into user wall, // if not, ask to user if he/she wants to let your app post thing for them if (!AccessToken.CurrentAccessToken.Permissions.Contains ("publish_actions")) { var alertView = new UIAlertView ("Post Hello", "Would you like to let this app to post a \"Hello\" for you?", null, "Maybe later", new [] { "Ok" }); alertView.Clicked += (sender, e) => { if (e.ButtonIndex == 1) return; // If they let you post thing, ask a new loggin with publish permissions var login = new LoginManager (); login.LogInWithPublishPermissions (new [] { "publish_actions" }, (result, error) => { if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } PostHello (); }); }; alertView.Show (); } else { // Once you have the permissions, you can publish into user wall var request = new GraphRequest ("me/feed", new NSDictionary ("message", "Hello!"), AccessToken.CurrentAccessToken.TokenString, null, "POST"); var requestConnection = new GraphRequestConnection (); // Handle the result of the request requestConnection.AddRequest (request, (connection, result, error) => { if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } helloId = (result as NSDictionary)["id"].ToString (); new UIAlertView ("Success!!", "Posted Hello in your wall, MsgId: " + helloId, null, "Ok", null).Show (); isHelloPosted = true; }); requestConnection.Start (); } } // Delete the "Hello!" post from user wall void DeleteHelloPost () { if (!isHelloPosted) { new UIAlertView ("Error", "Please Post \"Hello\" to your wall first", null, "Ok", null).Show(); return; } // Use GraphRequest to delete the Hello! post var request = new GraphRequest (helloId, null, AccessToken.CurrentAccessToken.TokenString, null, "DELETE"); var requestConnection = new GraphRequestConnection (); // Handle the result of the request requestConnection.AddRequest (request, (connection, result, error) => { if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } helloId = ""; new UIAlertView ("Success", "Deleted Hello from your wall", null, "Ok", null).Show (); isHelloPosted = false; }); requestConnection.Start (); } // Invite user's friends to use your Facebook app void InviteFriends () { var content = new AppInviteContent (appLinkUrl); content.PreviewImageURL = previewImageUrl; AppInviteDialog.Show (content, this); } #region ISharingDelegate Implement public void DidComplete (ISharing sharer, NSDictionary results) { if (results.ContainsKey (new NSString ("postId"))) { sharedId = results ["postId"].ToString (); new UIAlertView ("Success!!", "Successfully posted to Facebook!", null, "Ok", null).Show (); isXamarinShared = true; } } public void DidFail (ISharing sharer, NSError error) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); } public void DidCancel (ISharing sharer) { new UIAlertView ("Cancelled", "The share post was cancelled", null, "Ok", null).Show (); } #endregion #region IAppInviteDialogDelegate implement public void DidComplete (AppInviteDialog appInviteDialog, NSDictionary results) { Console.WriteLine (results); if (results["completionGesture"] != null && results["completionGesture"].ToString () != "cancel") new UIAlertView ("Success!!", "Successfully invited to some friends to use your app!", null, "Ok", null).Show (); } public void DidFail (AppInviteDialog appInviteDialog, NSError error) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// The configuration for compute nodes in a pool based on the Azure Virtual Machines infrastructure. /// </summary> public partial class VirtualMachineConfiguration : ITransportObjectProvider<Models.VirtualMachineConfiguration>, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<ContainerConfiguration> ContainerConfigurationProperty; public readonly PropertyAccessor<IList<DataDisk>> DataDisksProperty; public readonly PropertyAccessor<DiskEncryptionConfiguration> DiskEncryptionConfigurationProperty; public readonly PropertyAccessor<IList<VMExtension>> ExtensionsProperty; public readonly PropertyAccessor<ImageReference> ImageReferenceProperty; public readonly PropertyAccessor<string> LicenseTypeProperty; public readonly PropertyAccessor<string> NodeAgentSkuIdProperty; public readonly PropertyAccessor<NodePlacementConfiguration> NodePlacementConfigurationProperty; public readonly PropertyAccessor<OSDisk> OSDiskProperty; public readonly PropertyAccessor<WindowsConfiguration> WindowsConfigurationProperty; public PropertyContainer() : base(BindingState.Unbound) { this.ContainerConfigurationProperty = this.CreatePropertyAccessor<ContainerConfiguration>(nameof(ContainerConfiguration), BindingAccess.Read | BindingAccess.Write); this.DataDisksProperty = this.CreatePropertyAccessor<IList<DataDisk>>(nameof(DataDisks), BindingAccess.Read | BindingAccess.Write); this.DiskEncryptionConfigurationProperty = this.CreatePropertyAccessor<DiskEncryptionConfiguration>(nameof(DiskEncryptionConfiguration), BindingAccess.Read | BindingAccess.Write); this.ExtensionsProperty = this.CreatePropertyAccessor<IList<VMExtension>>(nameof(Extensions), BindingAccess.Read | BindingAccess.Write); this.ImageReferenceProperty = this.CreatePropertyAccessor<ImageReference>(nameof(ImageReference), BindingAccess.Read | BindingAccess.Write); this.LicenseTypeProperty = this.CreatePropertyAccessor<string>(nameof(LicenseType), BindingAccess.Read | BindingAccess.Write); this.NodeAgentSkuIdProperty = this.CreatePropertyAccessor<string>(nameof(NodeAgentSkuId), BindingAccess.Read | BindingAccess.Write); this.NodePlacementConfigurationProperty = this.CreatePropertyAccessor<NodePlacementConfiguration>(nameof(NodePlacementConfiguration), BindingAccess.Read | BindingAccess.Write); this.OSDiskProperty = this.CreatePropertyAccessor<OSDisk>(nameof(OSDisk), BindingAccess.Read | BindingAccess.Write); this.WindowsConfigurationProperty = this.CreatePropertyAccessor<WindowsConfiguration>(nameof(WindowsConfiguration), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.VirtualMachineConfiguration protocolObject) : base(BindingState.Bound) { this.ContainerConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ContainerConfiguration, o => new ContainerConfiguration(o)), nameof(ContainerConfiguration), BindingAccess.Read | BindingAccess.Write); this.DataDisksProperty = this.CreatePropertyAccessor( DataDisk.ConvertFromProtocolCollection(protocolObject.DataDisks), nameof(DataDisks), BindingAccess.Read | BindingAccess.Write); this.DiskEncryptionConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.DiskEncryptionConfiguration, o => new DiskEncryptionConfiguration(o)), nameof(DiskEncryptionConfiguration), BindingAccess.Read | BindingAccess.Write); this.ExtensionsProperty = this.CreatePropertyAccessor( VMExtension.ConvertFromProtocolCollection(protocolObject.Extensions), nameof(Extensions), BindingAccess.Read | BindingAccess.Write); this.ImageReferenceProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ImageReference, o => new ImageReference(o)), nameof(ImageReference), BindingAccess.Read | BindingAccess.Write); this.LicenseTypeProperty = this.CreatePropertyAccessor( protocolObject.LicenseType, nameof(LicenseType), BindingAccess.Read | BindingAccess.Write); this.NodeAgentSkuIdProperty = this.CreatePropertyAccessor( protocolObject.NodeAgentSKUId, nameof(NodeAgentSkuId), BindingAccess.Read | BindingAccess.Write); this.NodePlacementConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NodePlacementConfiguration, o => new NodePlacementConfiguration(o)), nameof(NodePlacementConfiguration), BindingAccess.Read | BindingAccess.Write); this.OSDiskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.OsDisk, o => new OSDisk(o)), nameof(OSDisk), BindingAccess.Read | BindingAccess.Write); this.WindowsConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.WindowsConfiguration, o => new WindowsConfiguration(o)), nameof(WindowsConfiguration), BindingAccess.Read | BindingAccess.Write); } } private readonly PropertyContainer propertyContainer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="VirtualMachineConfiguration"/> class. /// </summary> /// <param name='imageReference'>A reference to the Azure Virtual Machines Marketplace Image or the custom Virtual Machine Image to use.</param> /// <param name='nodeAgentSkuId'>The SKU of Batch Node Agent to be provisioned on the compute node.</param> public VirtualMachineConfiguration( ImageReference imageReference, string nodeAgentSkuId) { this.propertyContainer = new PropertyContainer(); this.ImageReference = imageReference; this.NodeAgentSkuId = nodeAgentSkuId; } /// <summary> /// Default constructor to support mocking the <see cref="VirtualMachineConfiguration"/> class. /// </summary> protected VirtualMachineConfiguration() { this.propertyContainer = new PropertyContainer(); } internal VirtualMachineConfiguration(Models.VirtualMachineConfiguration protocolObject) { this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region VirtualMachineConfiguration /// <summary> /// Gets or sets the container configuration for the pool. /// </summary> /// <remarks> /// If specified, setup is performed on each node in the pool to allow tasks to run in containers. All regular tasks /// and job manager tasks run on this pool must specify <see cref="TaskContainerSettings" />, and all other tasks /// may specify it. /// </remarks> public ContainerConfiguration ContainerConfiguration { get { return this.propertyContainer.ContainerConfigurationProperty.Value; } set { this.propertyContainer.ContainerConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the configuration for data disks attached to the Compute Nodes in the pool. /// </summary> /// <remarks> /// This property must be specified if the Compute Nodes in the pool need to have empty data disks attached to them. /// This cannot be updated. /// </remarks> public IList<DataDisk> DataDisks { get { return this.propertyContainer.DataDisksProperty.Value; } set { this.propertyContainer.DataDisksProperty.Value = ConcurrentChangeTrackedModifiableList<DataDisk>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the disk encryption configuration for the pool. /// </summary> /// <remarks> /// If specified, encryption is performed on each node in the pool during node provisioning. /// </remarks> public DiskEncryptionConfiguration DiskEncryptionConfiguration { get { return this.propertyContainer.DiskEncryptionConfigurationProperty.Value; } set { this.propertyContainer.DiskEncryptionConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the virtual machine extension for the pool. /// </summary> /// <remarks> /// If specified, the extensions mentioned in this configuration will be installed on each node. /// </remarks> public IList<VMExtension> Extensions { get { return this.propertyContainer.ExtensionsProperty.Value; } set { this.propertyContainer.ExtensionsProperty.Value = ConcurrentChangeTrackedModifiableList<VMExtension>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets a reference to the Azure Virtual Machines Marketplace Image or the custom Virtual Machine Image /// to use. /// </summary> public ImageReference ImageReference { get { return this.propertyContainer.ImageReferenceProperty.Value; } set { this.propertyContainer.ImageReferenceProperty.Value = value; } } /// <summary> /// Gets or sets the type of on-premises license to be used when deploying the operating system. /// </summary> /// <remarks> /// This only applies to images that contain the Windows operating system, and should only be used when you hold /// valid on-premises licenses for the nodes which will be deployed. If omitted, no on-premises licensing discount /// is applied. Values are: 'Windows_Server' - The on-premises license is for Windows Server. 'Windows_Client' - /// The on-premises license is for Windows Client. /// </remarks> public string LicenseType { get { return this.propertyContainer.LicenseTypeProperty.Value; } set { this.propertyContainer.LicenseTypeProperty.Value = value; } } /// <summary> /// Gets or sets the SKU of Batch Node Agent to be provisioned on the compute node. /// </summary> /// <remarks> /// The Batch node agent is a program that runs on each node in the pool, and provides the command-and-control interface /// between the node and the Batch service. There are different implementations of the node agent, known as SKUs, /// for different operating systems. /// </remarks> public string NodeAgentSkuId { get { return this.propertyContainer.NodeAgentSkuIdProperty.Value; } set { this.propertyContainer.NodeAgentSkuIdProperty.Value = value; } } /// <summary> /// Gets or sets the node placement configuration for the pool. /// </summary> /// <remarks> /// This configuration will specify rules on how nodes in the pool will be physically allocated. /// </remarks> public NodePlacementConfiguration NodePlacementConfiguration { get { return this.propertyContainer.NodePlacementConfigurationProperty.Value; } set { this.propertyContainer.NodePlacementConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets settings for the operating system disk of the Virtual Machine. /// </summary> public OSDisk OSDisk { get { return this.propertyContainer.OSDiskProperty.Value; } set { this.propertyContainer.OSDiskProperty.Value = value; } } /// <summary> /// Gets or sets windows operating system settings on the Virtual Machine. This property must not be specified if /// the ImageReference property specifies a Linux OS image. /// </summary> public WindowsConfiguration WindowsConfiguration { get { return this.propertyContainer.WindowsConfigurationProperty.Value; } set { this.propertyContainer.WindowsConfigurationProperty.Value = value; } } #endregion // VirtualMachineConfiguration #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.VirtualMachineConfiguration ITransportObjectProvider<Models.VirtualMachineConfiguration>.GetTransportObject() { Models.VirtualMachineConfiguration result = new Models.VirtualMachineConfiguration() { ContainerConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.ContainerConfiguration, (o) => o.GetTransportObject()), DataDisks = UtilitiesInternal.ConvertToProtocolCollection(this.DataDisks), DiskEncryptionConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.DiskEncryptionConfiguration, (o) => o.GetTransportObject()), Extensions = UtilitiesInternal.ConvertToProtocolCollection(this.Extensions), ImageReference = UtilitiesInternal.CreateObjectWithNullCheck(this.ImageReference, (o) => o.GetTransportObject()), LicenseType = this.LicenseType, NodeAgentSKUId = this.NodeAgentSkuId, NodePlacementConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NodePlacementConfiguration, (o) => o.GetTransportObject()), OsDisk = UtilitiesInternal.CreateObjectWithNullCheck(this.OSDisk, (o) => o.GetTransportObject()), WindowsConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.WindowsConfiguration, (o) => o.GetTransportObject()), }; return result; } #endregion // Internal/private methods } }
// QuickGraph Library // // Copyright (c) 2004 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from // the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // QuickGraph Library HomePage: http://www.mbunit.com // Author: Jonathan de Halleux namespace QuickGraph { using System; using System.Xml.Serialization; using QuickGraph.Concepts; using QuickGraph.Concepts.Serialization; /// <summary> /// A graph edge /// </summary> /// <remarks> /// This class represents a directed edge. It links /// a source <seealso cref="Vertex"/> to a target <seealso cref="Vertex"/>. /// /// The source and target vertices can be accessed as properties. /// </remarks> /// <example> /// This sample shows a basic usage of an edge: /// <code> /// Vertex v; // vertex /// foreach(Edge e in v.InEdges) /// { /// Console.WriteLine("{0} -> {1}", /// e.Source.GetHashCode(), /// e.Target.GetHashCode() /// ); /// } /// </code> /// </example> [Serializable] [XmlRoot("edge")] public class Edge : IEdge, IGraphBiSerializable { private int id; private IVertex source; private IVertex target; /// <summary> /// Empty Method. Used for serialization. /// </summary> public Edge() { this.id = -1; this.source = null; this.target = null; } /// <summary> /// Builds an edge from source to target /// </summary> /// <param name="id">unique identification number</param> /// <param name="source">Source vertex</param> /// <param name="target">Target vertex</param> /// <exception cref="ArgumentNullException">Source or Target is null</exception> public Edge(int id, IVertex source, IVertex target) { if (source == null) throw new ArgumentNullException("Source"); if (target == null) throw new ArgumentNullException("Target"); this.id = id; this.source = source; this.target = target; } /// <summary> /// /// </summary> /// <param name="e1"></param> /// <param name="e2"></param> /// <returns></returns> public static bool operator < (Edge e1, Edge e2) { return e1.CompareTo(e2)<0; } /// <summary> /// /// </summary> /// <param name="e1"></param> /// <param name="e2"></param> /// <returns></returns> public static bool operator > (Edge e1, Edge e2) { return e1.CompareTo(e2)>0; } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { return this.CompareTo((Edge)obj)==0; } /// <summary> /// Compares two edges /// </summary> /// <param name="obj">Edge to compare</param> /// <returns></returns> /// <exception cref="ArgumentException">obj is not of type Edge.</exception> public int CompareTo(Edge obj) { if(obj==null) return -1; return ID.CompareTo(obj.ID); } int IComparable.CompareTo(Object obj) { return this.CompareTo((Edge)obj); } /// <summary> /// Converts to string. /// </summary> /// <returns></returns> public override string ToString() { return ID.ToString(); } /// <summary> /// Converts to string by returning the formatted ID /// </summary> /// <param name="provider"></param> /// <returns></returns> public string ToString(IFormatProvider provider) { return ID.ToString(provider); } /// <summary> /// Edge unique identification number /// </summary> [XmlAttribute("edge-id")] public int ID { get { return this.id; } set { this.id = value; } } /// <summary> /// Source vertex /// </summary> [XmlIgnore] public IVertex Source { get { return this.source; } set { if (value == null) throw new ArgumentNullException("source vertex"); this.source = value; } } /// <summary> /// Source vertex id, for serialization /// </summary> [XmlAttribute("source")] public int SourceID { get { return this.source.ID; } set { this.source = new Vertex(value); } } /// <summary> /// Target Vertex /// </summary> [XmlIgnore] public IVertex Target { get { return target; } set { if (value == null) throw new ArgumentNullException("target vertex"); target = value; } } /// <summary> /// Source vertex id, for serialization /// </summary> [XmlAttribute("target")] public int TargetID { get { return this.target.ID; } set { this.target = new Vertex(value); } } /// <summary> /// Hash code, using ID /// </summary> /// <returns></returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Adds nothing to serialization info /// </summary> /// <param name="info">data holder</param> /// <exception cref="ArgumentNullException">info is null</exception> /// <exception cref="ArgumentException">info is not serializing</exception> public virtual void WriteGraphData(IGraphSerializationInfo info) { if (info==null) throw new ArgumentNullException("info"); if (!info.IsSerializing) throw new ArgumentException("not serializing"); } /// <summary> /// Reads no data from serialization info /// </summary> /// <param name="info">data holder</param> /// <exception cref="ArgumentNullException">info is null</exception> /// <exception cref="ArgumentException">info is serializing</exception> public virtual void ReadGraphData(IGraphSerializationInfo info) { if (info==null) throw new ArgumentNullException("info"); if (info.IsSerializing) throw new ArgumentException("serializing"); } } }
using System; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Crypto.Tests { /** * Wrap Test */ [TestFixture] public class AesWrapTest : ITest { public string Name { get { return "AESWrap"; } } private ITestResult wrapTest( int id, byte[] kek, byte[] inBytes, byte[] outBytes) { IWrapper wrapper = new AesWrapEngine(); wrapper.Init(true, new KeyParameter(kek)); try { byte[] cText = wrapper.Wrap(inBytes, 0, inBytes.Length); if (!Arrays.AreEqual(cText, outBytes)) { return new SimpleTestResult(false, Name + ": failed wrap test " + id + " expected " + Hex.ToHexString(outBytes) + " got " + Hex.ToHexString(cText)); } } catch (Exception e) { return new SimpleTestResult(false, Name + ": failed wrap test exception " + e); } wrapper.Init(false, new KeyParameter(kek)); try { byte[] pText = wrapper.Unwrap(outBytes, 0, outBytes.Length); if (!Arrays.AreEqual(pText, inBytes)) { return new SimpleTestResult(false, Name + ": failed unwrap test " + id + " expected " + Hex.ToHexString(inBytes) + " got " + Hex.ToHexString(pText)); } } catch (Exception e) { return new SimpleTestResult(false, Name + ": failed unwrap test exception.", e); } return new SimpleTestResult(true, Name + ": Okay"); } public ITestResult Perform() { byte[] kek1 = Hex.Decode("000102030405060708090a0b0c0d0e0f"); byte[] in1 = Hex.Decode("00112233445566778899aabbccddeeff"); byte[] out1 = Hex.Decode("1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5"); ITestResult result = wrapTest(1, kek1, in1, out1); if (!result.IsSuccessful()) { return result; } byte[] kek2 = Hex.Decode("000102030405060708090a0b0c0d0e0f1011121314151617"); byte[] in2 = Hex.Decode("00112233445566778899aabbccddeeff"); byte[] out2 = Hex.Decode("96778b25ae6ca435f92b5b97c050aed2468ab8a17ad84e5d"); result = wrapTest(2, kek2, in2, out2); if (!result.IsSuccessful()) { return result; } byte[] kek3 = Hex.Decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); byte[] in3 = Hex.Decode("00112233445566778899aabbccddeeff"); byte[] out3 = Hex.Decode("64e8c3f9ce0f5ba263e9777905818a2a93c8191e7d6e8ae7"); result = wrapTest(3, kek3, in3, out3); if (!result.IsSuccessful()) { return result; } byte[] kek4 = Hex.Decode("000102030405060708090a0b0c0d0e0f1011121314151617"); byte[] in4 = Hex.Decode("00112233445566778899aabbccddeeff0001020304050607"); byte[] out4 = Hex.Decode("031d33264e15d33268f24ec260743edce1c6c7ddee725a936ba814915c6762d2"); result = wrapTest(4, kek4, in4, out4); if (!result.IsSuccessful()) { return result; } byte[] kek5 = Hex.Decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); byte[] in5 = Hex.Decode("00112233445566778899aabbccddeeff0001020304050607"); byte[] out5 = Hex.Decode("a8f9bc1612c68b3ff6e6f4fbe30e71e4769c8b80a32cb8958cd5d17d6b254da1"); result = wrapTest(5, kek5, in5, out5); if (!result.IsSuccessful()) { return result; } byte[] kek6 = Hex.Decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); byte[] in6 = Hex.Decode("00112233445566778899aabbccddeeff000102030405060708090a0b0c0d0e0f"); byte[] out6 = Hex.Decode("28c9f404c4b810f4cbccb35cfb87f8263f5786e2d80ed326cbc7f0e71a99f43bfb988b9b7a02dd21"); result = wrapTest(6, kek6, in6, out6); if (!result.IsSuccessful()) { return result; } IWrapper wrapper = new AesWrapEngine(); KeyParameter key = new KeyParameter(new byte[16]); byte[] buf = new byte[16]; try { wrapper.Init(true, key); wrapper.Unwrap(buf, 0, buf.Length); return new SimpleTestResult(false, Name + ": failed unwrap state test."); } catch (InvalidOperationException) { // expected } catch (InvalidCipherTextException e) { return new SimpleTestResult(false, Name + ": unexpected exception: " + e, e); } try { wrapper.Init(false, key); wrapper.Wrap(buf, 0, buf.Length); return new SimpleTestResult(false, Name + ": failed unwrap state test."); } catch (InvalidOperationException) { // expected } // // short test // try { wrapper.Init(false, key); wrapper.Unwrap(buf, 0, buf.Length / 2); return new SimpleTestResult(false, Name + ": failed unwrap short test."); } catch (InvalidCipherTextException) { // expected } try { wrapper.Init(true, key); wrapper.Wrap(buf, 0, 15); return new SimpleTestResult(false, Name + ": failed wrap length test."); } catch (DataLengthException) { // expected } return new SimpleTestResult(true, Name + ": Okay"); } public static void Main( string[] args) { AesWrapTest test = new AesWrapTest(); ITestResult result = test.Perform(); Console.WriteLine(result); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using System; using System.IO; using System.Collections; using System.Windows.Forms; using System.Text; using HtmlHelp.ChmDecoding; using HtmlHelp.Storage; namespace HtmlHelp { /// <summary> /// The class <c>TOCItem</c> implements a toc-entry item /// </summary> public sealed class TOCItem { /// <summary> /// Constant for standard folder (closed) image index (HH2 image list) /// </summary> public const int STD_FOLDER_HH2 = 4; /// <summary> /// Constant for standard folder (opened) image index (HH2 image list) /// </summary> public const int STD_FOLDER_OPEN_HH2 = 6; /// <summary> /// Constant for standard file image index (HH2 image list) /// </summary> public const int STD_FILE_HH2 = 16; /// <summary> /// Constant for standard folder (closed) image index (HH1 image list) /// </summary> public const int STD_FOLDER_HH1 = 0; /// <summary> /// Constant for standard folder (opened) image index (HH1 image list) /// </summary> public const int STD_FOLDER_OPEN_HH1 = 1; /// <summary> /// Constant for standard file image index (HH1 image list) /// </summary> public const int STD_FILE_HH1 = 10; /// <summary> /// Internal flag specifying the data extraction mode used for this item /// </summary> private DataMode _tocMode = DataMode.TextBased; /// <summary> /// Internal member storing the offset (only used in binary tocs) /// </summary> private int _offset = 0; /// <summary> /// Internal member storing the offset of the next item(only used in binary tocs) /// </summary> private int _offsetNext = 0; /// <summary> /// Internal member storing a merge link. /// If the target file is in the merged files list of the CHM, /// this item will be replaced with the target TOC or Topic, if not it will /// be removed from TOC. /// </summary> private string _mergeLink = ""; /// <summary> /// Internal member storing the toc name /// </summary> private string _name = ""; /// <summary> /// Internal member storing the toc loca (content file) /// </summary> private string _local = ""; /// <summary> /// Internal member storing all associated information type strings /// </summary> private ArrayList _infoTypeStrings = new ArrayList(); /// <summary> /// Internal member storing the associated chm file /// </summary> private string _chmFile = ""; /// <summary> /// Internal member storing the image index /// </summary> private int _imageIndex = -1; /// <summary> /// Internal member storing the offset of the associated topic entry (for binary tocs) /// </summary> private int _topicOffset = -1; /// <summary> /// Internal member storing the toc children /// </summary> private ArrayList _children = new ArrayList(); /// <summary> /// Internal member storing the parameter collection /// </summary> private Hashtable _otherParams = new Hashtable(); /// <summary> /// Internal member storing the associated chmfile object /// </summary> private CHMFile _associatedFile = null; /// <summary> /// Parent item /// </summary> private TOCItem _parent=null; /// <summary> /// Constructor of the class used during text-based data extraction /// </summary> /// <param name="name">name of the item</param> /// <param name="local">local content file</param> /// <param name="ImageIndex">image index</param> /// <param name="chmFile">associated chm file</param> public TOCItem(string name, string local, int ImageIndex, string chmFile) { _tocMode = DataMode.TextBased; _name = name; _local = local; _imageIndex = ImageIndex; _chmFile = chmFile; } /// <summary> /// Constructor of the class used during binary data extraction /// </summary> /// <param name="topicOffset">offset of the associated topic entry</param> /// <param name="ImageIndex">image index to use</param> /// <param name="associatedFile">associated chm file</param> public TOCItem(int topicOffset, int ImageIndex, CHMFile associatedFile) { _tocMode = DataMode.Binary; _associatedFile = associatedFile; _chmFile = associatedFile.ChmFilePath; _topicOffset = topicOffset; _imageIndex = ImageIndex; } /// <summary> /// Standard constructor /// </summary> public TOCItem() { } #region Data dumping /// <summary> /// Dump the class data to a binary writer /// </summary> /// <param name="writer">writer to write the data</param> /// <param name="writeFilename">true if the chmfile name should be written</param> internal void Dump(ref BinaryWriter writer, bool writeFilename) { writer.Write((int)_tocMode); writer.Write(_topicOffset); writer.Write(_name); if((_tocMode == DataMode.TextBased)||(_topicOffset<0)) { writer.Write(_local); } writer.Write(_imageIndex); writer.Write(_mergeLink); if(writeFilename) writer.Write(_chmFile); writer.Write(_infoTypeStrings.Count); for(int i=0; i<_infoTypeStrings.Count; i++) writer.Write( (_infoTypeStrings[i]).ToString() ); writer.Write(_children.Count); for(int i=0; i<_children.Count; i++) { TOCItem child = ((TOCItem)(_children[i])); child.Dump(ref writer, writeFilename); } } /// <summary> /// Dump the class data to a binary writer /// </summary> /// <param name="writer">writer to write the data</param> internal void Dump(ref BinaryWriter writer) { Dump(ref writer, false); } /// <summary> /// Reads the object data from a dump store /// </summary> /// <param name="reader">reader to read the data</param> /// <param name="readFilename">true if the chmfile name should be read</param> internal void ReadDump(ref BinaryReader reader, bool readFilename) { int i=0; _tocMode = (DataMode)reader.ReadInt32(); _topicOffset = reader.ReadInt32(); _name = reader.ReadString(); if((_tocMode == DataMode.TextBased)||(_topicOffset<0)) { _local = reader.ReadString(); } _imageIndex = reader.ReadInt32(); _mergeLink = reader.ReadString(); if(readFilename) _chmFile = reader.ReadString(); int nCnt = reader.ReadInt32(); for(i=0; i<nCnt; i++) { string sIT = reader.ReadString(); _infoTypeStrings.Add(sIT); } nCnt = reader.ReadInt32(); if(_associatedFile != null) _chmFile = _associatedFile.ChmFilePath; for(i=0; i<nCnt; i++) { TOCItem child = new TOCItem(); child.AssociatedFile = _associatedFile; child.ReadDump(ref reader, readFilename); if(_associatedFile != null) child.ChmFile = _associatedFile.ChmFilePath; else if(!readFilename) child.ChmFile = _chmFile; child.Parent = this; _children.Add(child); if(child.MergeLink.Length > 0) _associatedFile.MergLinks.Add(child); } } /// <summary> /// Reads the object data from a dump store /// </summary> /// <param name="reader">reader to read the data</param> internal void ReadDump(ref BinaryReader reader) { ReadDump(ref reader, false); } #endregion /// <summary> /// Gets/Sets the data extraction mode with which this item was created. /// </summary> internal DataMode TocMode { get { return _tocMode; } set { _tocMode = value; } } /// <summary> /// Gets/Sets the offset of the associated topic entry /// </summary> internal int TopicOffset { get { return _topicOffset; } set { _topicOffset = value; } } /// <summary> /// Gets/Sets the associated CHMFile instance /// </summary> internal CHMFile AssociatedFile { get { return _associatedFile; } set { _associatedFile = value; } } /// <summary> /// Gets/Sets the offset of the item. /// </summary> /// <remarks>Only used in binary tocs</remarks> internal int Offset { get { return _offset; } set { _offset = value; } } /// <summary> /// Gets/Sets the offset of the next item. /// </summary> /// <remarks>Only used in binary tocs</remarks> internal int OffsetNext { get { return _offsetNext; } set { _offsetNext = value; } } /// <summary> /// Gets the ArrayList which holds all information types/categories this item is associated /// </summary> public ArrayList InfoTypeStrings { get { return _infoTypeStrings; } } /// <summary> /// Gets/Sets the parent of this item /// </summary> public TOCItem Parent { get { return _parent; } set { _parent = value; } } /// <summary> /// Gets/Sets the mergelink for this item. /// <b>You should not set the mergedlink by your own !</b> /// This is only for loading merged CHMs. /// </summary> public string MergeLink { get { return _mergeLink; } set { _mergeLink = value; } } /// <summary> /// Gets/Sets the name of the item /// </summary> public string Name { get { if(_mergeLink.Length > 0) return ""; if(_name.Length <= 0) { if((_tocMode == DataMode.Binary )&&(_associatedFile!=null)) { if( _topicOffset >= 0) { TopicEntry te = (TopicEntry) (_associatedFile.TopicsFile[_topicOffset]); if(te != null) { return te.Title; } } } } return _name; } set { _name = value; } } /// <summary> /// Gets/Sets the local of the item /// </summary> public string Local { get { if(_mergeLink.Length > 0) return ""; if(_local.Length <= 0) { if((_tocMode == DataMode.Binary )&&(_associatedFile!=null)) { if( _topicOffset >= 0) { TopicEntry te = (TopicEntry) (_associatedFile.TopicsFile[_topicOffset]); if(te != null) { return te.Locale; } } } } return _local; } set { _local = value; } } /// <summary> /// Gets/Sets the chm file /// </summary> public string ChmFile { get { if(_associatedFile!=null) return _associatedFile.ChmFilePath; return _chmFile; } set { _chmFile = value; } } /// <summary> /// Gets the url for the webbrowser for this file /// </summary> public string Url { get { string sL = Local; if( (sL.ToLower().IndexOf("http://") >= 0) || (sL.ToLower().IndexOf("https://") >= 0) || (sL.ToLower().IndexOf("mailto:") >= 0) || (sL.ToLower().IndexOf("ftp://") >= 0) ) return sL; return HtmlHelpSystem.UrlPrefix + ChmFile + "::/" + sL; } } /// <summary> /// Gets/Sets the image index of the item /// </summary> /// <remarks>Set this to -1 for a default icon</remarks> public int ImageIndex { get { if( _imageIndex == -1) { int nFolderAdd = 0; if((_associatedFile != null) && (_associatedFile.ImageTypeFolder)) { // get the value which should be added, to display folders instead of books if(HtmlHelpSystem.UseHH2TreePics) nFolderAdd = 8; else nFolderAdd = 4; } if( _children.Count > 0) return (HtmlHelpSystem.UseHH2TreePics ? (STD_FOLDER_HH2+nFolderAdd) : (STD_FOLDER_HH1+nFolderAdd)); return (HtmlHelpSystem.UseHH2TreePics ? STD_FILE_HH2 : STD_FILE_HH1); } return _imageIndex; } set { _imageIndex = value; } } /// <summary> /// Gets/Sets the children of this item. /// </summary> /// <remarks>Each entry in the ArrayList is of type TOCItem</remarks> public ArrayList Children { get { return _children; } set { _children = value; } } /// <summary> /// Gets the internal hashtable storing all params /// </summary> public Hashtable Params { get { return _otherParams; } } /// <summary> /// Gets the text encoding for reading the content file /// </summary> public Encoding TextEncoding { get { if(_associatedFile != null) return _associatedFile.TextEncoding; return Encoding.Default; } } /// <summary> /// Gets the FileObject of the topics' associated content file /// </summary> /// <remarks>If the file can't be opened, the property will return null. Always call Close() method of the file object after finishing reading the file contents !!!</remarks> public FileObject ContentFile { get { if((_associatedFile != null)&&(Local.Length > 0)) { ITStorageWrapper iw = _associatedFile.ChmWrapper; FileObject fileObject = null; fileObject = iw.OpenUCOMStream(null, Local); return fileObject; } return null; } } /// <summary> /// Gets the contents of the topics' associated content file /// </summary> /// <remarks>If the file can't be opened the property will return an emtpy string (same for binary data)</remarks> public string FileContents { get { FileObject fo = ContentFile; if(fo != null) { if(fo.CanRead) { byte[] fileData = new byte [fo.Length]; fo.Read(fileData, 0, (int)fo.Length); fo.Close(); return TextEncoding.GetString(fileData); } } return string.Empty; } } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace JavaScriptInjectionWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1) #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.IO; using Newtonsoft.Json.Utilities; using System.Globalization; namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a JSON object. /// </summary> public class JObject : JContainer, IDictionary<string, JToken>, INotifyPropertyChanged #if !(UNITY_WP8 || UNITY_WP_8_1) && !(UNITY_WINRT && !UNITY_EDITOR) , ICustomTypeDescriptor #endif #if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR)) , ObservableSupport.INotifyPropertyChanging #endif { public class JPropertKeyedCollection : KeyedCollection<string, JToken> { public JPropertKeyedCollection(IEqualityComparer<string> comparer) #if !(UNITY_WEBPLAYER || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE)) : base(comparer) #else : base(comparer, 0) #endif { } protected override string GetKeyForItem(JToken item) { return ((JProperty)item).Name; } protected override void InsertItem(int index, JToken item) { if (Dictionary == null) { base.InsertItem(index, item); } else { // need to override so that the dictionary key is always set rather than added string keyForItem = GetKeyForItem(item); Dictionary[keyForItem] = item; #if !UNITY_WEBPLAYER Items.Insert(index, item); #else base.InsertItem(index, item); #endif } } #if UNITY_WEBPLAYER public void RemoveItemAt(int index) { base.RemoveAt (index); } #endif #if !(UNITY_WEBPLAYER) public new IDictionary<string, JToken> Dictionary { get { return base.Dictionary; } } #else public IDictionary<string, JToken> Dictionary { get { return _dictionary; } } private readonly Dictionary<string, JToken> _dictionary = new Dictionary<string, JToken>(); #endif } private JPropertKeyedCollection _properties = new JPropertKeyedCollection(StringComparer.Ordinal); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _properties; } } /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE)) /// <summary> /// Occurs when a property value is changing. /// </summary> public event ObservableSupport.PropertyChangingEventHandler PropertyChanging; #endif /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class. /// </summary> public JObject() { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class from another <see cref="JObject"/> object. /// </summary> /// <param name="other">A <see cref="JObject"/> object to copy from.</param> public JObject(JObject other) : base(other) { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class with the specified content. /// </summary> /// <param name="content">The contents of the object.</param> public JObject(params object[] content) : this((object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class with the specified content. /// </summary> /// <param name="content">The contents of the object.</param> public JObject(object content) { Add(content); } internal override bool DeepEquals(JToken node) { JObject t = node as JObject; return (t != null && ContentsEqual(t)); } internal override void InsertItem(int index, JToken item) { // don't add comments to JObject, no name to reference comment by if (item != null && item.Type == JTokenType.Comment) return; base.InsertItem(index, item); } internal override void ValidateToken(JToken o, JToken existing) { ValidationUtils.ArgumentNotNull(o, "o"); if (o.Type != JTokenType.Property) throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType())); JProperty newProperty = (JProperty)o; if (existing != null) { JProperty existingProperty = (JProperty)existing; if (newProperty.Name == existingProperty.Name) return; } if (_properties.Dictionary != null && _properties.Dictionary.TryGetValue(newProperty.Name, out existing)) throw new ArgumentException("Can not add property {0} to {1}. Property with the same name already exists on object.".FormatWith(CultureInfo.InvariantCulture, newProperty.Name, GetType())); } internal void InternalPropertyChanged(JProperty childProperty) { OnPropertyChanged(childProperty.Name); #if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR)) OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, IndexOfItem(childProperty))); #endif } internal void InternalPropertyChanging(JProperty childProperty) { #if !UNITY_ANDROID && !(UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR)) OnPropertyChanging(childProperty.Name); #endif } internal override JToken CloneToken() { return new JObject(this); } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { get { return JTokenType.Object; } } /// <summary> /// Gets an <see cref="IEnumerable{JProperty}"/> of this object's properties. /// </summary> /// <returns>An <see cref="IEnumerable{JProperty}"/> of this object's properties.</returns> public IEnumerable<JProperty> Properties() { return ChildrenTokens.Cast<JProperty>(); } /// <summary> /// Gets a <see cref="JProperty"/> the specified name. /// </summary> /// <param name="name">The property name.</param> /// <returns>A <see cref="JProperty"/> with the specified name or null.</returns> public JProperty Property(string name) { if (_properties.Dictionary == null) return null; if (name == null) return null; JToken property; _properties.Dictionary.TryGetValue(name, out property); return (JProperty)property; } /// <summary> /// Gets an <see cref="JEnumerable{JToken}"/> of this object's property values. /// </summary> /// <returns>An <see cref="JEnumerable{JToken}"/> of this object's property values.</returns> public JEnumerable<JToken> PropertyValues() { return new JEnumerable<JToken>(Properties().Select(p => p.Value)); } /// <summary> /// Gets the <see cref="JToken"/> with the specified key. /// </summary> /// <value>The <see cref="JToken"/> with the specified key.</value> public override JToken this[object key] { get { ValidationUtils.ArgumentNotNull(key, "o"); string propertyName = key as string; if (propertyName == null) throw new ArgumentException("Accessed JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); return this[propertyName]; } set { ValidationUtils.ArgumentNotNull(key, "o"); string propertyName = key as string; if (propertyName == null) throw new ArgumentException("Set JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); this[propertyName] = value; } } /// <summary> /// Gets or sets the <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name. /// </summary> /// <value></value> public JToken this[string propertyName] { get { ValidationUtils.ArgumentNotNull(propertyName, "propertyName"); JProperty property = Property(propertyName); return (property != null) ? property.Value : null; } set { JProperty property = Property(propertyName); if (property != null) { property.Value = value; } else { #if !UNITY_ANDROID && !(UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) OnPropertyChanging(propertyName); #endif Add(new JProperty(propertyName, value)); OnPropertyChanged(propertyName); } } } /// <summary> /// Loads an <see cref="JObject"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JObject"/>.</param> /// <returns>A <see cref="JObject"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public static new JObject Load(JsonReader reader) { ValidationUtils.ArgumentNotNull(reader, "reader"); if (reader.TokenType == JsonToken.None) { if (!reader.Read()) throw new Exception("Error reading JObject from JsonReader."); } if (reader.TokenType != JsonToken.StartObject) { throw new Exception( "Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith( CultureInfo.InvariantCulture, reader.TokenType)); } JObject o = new JObject(); o.SetLineInfo(reader as IJsonLineInfo); o.ReadTokenFrom(reader); return o; } /// <summary> /// Load a <see cref="JObject"/> from a string that contains JSON. /// </summary> /// <param name="json">A <see cref="String"/> that contains JSON.</param> /// <returns>A <see cref="JObject"/> populated from the string that contains JSON.</returns> public static new JObject Parse(string json) { JsonReader jsonReader = new JsonTextReader(new StringReader(json)); return Load(jsonReader); } /// <summary> /// Creates a <see cref="JObject"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JObject"/>.</param> /// <returns>A <see cref="JObject"/> with the values of the specified object</returns> public static new JObject FromObject(object o) { return FromObject(o, new JsonSerializer()); } /// <summary> /// Creates a <see cref="JArray"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JArray"/>.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param> /// <returns>A <see cref="JArray"/> with the values of the specified object</returns> public static new JObject FromObject(object o, JsonSerializer jsonSerializer) { JToken token = FromObjectInternal(o, jsonSerializer); if (token != null && token.Type != JTokenType.Object) throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); return (JObject)token; } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartObject(); foreach (JProperty property in ChildrenTokens) { property.WriteTo(writer, converters); } writer.WriteEndObject(); } #region IDictionary<string,JToken> Members /// <summary> /// Adds the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> public void Add(string propertyName, JToken value) { Add(new JProperty(propertyName, value)); } bool IDictionary<string, JToken>.ContainsKey(string key) { if (_properties.Dictionary == null) return false; return _properties.Dictionary.ContainsKey(key); } ICollection<string> IDictionary<string, JToken>.Keys { get { return _properties.Dictionary.Keys; } } /// <summary> /// Removes the property with the specified name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns>true if item was successfully removed; otherwise, false.</returns> public bool Remove(string propertyName) { JProperty property = Property(propertyName); if (property == null) return false; property.Remove(); #if UNITY_WEBPLAYER _properties.Dictionary.Remove (propertyName); #endif return true; } /// <summary> /// Tries the get value. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> /// <returns>true if a value was successfully retrieved; otherwise, false.</returns> public bool TryGetValue(string propertyName, out JToken value) { JProperty property = Property(propertyName); if (property == null) { value = null; return false; } value = property.Value; return true; } ICollection<JToken> IDictionary<string, JToken>.Values { get { return _properties.Dictionary.Values; } } #endregion #region ICollection<KeyValuePair<string,JToken>> Members void ICollection<KeyValuePair<string, JToken>>.Add(KeyValuePair<string, JToken> item) { Add(new JProperty(item.Key, item.Value)); } void ICollection<KeyValuePair<string, JToken>>.Clear() { RemoveAll(); } bool ICollection<KeyValuePair<string, JToken>>.Contains(KeyValuePair<string, JToken> item) { JProperty property = Property(item.Key); if (property == null) return false; return (property.Value == item.Value); } void ICollection<KeyValuePair<string, JToken>>.CopyTo(KeyValuePair<string, JToken>[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0."); if (arrayIndex >= array.Length) throw new ArgumentException("arrayIndex is equal to or greater than the length of array."); if (Count > array.Length - arrayIndex) throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); int index = 0; foreach (JProperty property in ChildrenTokens) { array[arrayIndex + index] = new KeyValuePair<string, JToken>(property.Name, property.Value); index++; } } bool ICollection<KeyValuePair<string, JToken>>.IsReadOnly { get { return false; } } bool ICollection<KeyValuePair<string, JToken>>.Remove(KeyValuePair<string, JToken> item) { if (!((ICollection<KeyValuePair<string, JToken>>)this).Contains(item)) return false; ((IDictionary<string, JToken>)this).Remove(item.Key); return true; } #endregion internal override int GetDeepHashCode() { return ContentsHashCode(); } /// <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 IEnumerator<KeyValuePair<string, JToken>> GetEnumerator() { foreach (JProperty property in ChildrenTokens) { yield return new KeyValuePair<string, JToken>(property.Name, property.Value); } } /// <summary> /// Raises the <see cref="PropertyChanged"/> event with the provided arguments. /// </summary> /// <param name="propertyName">Name of the property.</param> protected virtual void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #if !UNITY_ANDROID && !(UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) /// <summary> /// Raises the <see cref="PropertyChanging"/> event with the provided arguments. /// </summary> /// <param name="propertyName">Name of the property.</param> protected virtual void OnPropertyChanging(string propertyName) { if (PropertyChanging != null) PropertyChanging(this, new ObservableSupport.PropertyChangingEventArgs(propertyName)); } #endif #if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR)) // include custom type descriptor on JObject rather than use a provider because the properties are specific to a type #region ICustomTypeDescriptor /// <summary> /// Returns the properties for this instance of a component. /// </summary> /// <returns> /// A <see cref="T:System.ComponentModel.PropertyDescriptorCollection"/> that represents the properties for this component instance. /// </returns> PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(null); } private static Type GetTokenPropertyType(JToken token) { if (token is JValue) { JValue v = (JValue)token; return (v.Value != null) ? v.Value.GetType() : typeof(object); } return token.GetType(); } /// <summary> /// Returns the properties for this instance of a component using the attribute array as a filter. /// </summary> /// <param name="attributes">An array of type <see cref="T:System.Attribute"/> that is used as a filter.</param> /// <returns> /// A <see cref="T:System.ComponentModel.PropertyDescriptorCollection"/> that represents the filtered properties for this component instance. /// </returns> PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(System.Attribute[] attributes) { PropertyDescriptorCollection descriptors = new PropertyDescriptorCollection(null); foreach (KeyValuePair<string, JToken> propertyValue in this) { descriptors.Add(new JPropertyDescriptor(propertyValue.Key, GetTokenPropertyType(propertyValue.Value))); } return descriptors; } /// <summary> /// Returns a collection of custom attributes for this instance of a component. /// </summary> /// <returns> /// An <see cref="T:System.ComponentModel.AttributeCollection"/> containing the attributes for this object. /// </returns> AttributeCollection ICustomTypeDescriptor.GetAttributes() { return AttributeCollection.Empty; } /// <summary> /// Returns the class name of this instance of a component. /// </summary> /// <returns> /// The class name of the object, or null if the class does not have a name. /// </returns> string ICustomTypeDescriptor.GetClassName() { return null; } /// <summary> /// Returns the name of this instance of a component. /// </summary> /// <returns> /// The name of the object, or null if the object does not have a name. /// </returns> string ICustomTypeDescriptor.GetComponentName() { return null; } /// <summary> /// Returns a type converter for this instance of a component. /// </summary> /// <returns> /// A <see cref="T:System.ComponentModel.TypeConverter"/> that is the converter for this object, or null if there is no <see cref="T:System.ComponentModel.TypeConverter"/> for this object. /// </returns> TypeConverter ICustomTypeDescriptor.GetConverter() { return new TypeConverter(); } /// <summary> /// Returns the default event for this instance of a component. /// </summary> /// <returns> /// An <see cref="T:System.ComponentModel.EventDescriptor"/> that represents the default event for this object, or null if this object does not have events. /// </returns> EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return null; } /// <summary> /// Returns the default property for this instance of a component. /// </summary> /// <returns> /// A <see cref="T:System.ComponentModel.PropertyDescriptor"/> that represents the default property for this object, or null if this object does not have properties. /// </returns> PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return null; } /// <summary> /// Returns an editor of the specified type for this instance of a component. /// </summary> /// <param name="editorBaseType">A <see cref="T:System.Type"/> that represents the editor for this object.</param> /// <returns> /// An <see cref="T:System.Object"/> of the specified type that is the editor for this object, or null if the editor cannot be found. /// </returns> object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return null; } /// <summary> /// Returns the events for this instance of a component using the specified attribute array as a filter. /// </summary> /// <param name="attributes">An array of type <see cref="T:System.Attribute"/> that is used as a filter.</param> /// <returns> /// An <see cref="T:System.ComponentModel.EventDescriptorCollection"/> that represents the filtered events for this component instance. /// </returns> EventDescriptorCollection ICustomTypeDescriptor.GetEvents(System.Attribute[] attributes) { return EventDescriptorCollection.Empty; } /// <summary> /// Returns the events for this instance of a component. /// </summary> /// <returns> /// An <see cref="T:System.ComponentModel.EventDescriptorCollection"/> that represents the events for this component instance. /// </returns> EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return EventDescriptorCollection.Empty; } /// <summary> /// Returns an object that contains the property described by the specified property descriptor. /// </summary> /// <param name="pd">A <see cref="T:System.ComponentModel.PropertyDescriptor"/> that represents the property whose owner is to be found.</param> /// <returns> /// An <see cref="T:System.Object"/> that represents the owner of the specified property. /// </returns> object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return null; } #endregion #endif } } #endif
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Crossroads.Gateway.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.IO; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; namespace YamlDotNet.Serialization { public sealed class Serializer { private readonly IValueSerializer valueSerializer; #region Backwards compatibility private class BackwardsCompatibleConfiguration : IValueSerializer { public IList<IYamlTypeConverter> Converters { get; private set; } private readonly SerializationOptions options; private readonly INamingConvention namingConvention; private readonly ITypeResolver typeResolver; private readonly YamlAttributeOverrides overrides; public BackwardsCompatibleConfiguration(SerializationOptions options, INamingConvention namingConvention, YamlAttributeOverrides overrides) { this.options = options; this.namingConvention = namingConvention ?? new NullNamingConvention(); this.overrides = overrides; Converters = new List<IYamlTypeConverter>(); Converters.Add(new GuidConverter(IsOptionSet(SerializationOptions.JsonCompatible))); typeResolver = IsOptionSet(SerializationOptions.DefaultToStaticType) ? (ITypeResolver)new StaticTypeResolver() : (ITypeResolver)new DynamicTypeResolver(); } public bool IsOptionSet(SerializationOptions option) { return (options & option) != 0; } private IObjectGraphVisitor<IEmitter> CreateEmittingVisitor(IEmitter emitter, IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IObjectDescriptor graph) { IObjectGraphVisitor<IEmitter> emittingVisitor = new EmittingObjectGraphVisitor(eventEmitter); ObjectSerializer nestedObjectSerializer = (v, t) => SerializeValue(emitter, v, t); emittingVisitor = new CustomSerializationObjectGraphVisitor(emittingVisitor, Converters, nestedObjectSerializer); if (!IsOptionSet(SerializationOptions.DisableAliases)) { var anchorAssigner = new AnchorAssigner(Converters); traversalStrategy.Traverse<Nothing>(graph, anchorAssigner, null); emittingVisitor = new AnchorAssigningObjectGraphVisitor(emittingVisitor, eventEmitter, anchorAssigner); } if (!IsOptionSet(SerializationOptions.EmitDefaults)) { emittingVisitor = new DefaultExclusiveObjectGraphVisitor(emittingVisitor); } return emittingVisitor; } private IEventEmitter CreateEventEmitter() { var writer = new WriterEventEmitter(); if (IsOptionSet(SerializationOptions.JsonCompatible)) { return new JsonEventEmitter(writer); } else { return new TypeAssigningEventEmitter(writer, IsOptionSet(SerializationOptions.Roundtrip)); } } private IObjectGraphTraversalStrategy CreateTraversalStrategy() { ITypeInspector typeDescriptor = new ReadablePropertiesTypeInspector(typeResolver); if (IsOptionSet(SerializationOptions.Roundtrip)) { typeDescriptor = new ReadableAndWritablePropertiesTypeInspector(typeDescriptor); } typeDescriptor = new YamlAttributeOverridesInspector(typeDescriptor, overrides); typeDescriptor = new YamlAttributesTypeInspector(typeDescriptor); typeDescriptor = new NamingConventionTypeInspector(typeDescriptor, namingConvention); if (IsOptionSet(SerializationOptions.DefaultToStaticType)) { typeDescriptor = new CachedTypeInspector(typeDescriptor); } if (IsOptionSet(SerializationOptions.Roundtrip)) { return new RoundtripObjectGraphTraversalStrategy(Converters, typeDescriptor, typeResolver, 50); } else { return new FullObjectGraphTraversalStrategy(typeDescriptor, typeResolver, 50, namingConvention); } } public void SerializeValue(IEmitter emitter, object value, Type type) { var graph = type != null ? new ObjectDescriptor(value, type, type) : new ObjectDescriptor(value, value != null ? value.GetType() : typeof(object), typeof(object)); var traversalStrategy = CreateTraversalStrategy(); var emittingVisitor = CreateEmittingVisitor( emitter, traversalStrategy, CreateEventEmitter(), graph ); traversalStrategy.Traverse(graph, emittingVisitor, emitter); } } private readonly BackwardsCompatibleConfiguration backwardsCompatibleConfiguration; private void ThrowUnlessInBackwardsCompatibleMode() { if (backwardsCompatibleConfiguration == null) { throw new InvalidOperationException("This method / property exists for backwards compatibility reasons, but the Serializer was created using the new configuration mechanism. To configure the Serializer, use the SerializerBuilder."); } } /// <summary> /// /// </summary> /// <param name="options">Options that control how the serialization is to be performed.</param> /// <param name="namingConvention">Naming strategy to use for serialized property names</param> /// <param name="overrides">Yaml attribute overrides</param> [Obsolete("Please use SerializerBuilder to customize the Serializer. This constructor will be removed in future releases.")] public Serializer(SerializationOptions options = SerializationOptions.None, INamingConvention namingConvention = null, YamlAttributeOverrides overrides = null) { backwardsCompatibleConfiguration = new BackwardsCompatibleConfiguration(options, namingConvention, overrides); } /// <summary> /// Registers a type converter to be used to serialize and deserialize specific types. /// </summary> [Obsolete("Please use SerializerBuilder to customize the Serializer. This method will be removed in future releases.")] public void RegisterTypeConverter(IYamlTypeConverter converter) { ThrowUnlessInBackwardsCompatibleMode(); backwardsCompatibleConfiguration.Converters.Insert(0, converter); } #endregion /// <summary> /// Initializes a new instance of <see cref="Serializer" /> using the default configuration. /// </summary> /// <remarks> /// To customize the bahavior of the serializer, use <see cref="SerializerBuilder" />. /// </remarks> public Serializer() // TODO: When the backwards compatibility is dropped, uncomment the following line and remove the body of this constructor. //: this(new SerializerBuilder().BuildSerializerParams()) { backwardsCompatibleConfiguration = new BackwardsCompatibleConfiguration(SerializationOptions.None, null, null); } /// <remarks> /// This constructor is private to discourage its use. /// To invoke it, call the <see cref="FromValueSerializer"/> method. /// </remarks> private Serializer(IValueSerializer valueSerializer) { if (valueSerializer == null) { throw new ArgumentNullException("valueSerializer"); } this.valueSerializer = valueSerializer; } /// <summary> /// Creates a new <see cref="Serializer" /> that uses the specified <see cref="IValueSerializer" />. /// This method is available for advanced scenarios. The preferred way to customize the bahavior of the /// deserializer is to use <see cref="SerializerBuilder" />. /// </summary> public static Serializer FromValueSerializer(IValueSerializer valueSerializer) { return new Serializer(valueSerializer); } /// <summary> /// Serializes the specified object. /// </summary> /// <param name="writer">The <see cref="TextWriter" /> where to serialize the object.</param> /// <param name="graph">The object to serialize.</param> public void Serialize(TextWriter writer, object graph) { Serialize(new Emitter(writer), graph); } /// <summary> /// Serializes the specified object into a string. /// </summary> /// <param name="graph">The object to serialize.</param> public string Serialize(object graph) { using (var buffer = new StringWriter()) { Serialize(buffer, graph); return buffer.ToString(); } } /// <summary> /// Serializes the specified object. /// </summary> /// <param name="writer">The <see cref="TextWriter" /> where to serialize the object.</param> /// <param name="graph">The object to serialize.</param> /// <param name="type">The static type of the object to serialize.</param> public void Serialize(TextWriter writer, object graph, Type type) { Serialize(new Emitter(writer), graph, type); } /// <summary> /// Serializes the specified object. /// </summary> /// <param name="emitter">The <see cref="IEmitter" /> where to serialize the object.</param> /// <param name="graph">The object to serialize.</param> public void Serialize(IEmitter emitter, object graph) { if (emitter == null) { throw new ArgumentNullException("emitter"); } EmitDocument(emitter, graph, null); } /// <summary> /// Serializes the specified object. /// </summary> /// <param name="emitter">The <see cref="IEmitter" /> where to serialize the object.</param> /// <param name="graph">The object to serialize.</param> /// <param name="type">The static type of the object to serialize.</param> public void Serialize(IEmitter emitter, object graph, Type type) { if (emitter == null) { throw new ArgumentNullException("emitter"); } if (type == null) { throw new ArgumentNullException("type"); } EmitDocument(emitter, graph, type); } private void EmitDocument(IEmitter emitter, object graph, Type type) { emitter.Emit(new StreamStart()); emitter.Emit(new DocumentStart()); IValueSerializer actualValueSerializer = backwardsCompatibleConfiguration ?? valueSerializer; actualValueSerializer.SerializeValue(emitter, graph, type); emitter.Emit(new DocumentEnd(true)); emitter.Emit(new StreamEnd()); } } }
/* * 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 NUnit.Framework; using Analyzer = Lucene.Net.Analysis.Analyzer; using TokenStream = Lucene.Net.Analysis.TokenStream; using OffsetAttribute = Lucene.Net.Analysis.Tokenattributes.OffsetAttribute; using PositionIncrementAttribute = Lucene.Net.Analysis.Tokenattributes.PositionIncrementAttribute; using TermAttribute = Lucene.Net.Analysis.Tokenattributes.TermAttribute; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using MockRAMDirectory = Lucene.Net.Store.MockRAMDirectory; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Index { [TestFixture] public class TestTermVectorsReader:LuceneTestCase { private void InitBlock() { positions = new int[testTerms.Length][]; offsets = new TermVectorOffsetInfo[testTerms.Length][]; tokens = new TestToken[testTerms.Length * TERM_FREQ]; } //Must be lexicographically sorted, will do in setup, versus trying to maintain here private System.String[] testFields = new System.String[]{"f1", "f2", "f3", "f4"}; private bool[] testFieldsStorePos = new bool[]{true, false, true, false}; private bool[] testFieldsStoreOff = new bool[]{true, false, false, true}; private System.String[] testTerms = new System.String[]{"this", "is", "a", "test"}; private int[][] positions; private TermVectorOffsetInfo[][] offsets; private MockRAMDirectory dir = new MockRAMDirectory(); private System.String seg; private FieldInfos fieldInfos = new FieldInfos(); private static int TERM_FREQ = 3; public TestTermVectorsReader(System.String s):base(s) { InitBlock(); } public TestTermVectorsReader() : base() { InitBlock(); } internal class TestToken : System.IComparable { public TestToken(TestTermVectorsReader enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestTermVectorsReader enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTermVectorsReader enclosingInstance; public TestTermVectorsReader Enclosing_Instance { get { return enclosingInstance; } } internal System.String text; internal int pos; internal int startOffset; internal int endOffset; public virtual int CompareTo(System.Object other) { return pos - ((TestToken) other).pos; } } internal TestToken[] tokens; [SetUp] public override void SetUp() { base.SetUp(); /* for (int i = 0; i < testFields.length; i++) { fieldInfos.add(testFields[i], true, true, testFieldsStorePos[i], testFieldsStoreOff[i]); } */ System.Array.Sort(testTerms); int tokenUpto = 0; for (int i = 0; i < testTerms.Length; i++) { positions[i] = new int[TERM_FREQ]; offsets[i] = new TermVectorOffsetInfo[TERM_FREQ]; // first position must be 0 for (int j = 0; j < TERM_FREQ; j++) { // positions are always sorted in increasing order positions[i][j] = (int) (j * 10 + (new System.Random().NextDouble()) * 10); // offsets are always sorted in increasing order offsets[i][j] = new TermVectorOffsetInfo(j * 10, j * 10 + testTerms[i].Length); TestToken token = tokens[tokenUpto++] = new TestToken(this); token.text = testTerms[i]; token.pos = positions[i][j]; token.startOffset = offsets[i][j].GetStartOffset(); token.endOffset = offsets[i][j].GetEndOffset(); } } System.Array.Sort(tokens); IndexWriter writer = new IndexWriter(dir, new MyAnalyzer(this), true, IndexWriter.MaxFieldLength.LIMITED); writer.SetUseCompoundFile(false); Document doc = new Document(); for (int i = 0; i < testFields.Length; i++) { Field.TermVector tv; if (testFieldsStorePos[i] && testFieldsStoreOff[i]) tv = Field.TermVector.WITH_POSITIONS_OFFSETS; else if (testFieldsStorePos[i] && !testFieldsStoreOff[i]) tv = Field.TermVector.WITH_POSITIONS; else if (!testFieldsStorePos[i] && testFieldsStoreOff[i]) tv = Field.TermVector.WITH_OFFSETS; else tv = Field.TermVector.YES; doc.Add(new Field(testFields[i], "", Field.Store.NO, Field.Index.ANALYZED, tv)); } //Create 5 documents for testing, they all have the same //terms for (int j = 0; j < 5; j++) writer.AddDocument(doc); writer.Flush(); seg = writer.NewestSegment().name; writer.Close(); fieldInfos = new FieldInfos(dir, seg + "." + IndexFileNames.FIELD_INFOS_EXTENSION); } private class MyTokenStream:TokenStream { private void InitBlock(TestTermVectorsReader enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTermVectorsReader enclosingInstance; public TestTermVectorsReader Enclosing_Instance { get { return enclosingInstance; } } internal int tokenUpto; internal TermAttribute termAtt; internal PositionIncrementAttribute posIncrAtt; internal OffsetAttribute offsetAtt; public MyTokenStream(TestTermVectorsReader enclosingInstance) { InitBlock(enclosingInstance); termAtt = (TermAttribute) AddAttribute(typeof(TermAttribute)); posIncrAtt = (PositionIncrementAttribute) AddAttribute(typeof(PositionIncrementAttribute)); offsetAtt = (OffsetAttribute) AddAttribute(typeof(OffsetAttribute)); } public override bool IncrementToken() { if (tokenUpto >= Enclosing_Instance.tokens.Length) return false; else { TestToken testToken = Enclosing_Instance.tokens[tokenUpto++]; ClearAttributes(); termAtt.SetTermBuffer(testToken.text); offsetAtt.SetOffset(testToken.startOffset, testToken.endOffset); if (tokenUpto > 1) { posIncrAtt.SetPositionIncrement(testToken.pos - Enclosing_Instance.tokens[tokenUpto - 2].pos); } else { posIncrAtt.SetPositionIncrement(testToken.pos + 1); } return true; } } } private class MyAnalyzer:Analyzer { public MyAnalyzer(TestTermVectorsReader enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestTermVectorsReader enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTermVectorsReader enclosingInstance; public TestTermVectorsReader Enclosing_Instance { get { return enclosingInstance; } } public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader) { return new MyTokenStream(enclosingInstance); } } [Test] public virtual void Test() { //Check to see the files were created properly in setup Assert.IsTrue(dir.FileExists(seg + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION)); Assert.IsTrue(dir.FileExists(seg + "." + IndexFileNames.VECTORS_INDEX_EXTENSION)); } [Test] public virtual void TestReader() { TermVectorsReader reader = new TermVectorsReader(dir, seg, fieldInfos); Assert.IsTrue(reader != null); for (int j = 0; j < 5; j++) { TermFreqVector vector = reader.Get(j, testFields[0]); Assert.IsTrue(vector != null); System.String[] terms = vector.GetTerms(); Assert.IsTrue(terms != null); Assert.IsTrue(terms.Length == testTerms.Length); for (int i = 0; i < terms.Length; i++) { System.String term = terms[i]; //System.out.println("Term: " + term); Assert.IsTrue(term.Equals(testTerms[i])); } } } [Test] public virtual void TestPositionReader() { TermVectorsReader reader = new TermVectorsReader(dir, seg, fieldInfos); Assert.IsTrue(reader != null); TermPositionVector vector; System.String[] terms; vector = (TermPositionVector) reader.Get(0, testFields[0]); Assert.IsTrue(vector != null); terms = vector.GetTerms(); Assert.IsTrue(terms != null); Assert.IsTrue(terms.Length == testTerms.Length); for (int i = 0; i < terms.Length; i++) { System.String term = terms[i]; //System.out.println("Term: " + term); Assert.IsTrue(term.Equals(testTerms[i])); int[] positions = vector.GetTermPositions(i); Assert.IsTrue(positions != null); Assert.IsTrue(positions.Length == this.positions[i].Length); for (int j = 0; j < positions.Length; j++) { int position = positions[j]; Assert.IsTrue(position == this.positions[i][j]); } TermVectorOffsetInfo[] offset = vector.GetOffsets(i); Assert.IsTrue(offset != null); Assert.IsTrue(offset.Length == this.offsets[i].Length); for (int j = 0; j < offset.Length; j++) { TermVectorOffsetInfo termVectorOffsetInfo = offset[j]; Assert.IsTrue(termVectorOffsetInfo.Equals(offsets[i][j])); } } TermFreqVector freqVector = reader.Get(0, testFields[1]); //no pos, no offset Assert.IsTrue(freqVector != null); Assert.IsTrue(freqVector is TermPositionVector == false); terms = freqVector.GetTerms(); Assert.IsTrue(terms != null); Assert.IsTrue(terms.Length == testTerms.Length); for (int i = 0; i < terms.Length; i++) { System.String term = terms[i]; //System.out.println("Term: " + term); Assert.IsTrue(term.Equals(testTerms[i])); } } [Test] public virtual void TestOffsetReader() { TermVectorsReader reader = new TermVectorsReader(dir, seg, fieldInfos); Assert.IsTrue(reader != null); TermPositionVector vector = (TermPositionVector) reader.Get(0, testFields[0]); Assert.IsTrue(vector != null); System.String[] terms = vector.GetTerms(); Assert.IsTrue(terms != null); Assert.IsTrue(terms.Length == testTerms.Length); for (int i = 0; i < terms.Length; i++) { System.String term = terms[i]; //System.out.println("Term: " + term); Assert.IsTrue(term.Equals(testTerms[i])); int[] positions = vector.GetTermPositions(i); Assert.IsTrue(positions != null); Assert.IsTrue(positions.Length == this.positions[i].Length); for (int j = 0; j < positions.Length; j++) { int position = positions[j]; Assert.IsTrue(position == this.positions[i][j]); } TermVectorOffsetInfo[] offset = vector.GetOffsets(i); Assert.IsTrue(offset != null); Assert.IsTrue(offset.Length == this.offsets[i].Length); for (int j = 0; j < offset.Length; j++) { TermVectorOffsetInfo termVectorOffsetInfo = offset[j]; Assert.IsTrue(termVectorOffsetInfo.Equals(offsets[i][j])); } } } [Test] public virtual void TestMapper() { TermVectorsReader reader = new TermVectorsReader(dir, seg, fieldInfos); Assert.IsTrue(reader != null); SortedTermVectorMapper mapper = new SortedTermVectorMapper(new TermVectorEntryFreqSortedComparator()); reader.Get(0, mapper); System.Collections.Generic.SortedDictionary<Object,Object> set_Renamed = mapper.GetTermVectorEntrySet(); Assert.IsTrue(set_Renamed != null, "set is null and it shouldn't be"); //three fields, 4 terms, all terms are the same Assert.IsTrue(set_Renamed.Count == 4, "set Size: " + set_Renamed.Count + " is not: " + 4); //Check offsets and positions for (System.Collections.IEnumerator iterator = set_Renamed.Keys.GetEnumerator(); iterator.MoveNext(); ) { TermVectorEntry tve = (TermVectorEntry) iterator.Current; Assert.IsTrue(tve != null, "tve is null and it shouldn't be"); Assert.IsTrue(tve.GetOffsets() != null, "tve.getOffsets() is null and it shouldn't be"); Assert.IsTrue(tve.GetPositions() != null, "tve.getPositions() is null and it shouldn't be"); } mapper = new SortedTermVectorMapper(new TermVectorEntryFreqSortedComparator()); reader.Get(1, mapper); set_Renamed = mapper.GetTermVectorEntrySet(); Assert.IsTrue(set_Renamed != null, "set is null and it shouldn't be"); //three fields, 4 terms, all terms are the same Assert.IsTrue(set_Renamed.Count == 4, "set Size: " + set_Renamed.Count + " is not: " + 4); //Should have offsets and positions b/c we are munging all the fields together for (System.Collections.IEnumerator iterator = set_Renamed.Keys.GetEnumerator(); iterator.MoveNext(); ) { TermVectorEntry tve = (TermVectorEntry) iterator.Current; Assert.IsTrue(tve != null, "tve is null and it shouldn't be"); Assert.IsTrue(tve.GetOffsets() != null, "tve.getOffsets() is null and it shouldn't be"); Assert.IsTrue(tve.GetPositions() != null, "tve.getPositions() is null and it shouldn't be"); } FieldSortedTermVectorMapper fsMapper = new FieldSortedTermVectorMapper(new TermVectorEntryFreqSortedComparator()); reader.Get(0, fsMapper); System.Collections.IDictionary map = fsMapper.GetFieldToTerms(); Assert.IsTrue(map.Count == testFields.Length, "map Size: " + map.Count + " is not: " + testFields.Length); for (System.Collections.IEnumerator iterator = new System.Collections.Hashtable(map).GetEnumerator(); iterator.MoveNext(); ) { System.Collections.DictionaryEntry entry = (System.Collections.DictionaryEntry) iterator.Current; System.Collections.Generic.SortedDictionary<Object,Object> sortedSet = (System.Collections.Generic.SortedDictionary<Object,Object>)entry.Value; Assert.IsTrue(sortedSet.Count == 4, "sortedSet Size: " + sortedSet.Count + " is not: " + 4); for (System.Collections.IEnumerator inner = sortedSet.Keys.GetEnumerator(); inner.MoveNext(); ) { TermVectorEntry tve = (TermVectorEntry) inner.Current; Assert.IsTrue(tve != null, "tve is null and it shouldn't be"); //Check offsets and positions. Assert.IsTrue(tve != null, "tve is null and it shouldn't be"); System.String field = tve.GetField(); if (field.Equals(testFields[0])) { //should have offsets Assert.IsTrue(tve.GetOffsets() != null, "tve.getOffsets() is null and it shouldn't be"); Assert.IsTrue(tve.GetPositions() != null, "tve.getPositions() is null and it shouldn't be"); } else if (field.Equals(testFields[1])) { //should not have offsets Assert.IsTrue(tve.GetOffsets() == null, "tve.getOffsets() is not null and it shouldn't be"); Assert.IsTrue(tve.GetPositions() == null, "tve.getPositions() is not null and it shouldn't be"); } } } //Try mapper that ignores offs and positions fsMapper = new FieldSortedTermVectorMapper(true, true, new TermVectorEntryFreqSortedComparator()); reader.Get(0, fsMapper); map = fsMapper.GetFieldToTerms(); Assert.IsTrue(map.Count == testFields.Length, "map Size: " + map.Count + " is not: " + testFields.Length); for (System.Collections.IEnumerator iterator = new System.Collections.Hashtable(map).GetEnumerator(); iterator.MoveNext(); ) { System.Collections.DictionaryEntry entry = (System.Collections.DictionaryEntry) iterator.Current; System.Collections.Generic.SortedDictionary<Object,Object> sortedSet = (System.Collections.Generic.SortedDictionary<Object,Object>)entry.Value; Assert.IsTrue(sortedSet.Count == 4, "sortedSet Size: " + sortedSet.Count + " is not: " + 4); for (System.Collections.IEnumerator inner = sortedSet.Keys.GetEnumerator(); inner.MoveNext(); ) { TermVectorEntry tve = (TermVectorEntry) inner.Current; Assert.IsTrue(tve != null, "tve is null and it shouldn't be"); //Check offsets and positions. Assert.IsTrue(tve != null, "tve is null and it shouldn't be"); System.String field = tve.GetField(); if (field.Equals(testFields[0])) { //should have offsets Assert.IsTrue(tve.GetOffsets() == null, "tve.getOffsets() is null and it shouldn't be"); Assert.IsTrue(tve.GetPositions() == null, "tve.getPositions() is null and it shouldn't be"); } else if (field.Equals(testFields[1])) { //should not have offsets Assert.IsTrue(tve.GetOffsets() == null, "tve.getOffsets() is not null and it shouldn't be"); Assert.IsTrue(tve.GetPositions() == null, "tve.getPositions() is not null and it shouldn't be"); } } } // test setDocumentNumber() IndexReader ir = IndexReader.Open(dir); DocNumAwareMapper docNumAwareMapper = new DocNumAwareMapper(); Assert.AreEqual(- 1, docNumAwareMapper.GetDocumentNumber()); ir.GetTermFreqVector(0, docNumAwareMapper); Assert.AreEqual(0, docNumAwareMapper.GetDocumentNumber()); docNumAwareMapper.SetDocumentNumber(- 1); ir.GetTermFreqVector(1, docNumAwareMapper); Assert.AreEqual(1, docNumAwareMapper.GetDocumentNumber()); docNumAwareMapper.SetDocumentNumber(- 1); ir.GetTermFreqVector(0, "f1", docNumAwareMapper); Assert.AreEqual(0, docNumAwareMapper.GetDocumentNumber()); docNumAwareMapper.SetDocumentNumber(- 1); ir.GetTermFreqVector(1, "f2", docNumAwareMapper); Assert.AreEqual(1, docNumAwareMapper.GetDocumentNumber()); docNumAwareMapper.SetDocumentNumber(- 1); ir.GetTermFreqVector(0, "f1", docNumAwareMapper); Assert.AreEqual(0, docNumAwareMapper.GetDocumentNumber()); ir.Close(); } /// <summary> Make sure exceptions and bad params are handled appropriately</summary> [Test] public virtual void TestBadParams() { try { TermVectorsReader reader = new TermVectorsReader(dir, seg, fieldInfos); Assert.IsTrue(reader != null); //Bad document number, good field number reader.Get(50, testFields[0]); Assert.Fail(); } catch (System.IO.IOException e) { // expected exception } try { TermVectorsReader reader = new TermVectorsReader(dir, seg, fieldInfos); Assert.IsTrue(reader != null); //Bad document number, no field reader.Get(50); Assert.Fail(); } catch (System.IO.IOException e) { // expected exception } try { TermVectorsReader reader = new TermVectorsReader(dir, seg, fieldInfos); Assert.IsTrue(reader != null); //good document number, bad field number TermFreqVector vector = reader.Get(0, "f50"); Assert.IsTrue(vector == null); } catch (System.IO.IOException e) { Assert.Fail(); } } public class DocNumAwareMapper:TermVectorMapper { public DocNumAwareMapper() { } private int documentNumber = - 1; public override void SetExpectations(System.String field, int numTerms, bool storeOffsets, bool storePositions) { if (documentNumber == - 1) { throw new System.SystemException("Documentnumber should be set at this point!"); } } public override void Map(System.String term, int frequency, TermVectorOffsetInfo[] offsets, int[] positions) { if (documentNumber == - 1) { throw new System.SystemException("Documentnumber should be set at this point!"); } } public virtual int GetDocumentNumber() { return documentNumber; } public override void SetDocumentNumber(int documentNumber) { this.documentNumber = documentNumber; } } } }
/* ==================================================================== 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 is1 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 TestCases.HSSF.Model { using System; using System.Collections; using System.IO; using NUnit.Framework; using NPOI.HSSF.Record.Aggregates; using NPOI.HSSF.Record; using NPOI.HSSF.EventModel; using NPOI.HSSF.Model; using NPOI.SS.Util; using TestCases.HSSF.UserModel; using System.Collections.Generic; using NPOI.HSSF.UserModel; using NPOI.SS.Formula; using NPOI.Util; using NPOI.DDF; /** * Unit Test for the Sheet class. * * @author Glen Stampoultzis (glens at apache.org) */ [TestFixture] public class TestSheet { private static Record[] GetSheetRecords(InternalSheet s, int offset) { RecordInspector.RecordCollector rc = new RecordInspector.RecordCollector(); s.VisitContainedRecords(rc, offset); return rc.Records; } private static InternalSheet CreateSheet(ArrayList inRecs) { return InternalSheet.CreateSheet(new RecordStream(inRecs, 0)); } [Test] public void TestCreateSheet() { // Check we're Adding row and cell aggregates ArrayList records = new ArrayList(); records.Add(BOFRecord.CreateSheetBOF()); records.Add(new DimensionsRecord()); records.Add(CreateWindow2Record()); records.Add(new EOFRecord()); InternalSheet sheet = CreateSheet(records); Record[] outRecs = GetSheetRecords(sheet, 0); int pos = 0; Assert.IsTrue(outRecs[pos++] is BOFRecord); Assert.IsTrue(outRecs[pos++] is IndexRecord); Assert.IsTrue(outRecs[pos++] is DimensionsRecord); Assert.IsTrue(outRecs[pos++] is WindowTwoRecord); Assert.IsTrue(outRecs[pos++] is EOFRecord); } private class MergedCellListener:RecordVisitor { private int _count; public MergedCellListener() { _count = 0; } public void VisitRecord(Record r) { if (r is MergeCellsRecord) { _count++; } } public int Count { get { return _count; } } } [Test] public void TestAddMergedRegion() { InternalSheet sheet = InternalSheet.CreateSheet(); int regionsToAdd = 4096; int startRecords = sheet.Records.Count; //simple Test that Adds a load of regions for (int n = 0; n < regionsToAdd; n++) { int index = sheet.AddMergedRegion(0, 0, 1, 1); Assert.AreEqual(index, n, "Merged region index expected to be " + n + " got " + index); } //test all the regions were indeed Added Assert.AreEqual(sheet.NumMergedRegions, regionsToAdd); //test that the regions were spread out over the appropriate number of records MergedCellListener mcListener = new MergedCellListener(); sheet.VisitContainedRecords(mcListener, 0); int recordsAdded = mcListener.Count; int recordsExpected = regionsToAdd / 1027; if ((regionsToAdd % 1027) != 0) recordsExpected++; Assert.AreEqual(recordsAdded, recordsExpected, "The " + regionsToAdd + " merged regions should have been spRead out over " + recordsExpected + " records, not " + recordsAdded); // Check we can't Add one with invalid date try { sheet.AddMergedRegion(10, 10, 9, 12); Assert.Fail("Expected an exception to occur"); } catch (ArgumentException e) { // occurs during successful Test Assert.AreEqual("The 'to' row (9) must not be less than the 'from' row (10)", e.Message); } try { sheet.AddMergedRegion(10, 10, 12, 9); Assert.Fail("Expected an exception to occur"); } catch (ArgumentException e) { // occurs during successful Test Assert.AreEqual("The 'to' col (9) must not be less than the 'from' col (10)", e.Message); } } [Test] public void TestRemoveMergedRegion() { InternalSheet sheet = InternalSheet.CreateSheet(); int regionsToAdd = 4096; for (int n = 0; n < regionsToAdd; n++) sheet.AddMergedRegion(0, 0, 1,1); int nSheetRecords = sheet.Records.Count; //remove a third from the beginning for (int n = 0; n < regionsToAdd / 3; n++) { sheet.RemoveMergedRegion(0); //assert they have been deleted Assert.AreEqual(sheet.NumMergedRegions,regionsToAdd - n - 1, "Num of regions should be " + (regionsToAdd - n - 1) + " not " + sheet.NumMergedRegions); } // merge records are removed from within the MergedCellsTable, // so the sheet record count should not change Assert.AreEqual(nSheetRecords, sheet.Records.Count, "Sheet Records"); } /** * Bug: 22922 (Reported by Xuemin Guan) * * Remove mergedregion Assert.Fails when a sheet loses records after an initial CreateSheet * fills up the records. * */ [Test] public void TestMovingMergedRegion() { ArrayList records = new ArrayList(); CellRangeAddress[] cras = { new CellRangeAddress(0, 1, 0, 2), }; MergeCellsRecord merged = new MergeCellsRecord(cras, 0, cras.Length); records.Add(BOFRecord.CreateSheetBOF()); records.Add(new DimensionsRecord()); records.Add(new RowRecord(0)); records.Add(new RowRecord(1)); records.Add(new RowRecord(2)); records.Add(CreateWindow2Record()); records.Add(EOFRecord.instance); records.Add(merged); InternalSheet sheet = CreateSheet(records); sheet.Records.RemoveAt(0); //stub object to throw off list INDEX operations sheet.RemoveMergedRegion(0); Assert.AreEqual(0, sheet.NumMergedRegions, "Should be no more merged regions"); } public void TestGetMergedRegionAt() { //TODO } public void TestGetNumMergedRegions() { //TODO } private static Record CreateWindow2Record() { WindowTwoRecord result = new WindowTwoRecord(); result.Options=((short)0x6b6); result.TopRow=((short)0); result.LeftCol=((short)0); result.HeaderColor=(0x40); result.PageBreakZoom=((short)0); result.NormalZoom=((short)0); return result; } /** * Makes sure all rows registered for this sheet are aggregated, they were being skipped * */ [Test] public void TestRowAggregation() { ArrayList records = new ArrayList(); records.Add(InternalSheet.CreateBOF()); records.Add(new DimensionsRecord()); records.Add(new RowRecord(0)); records.Add(new RowRecord(1)); FormulaRecord formulaRecord = new FormulaRecord(); formulaRecord.SetCachedResultTypeString(); records.Add(formulaRecord); records.Add(new StringRecord()); records.Add(new RowRecord(2)); records.Add(CreateWindow2Record()); records.Add(EOFRecord.instance); InternalSheet sheet = CreateSheet(records); Assert.IsNotNull(sheet.GetRow(2), "Row [2] was skipped"); } /** * Make sure page break functionality works (in memory) * */ [Test] public void TestRowPageBreaks() { short colFrom = 0; short colTo = 255; InternalSheet worksheet = InternalSheet.CreateSheet(); PageSettingsBlock sheet = worksheet.PageSettings; sheet.SetRowBreak(0, colFrom, colTo); Assert.IsTrue(sheet.IsRowBroken(0), "no row break at 0"); Assert.AreEqual(1, sheet.NumRowBreaks, "1 row break available"); sheet.SetRowBreak(0, colFrom, colTo); sheet.SetRowBreak(0, colFrom, colTo); Assert.IsTrue(sheet.IsRowBroken(0), "no row break at 0"); Assert.AreEqual(1, sheet.NumRowBreaks, "1 row break available"); sheet.SetRowBreak(10, colFrom, colTo); sheet.SetRowBreak(11, colFrom, colTo); Assert.IsTrue(sheet.IsRowBroken(10), "no row break at 10"); Assert.IsTrue(sheet.IsRowBroken(11), "no row break at 11"); Assert.AreEqual(3, sheet.NumRowBreaks, "3 row break available"); bool is10 = false; bool is0 = false; bool is11 = false; int[] rowBreaks = sheet.RowBreaks; for (int i = 0; i < rowBreaks.Length; i++) { int main = rowBreaks[i]; if (main != 0 && main != 10 && main != 11) Assert.Fail("Invalid page break"); if (main == 0) is0 = true; if (main == 10) is10 = true; if (main == 11) is11 = true; } Assert.IsTrue(is0 && is10 && is11, "one of the breaks didnt make it"); sheet.RemoveRowBreak(11); Assert.IsFalse(sheet.IsRowBroken(11), "row should be removed"); sheet.RemoveRowBreak(0); Assert.IsFalse(sheet.IsRowBroken(0), "row should be removed"); sheet.RemoveRowBreak(10); Assert.IsFalse(sheet.IsRowBroken(10), "row should be removed"); Assert.AreEqual(0, sheet.NumRowBreaks, "no more breaks"); } /** * Make sure column pag breaks works properly (in-memory) * */ [Test] public void TestColPageBreaks() { int rowFrom = 0; int rowTo = 65535; InternalSheet worksheet = InternalSheet.CreateSheet(); PageSettingsBlock sheet = worksheet.PageSettings; sheet.SetColumnBreak(0, rowFrom, rowTo); Assert.IsTrue(sheet.IsColumnBroken(0), "no col break at 0"); Assert.AreEqual(1, sheet.NumColumnBreaks, "1 col break available"); sheet.SetColumnBreak(0, rowFrom, rowTo); Assert.IsTrue(sheet.IsColumnBroken(0), "no col break at 0"); Assert.AreEqual(1, sheet.NumColumnBreaks, "1 col break available"); sheet.SetColumnBreak(1, rowFrom, rowTo); sheet.SetColumnBreak(10, rowFrom, rowTo); sheet.SetColumnBreak(15, rowFrom, rowTo); Assert.IsTrue(sheet.IsColumnBroken(1), "no col break at 1"); Assert.IsTrue(sheet.IsColumnBroken(10), "no col break at 10"); Assert.IsTrue(sheet.IsColumnBroken(15), "no col break at 15"); Assert.AreEqual(4, sheet.NumColumnBreaks, "4 col break available"); bool is10 = false; bool is0 = false; bool is1 = false; bool is15 = false; int[] colBreaks = sheet.ColumnBreaks; for (int i = 0; i < colBreaks.Length; i++) { int main = colBreaks[i]; if (main != 0 && main != 1 && main != 10 && main != 15) Assert.Fail("Invalid page break"); if (main == 0) is0 = true; if (main == 1) is1 = true; if (main == 10) is10 = true; if (main == 15) is15 = true; } Assert.IsTrue(is0 && is1 && is10 && is15, "one of the breaks didnt make it"); sheet.RemoveColumnBreak(15); Assert.IsFalse(sheet.IsColumnBroken(15), "column break should not be there"); sheet.RemoveColumnBreak(0); Assert.IsFalse(sheet.IsColumnBroken(0), "column break should not be there"); sheet.RemoveColumnBreak(1); Assert.IsFalse(sheet.IsColumnBroken(1), "column break should not be there"); sheet.RemoveColumnBreak(10); Assert.IsFalse(sheet.IsColumnBroken(10), "column break should not be there"); Assert.AreEqual(0, sheet.NumColumnBreaks, "no more breaks"); } /** * Test newly Added method Sheet.GetXFIndexForColAt(..) * works as designed. */ [Test] public void TestXFIndexForColumn() { short TEST_IDX = 10; short DEFAULT_IDX = 0xF; // 15 short xfindex = short.MinValue; InternalSheet sheet = InternalSheet.CreateSheet(); // without ColumnInfoRecord xfindex = sheet.GetXFIndexForColAt((short)0); Assert.AreEqual(DEFAULT_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)1); Assert.AreEqual(DEFAULT_IDX, xfindex); ColumnInfoRecord nci = new ColumnInfoRecord(); sheet.ColumnInfos.InsertColumn(nci); // single column ColumnInfoRecord nci.FirstColumn = ((short)2); nci.LastColumn = ((short)2); nci.XFIndex = (TEST_IDX); xfindex = sheet.GetXFIndexForColAt((short)0); Assert.AreEqual(DEFAULT_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)1); Assert.AreEqual(DEFAULT_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)2); Assert.AreEqual(TEST_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)3); Assert.AreEqual(DEFAULT_IDX, xfindex); // ten column ColumnInfoRecord nci.FirstColumn = ((short)2); nci.LastColumn = ((short)11); nci.XFIndex = (TEST_IDX); xfindex = sheet.GetXFIndexForColAt((short)1); Assert.AreEqual(DEFAULT_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)2); Assert.AreEqual(TEST_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)6); Assert.AreEqual(TEST_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)11); Assert.AreEqual(TEST_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)12); Assert.AreEqual(DEFAULT_IDX, xfindex); // single column ColumnInfoRecord starting at index 0 nci.FirstColumn = ((short)0); nci.LastColumn = ((short)0); nci.XFIndex = (TEST_IDX); xfindex = sheet.GetXFIndexForColAt((short)0); Assert.AreEqual(TEST_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)1); Assert.AreEqual(DEFAULT_IDX, xfindex); // ten column ColumnInfoRecord starting at index 0 nci.FirstColumn = ((short)0); nci.LastColumn = ((short)9); nci.XFIndex = (TEST_IDX); xfindex = sheet.GetXFIndexForColAt((short)0); Assert.AreEqual(TEST_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)7); Assert.AreEqual(TEST_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)9); Assert.AreEqual(TEST_IDX, xfindex); xfindex = sheet.GetXFIndexForColAt((short)10); Assert.AreEqual(DEFAULT_IDX, xfindex); } private class SizeCheckingRecordVisitor : RecordVisitor { private int _totalSize; public SizeCheckingRecordVisitor() { _totalSize = 0; } public void VisitRecord(Record r) { int estimatedSize = r.RecordSize; byte[] buf = new byte[estimatedSize]; int serializedSize = r.Serialize(0, buf); if (estimatedSize != serializedSize) { throw new AssertionException("serialized size mismatch for record (" + r.GetType().Name + ")"); } _totalSize += estimatedSize; } public int TotalSize { get { return _totalSize; } } } /** * Prior to bug 45066, POI would Get the estimated sheet size wrong * when an <c>UncalcedRecord</c> was present.<p/> */ [Test] public void TestUncalcSize_bug45066() { ArrayList records = new ArrayList(); records.Add(BOFRecord.CreateSheetBOF()); records.Add(new UncalcedRecord()); records.Add(new DimensionsRecord()); records.Add(CreateWindow2Record()); records.Add(new EOFRecord()); InternalSheet sheet = CreateSheet(records); // The original bug was due to different logic for collecting records for sizing and // serialization. The code has since been refactored into a single method for visiting // all contained records. Now this Test is much less interesting SizeCheckingRecordVisitor scrv = new SizeCheckingRecordVisitor(); sheet.VisitContainedRecords(scrv, 0); Assert.AreEqual(90, scrv.TotalSize); } /** * Prior to bug 45145 <c>RowRecordsAggregate</c> and <c>ValueRecordsAggregate</c> could * sometimes occur in reverse order. This Test reproduces one of those situations and makes * sure that RRA comes before VRA.<br/> * * The code here represents a normal POI use case where a spReadsheet is1 Created from scratch. */ [Test] public void TestRowValueAggregatesOrder_bug45145() { InternalSheet sheet = InternalSheet.CreateSheet(); RowRecord rr = new RowRecord(5); sheet.AddRow(rr); CellValueRecordInterface cvr = new BlankRecord(); cvr.Column = 0; cvr.Row = (5); sheet.AddValueRecord(5, cvr); int dbCellRecordPos = GetDbCellRecordPos(sheet); if (dbCellRecordPos == 252) { // The overt symptom of the bug // DBCELL record pos is1 calculated wrong if VRA comes before RRA throw new AssertionException("Identified bug 45145"); } Assert.AreEqual(242, dbCellRecordPos); } /** * @return the value calculated for the position of the first DBCELL record for this sheet. * That value is1 found on the IndexRecord. */ private static int GetDbCellRecordPos(InternalSheet sheet) { MyIndexRecordListener myIndexListener = new MyIndexRecordListener(); sheet.VisitContainedRecords(myIndexListener, 0); IndexRecord indexRecord = myIndexListener.GetIndexRecord(); int dbCellRecordPos = indexRecord.GetDbcellAt(0); return dbCellRecordPos; } private class MyIndexRecordListener : RecordVisitor { private IndexRecord _indexRecord; public MyIndexRecordListener() { // no-arg constructor } public IndexRecord GetIndexRecord() { return _indexRecord; } public void VisitRecord(Record r) { if (r is IndexRecord) { if (_indexRecord != null) { throw new Exception("too many index records"); } _indexRecord = (IndexRecord)r; } } } /** * Checks for bug introduced around r682282-r683880 that caused a second GUTS records * which in turn got the dimensions record out of alignment */ public void TestGutsRecord_bug45640() { InternalSheet sheet = InternalSheet.CreateSheet(); sheet.AddRow(new RowRecord(0)); sheet.AddRow(new RowRecord(1)); sheet.GroupRowRange( 0, 1, true ); sheet.ToString(); IList recs = sheet.Records; int count=0; for(int i=0; i< recs.Count; i++) { if (recs[i] is GutsRecord) { count++; } } if (count == 2) { throw new AssertionException("Identified bug 45640"); } Assert.AreEqual(1, count); } public void TestMisplacedMergedCellsRecords_bug45699() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("ex45698-22488.xls"); HSSFSheet sheet =(HSSFSheet)wb.GetSheetAt(0); HSSFRow row = (HSSFRow)sheet.GetRow(3); HSSFCell cell = (HSSFCell)row.GetCell(4); if (cell == null) { throw new AssertionException("Identified bug 45699"); } Assert.AreEqual("Informations", cell.RichStringCellValue.String); } /** * In 3.1, setting margins between creating first row and first cell caused an exception. */ [Test] public void TestSetMargins_bug45717() { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Vorschauliste"); HSSFRow row = (HSSFRow)sheet.CreateRow(0); sheet.SetMargin(NPOI.SS.UserModel.MarginType.LeftMargin, 0.3); try { row.CreateCell(0); } catch (InvalidOperationException e) { if (e.Message.Equals("Cannot Create value records before row records exist")) { throw new AssertionException("Identified bug 45717"); } throw e; } } /** * Some apps seem to write files with missing DIMENSION records. * Excel(2007) tolerates this, so POI should too. */ [Test] public void TestMissingDims() { int rowIx = 5; int colIx = 6; NumberRecord nr = new NumberRecord(); nr.Row = (rowIx); nr.Column = ((short)colIx); nr.Value = (3.0); ArrayList inRecs = new ArrayList(); inRecs.Add(BOFRecord.CreateSheetBOF()); inRecs.Add(new RowRecord(rowIx)); inRecs.Add(nr); inRecs.Add(CreateWindow2Record()); inRecs.Add(EOFRecord.instance); InternalSheet sheet; try { sheet = CreateSheet(inRecs); } catch (Exception e) { if ("DimensionsRecord was not found".Equals(e.Message)) { throw new AssertionException("Identified bug 46206"); } throw e; } RecordInspector.RecordCollector rv = new RecordInspector.RecordCollector(); sheet.VisitContainedRecords(rv, rowIx); Record[] outRecs = rv.Records; Assert.AreEqual(8, outRecs.Length); DimensionsRecord dims = (DimensionsRecord)outRecs[5]; Assert.AreEqual(rowIx, dims.FirstRow); Assert.AreEqual(rowIx, dims.LastRow); Assert.AreEqual(colIx, dims.FirstCol); Assert.AreEqual(colIx, dims.LastCol); } /** * Prior to the fix for bug 46547, shifting formulas would have the side-effect * of creating a {@link ConditionalFormattingTable}. There was no impairment to * functionality since empty record aggregates are equivalent to missing record * aggregates. However, since this unnecessary creation helped expose bug 46547b, * and since there is a slight performance hit the fix was made to avoid it. */ [Test] public void TestShiftFormulasAddCondFormat_bug46547() { // Create a sheet with data validity (similar to bugzilla attachment id=23131). InternalSheet sheet = InternalSheet.CreateSheet(); IList sheetRecs = sheet.Records; //Assert.AreEqual(23, sheetRecs.Count); Assert.AreEqual(24, sheetRecs.Count); //for SheetExtRecord FormulaShifter shifter = FormulaShifter.CreateForRowShift(0,"", 0, 0, 1); sheet.UpdateFormulasAfterCellShift(shifter, 0); if (sheetRecs.Count == 25 && sheetRecs[22] is ConditionalFormattingTable) { throw new AssertionException("Identified bug 46547a"); } //Assert.AreEqual(23, sheetRecs.Count); Assert.AreEqual(24, sheetRecs.Count); //for SheetExtRecord } /** * Bug 46547 happened when attempting to Add conditional formatting to a sheet * which already had data validity constraints. */ [Test] public void TestAddCondFormatAfterDataValidation_bug46547() { // Create a sheet with data validity (similar to bugzilla attachment id=23131). InternalSheet sheet = InternalSheet.CreateSheet(); sheet.GetOrCreateDataValidityTable(); ConditionalFormattingTable cft; // attempt to Add conditional formatting try { cft = sheet.ConditionalFormattingTable; // lazy getter } catch (InvalidCastException) { throw new AssertionException("Identified bug 46547b"); } Assert.IsNotNull(cft); } [Test] public void TestCloneMulBlank_bug46776() { Record[] recs = { InternalSheet.CreateBOF(), new DimensionsRecord(), new RowRecord(1), new MulBlankRecord(1, 3, new short[] { 0x0F, 0x0F, 0x0F, } ), new RowRecord(2), CreateWindow2Record(), EOFRecord.instance, }; InternalSheet sheet = CreateSheet(NPOI.Util.Arrays.AsList(recs)); InternalSheet sheet2; try { sheet2 = sheet.CloneSheet(); } catch (Exception e) { if (e.Message.Equals("The class org.apache.poi.hssf.record.MulBlankRecord needs to define a clone method")) { throw new AssertionException("Identified bug 46776"); } throw e; } TestCases.HSSF.UserModel.RecordInspector.RecordCollector rc = new TestCases.HSSF.UserModel.RecordInspector.RecordCollector(); sheet2.VisitContainedRecords(rc, 0); Record[] clonedRecs = rc.Records; Assert.AreEqual(recs.Length + 2, clonedRecs.Length); // +2 for INDEX and DBCELL } [Test] public void TestCreateAggregate() { String msoDrawingRecord1 = "0F 00 02 F0 20 01 00 00 10 00 08 F0 08 00 00 00 \n" + "03 00 00 00 02 04 00 00 0F 00 03 F0 08 01 00 00 \n" + "0F 00 04 F0 28 00 00 00 01 00 09 F0 10 00 00 00 \n" + "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \n" + "02 00 0A F0 08 00 00 00 00 04 00 00 05 00 00 00 \n" + "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 \n" + "01 04 00 00 00 0A 00 00 73 00 0B F0 2A 00 00 00 \n" + "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 \n" + "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 \n" + "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 \n" + "00 00 00 00 01 00 54 00 05 00 45 00 01 00 88 03 \n" + "05 00 94 00 00 00 11 F0 00 00 00 00"; String msoDrawingRecord2 = "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 " + "02 04 00 00 80 0A 00 00 73 00 0B F0 2A 00 00 00 " + "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 " + "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 " + "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 " + "00 00 00 00 01 00 8D 03 05 00 E4 00 03 00 4D 03 " + "0B 00 0C 00 00 00 11 F0 00 00 00 00"; DrawingRecord d1 = new DrawingRecord(); d1.Data = HexRead.ReadFromString(msoDrawingRecord1); ObjRecord r1 = new ObjRecord(); DrawingRecord d2 = new DrawingRecord(); d2.Data = (HexRead.ReadFromString(msoDrawingRecord2)); TextObjectRecord r2 = new TextObjectRecord(); r2.Str = (new HSSFRichTextString("Aggregated")); NoteRecord n2 = new NoteRecord(); List<RecordBase> recordStream = new List<RecordBase>(); recordStream.Add(InternalSheet.CreateBOF()); recordStream.Add(d1); recordStream.Add(r1); recordStream.Add(CreateWindow2Record()); recordStream.Add(EOFRecord.instance); ConfirmAggregatedRecords(recordStream); recordStream = new List<RecordBase>(); recordStream.Add(InternalSheet.CreateBOF()); recordStream.Add(d1); recordStream.Add(r1); recordStream.Add(d2); recordStream.Add(r2); recordStream.Add(CreateWindow2Record()); recordStream.Add(EOFRecord.instance); ConfirmAggregatedRecords(recordStream); recordStream = new List<RecordBase>(); recordStream.Add(InternalSheet.CreateBOF()); recordStream.Add(d1); recordStream.Add(r1); recordStream.Add(d2); recordStream.Add(r2); recordStream.Add(n2); recordStream.Add(CreateWindow2Record()); recordStream.Add(EOFRecord.instance); ConfirmAggregatedRecords(recordStream); } private void ConfirmAggregatedRecords(List<RecordBase> recordStream) { InternalSheet sheet = InternalSheet.CreateSheet(); sheet.Records.Clear(); ((List<RecordBase>)sheet.Records).AddRange(recordStream); IList sheetRecords = sheet.Records; DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord()); sheet.AggregateDrawingRecords(drawingManager, false); Assert.AreEqual(4, sheetRecords.Count); Assert.AreEqual(BOFRecord.sid, ((Record)sheetRecords[0]).Sid); Assert.AreEqual(EscherAggregate.sid, ((Record)sheetRecords[1]).Sid); Assert.AreEqual(WindowTwoRecord.sid, ((Record)sheetRecords[2]).Sid); Assert.AreEqual(EOFRecord.sid, ((Record)sheetRecords[3]).Sid); } [Test] public void TestSheetDimensions() { InternalSheet sheet = InternalSheet.CreateSheet(); DimensionsRecord dimensions = (DimensionsRecord)sheet.FindFirstRecordBySid(DimensionsRecord.sid); Assert.AreEqual(0, dimensions.FirstCol); Assert.AreEqual(0, dimensions.FirstRow); Assert.AreEqual(1, dimensions.LastCol); // plus pne Assert.AreEqual(1, dimensions.LastRow); // plus pne RowRecord rr = new RowRecord(0); sheet.AddRow(rr); Assert.AreEqual(0, dimensions.FirstCol); Assert.AreEqual(0, dimensions.FirstRow); Assert.AreEqual(1, dimensions.LastCol); Assert.AreEqual(1, dimensions.LastRow); CellValueRecordInterface cvr; cvr = new BlankRecord(); cvr.Column = ((short)0); cvr.Row = (0); sheet.AddValueRecord(0, cvr); Assert.AreEqual(0, dimensions.FirstCol); Assert.AreEqual(0, dimensions.FirstRow); Assert.AreEqual(1, dimensions.LastCol); Assert.AreEqual(1, dimensions.LastRow); cvr = new BlankRecord(); cvr.Column = ((short)1); cvr.Row = (0); sheet.AddValueRecord(0, cvr); Assert.AreEqual(0, dimensions.FirstCol); Assert.AreEqual(0, dimensions.FirstRow); Assert.AreEqual(2, dimensions.LastCol); //YK: failed until Bugzilla 53414 was fixed Assert.AreEqual(1, dimensions.LastRow); } } }
namespace Humidifier.RDS { using System.Collections.Generic; using DBClusterTypes; public class DBCluster : Humidifier.Resource { public static class Attributes { } public override string AWSTypeName { get { return @"AWS::RDS::DBCluster"; } } /// <summary> /// AssociatedRoles /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-associatedroles /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: DBClusterRole /// </summary> public List<DBClusterRole> AssociatedRoles { get; set; } /// <summary> /// AvailabilityZones /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-availabilityzones /// Required: False /// UpdateType: Immutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic AvailabilityZones { get; set; } /// <summary> /// BacktrackWindow /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-backtrackwindow /// Required: False /// UpdateType: Mutable /// PrimitiveType: Long /// </summary> public dynamic BacktrackWindow { get; set; } /// <summary> /// BackupRetentionPeriod /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-backuprententionperiod /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic BackupRetentionPeriod { get; set; } /// <summary> /// DBClusterIdentifier /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-dbclusteridentifier /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic DBClusterIdentifier { get; set; } /// <summary> /// DBClusterParameterGroupName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-dbclusterparametergroupname /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic DBClusterParameterGroupName { get; set; } /// <summary> /// DBSubnetGroupName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-dbsubnetgroupname /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic DBSubnetGroupName { get; set; } /// <summary> /// DatabaseName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-databasename /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic DatabaseName { get; set; } /// <summary> /// DeletionProtection /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-deletionprotection /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic DeletionProtection { get; set; } /// <summary> /// EnableCloudwatchLogsExports /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-enablecloudwatchlogsexports /// Required: False /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic EnableCloudwatchLogsExports { get; set; } /// <summary> /// EnableHttpEndpoint /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-enablehttpendpoint /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic EnableHttpEndpoint { get; set; } /// <summary> /// EnableIAMDatabaseAuthentication /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-enableiamdatabaseauthentication /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic EnableIAMDatabaseAuthentication { get; set; } /// <summary> /// Engine /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-engine /// Required: True /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic Engine { get; set; } /// <summary> /// EngineMode /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-enginemode /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic EngineMode { get; set; } /// <summary> /// EngineVersion /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-engineversion /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic EngineVersion { get; set; } /// <summary> /// KmsKeyId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-kmskeyid /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic KmsKeyId { get; set; } /// <summary> /// MasterUserPassword /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-masteruserpassword /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic MasterUserPassword { get; set; } /// <summary> /// MasterUsername /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-masterusername /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic MasterUsername { get; set; } /// <summary> /// Port /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-port /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic Port { get; set; } /// <summary> /// PreferredBackupWindow /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-preferredbackupwindow /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic PreferredBackupWindow { get; set; } /// <summary> /// PreferredMaintenanceWindow /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-preferredmaintenancewindow /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic PreferredMaintenanceWindow { get; set; } /// <summary> /// ReplicationSourceIdentifier /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-replicationsourceidentifier /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ReplicationSourceIdentifier { get; set; } /// <summary> /// RestoreType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-restoretype /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic RestoreType { get; set; } /// <summary> /// ScalingConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-scalingconfiguration /// Required: False /// UpdateType: Mutable /// Type: ScalingConfiguration /// </summary> public ScalingConfiguration ScalingConfiguration { get; set; } /// <summary> /// SnapshotIdentifier /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-snapshotidentifier /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic SnapshotIdentifier { get; set; } /// <summary> /// SourceDBClusterIdentifier /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-sourcedbclusteridentifier /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic SourceDBClusterIdentifier { get; set; } /// <summary> /// SourceRegion /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-sourceregion /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic SourceRegion { get; set; } /// <summary> /// StorageEncrypted /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-storageencrypted /// Required: False /// UpdateType: Immutable /// PrimitiveType: Boolean /// </summary> public dynamic StorageEncrypted { get; set; } /// <summary> /// Tags /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-tags /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: Tag /// </summary> public List<Tag> Tags { get; set; } /// <summary> /// UseLatestRestorableTime /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-uselatestrestorabletime /// Required: False /// UpdateType: Immutable /// PrimitiveType: Boolean /// </summary> public dynamic UseLatestRestorableTime { get; set; } /// <summary> /// VpcSecurityGroupIds /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-vpcsecuritygroupids /// Required: False /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic VpcSecurityGroupIds { get; set; } } namespace DBClusterTypes { public class ScalingConfiguration { /// <summary> /// AutoPause /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbcluster-scalingconfiguration.html#cfn-rds-dbcluster-scalingconfiguration-autopause /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic AutoPause { get; set; } /// <summary> /// MaxCapacity /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbcluster-scalingconfiguration.html#cfn-rds-dbcluster-scalingconfiguration-maxcapacity /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic MaxCapacity { get; set; } /// <summary> /// MinCapacity /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbcluster-scalingconfiguration.html#cfn-rds-dbcluster-scalingconfiguration-mincapacity /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic MinCapacity { get; set; } /// <summary> /// SecondsUntilAutoPause /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbcluster-scalingconfiguration.html#cfn-rds-dbcluster-scalingconfiguration-secondsuntilautopause /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic SecondsUntilAutoPause { get; set; } } public class DBClusterRole { /// <summary> /// FeatureName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbcluster-dbclusterrole.html#cfn-rds-dbcluster-dbclusterrole-featurename /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic FeatureName { get; set; } /// <summary> /// RoleArn /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbcluster-dbclusterrole.html#cfn-rds-dbcluster-dbclusterrole-rolearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RoleArn { 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. #if AMD64 || (BIT32 && !ARM) #define HAS_CUSTOM_BLOCKS #endif using System; using System.Runtime; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; #if BIT64 using nint = System.Int64; using nuint = System.UInt64; #else using nint = System.Int32; using nuint = System.UInt32; #endif namespace System { public static class Buffer { public static unsafe void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count) { nuint uSrcLen; nuint uDstLen; if (src == null) throw new ArgumentNullException(nameof(src)); if (dst == null) throw new ArgumentNullException(nameof(dst)); // Use optimized path for byte arrays since this is the main scenario for Buffer::BlockCopy // We only need an unreliable comparison since the slow path can handle the byte[] case too. if (src.EETypePtr.FastEqualsUnreliable(EETypePtr.EETypePtrOf<byte[]>())) { uSrcLen = (nuint)src.Length; } else { RuntimeImports.RhCorElementTypeInfo srcCorElementTypeInfo = src.ElementEEType.CorElementTypeInfo; uSrcLen = ((nuint)src.Length) << srcCorElementTypeInfo.Log2OfSize; if (!srcCorElementTypeInfo.IsPrimitive) throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(src)); } if (src != dst) { // Use optimized path for byte arrays since this is the main scenario for Buffer::BlockCopy // We only need an unreliable comparison since the slow path can handle the byte[] case too. if (dst.EETypePtr.FastEqualsUnreliable(EETypePtr.EETypePtrOf<byte[]>())) { uDstLen = (nuint)dst.Length; } else { RuntimeImports.RhCorElementTypeInfo dstCorElementTypeInfo = dst.ElementEEType.CorElementTypeInfo; if (!dstCorElementTypeInfo.IsPrimitive) throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(dst)); uDstLen = ((nuint)dst.Length) << dstCorElementTypeInfo.Log2OfSize; } } else { uDstLen = uSrcLen; } if (srcOffset < 0) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_MustBeNonNegInt32, nameof(srcOffset)); if (dstOffset < 0) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_MustBeNonNegInt32, nameof(dstOffset)); if (count < 0) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_MustBeNonNegInt32, nameof(count)); nuint uCount = (nuint)count; nuint uSrcOffset = (nuint)srcOffset; nuint uDstOffset = (nuint)dstOffset; if (uSrcLen < uSrcOffset + uCount) throw new ArgumentException(SR.Argument_InvalidOffLen); if (uDstLen < uDstOffset + uCount) throw new ArgumentException(SR.Argument_InvalidOffLen); if (uCount != 0) { fixed (byte* pSrc = &src.GetRawArrayData(), pDst = &dst.GetRawArrayData()) { Buffer.Memmove(pDst + uDstOffset, pSrc + uSrcOffset, uCount); } } } internal static unsafe void ZeroMemory(byte* src, long len) { while (len-- > 0) *(src + len) = 0; } public static int ByteLength(Array array) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!array.ElementEEType.IsPrimitive) throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(array)); return _ByteLength(array); } private static unsafe int _ByteLength(Array array) { return checked(array.Length * array.EETypePtr.ComponentSize); } public static unsafe byte GetByte(Array array, int index) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!array.ElementEEType.IsPrimitive) throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(array)); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException(nameof(index)); return Unsafe.Add(ref array.GetRawArrayData(), index); } public static unsafe void SetByte(Array array, int index, byte value) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!array.ElementEEType.IsPrimitive) throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(array)); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException(nameof(index)); Unsafe.Add(ref array.GetRawArrayData(), index) = value; } // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { throw new ArgumentOutOfRangeException(nameof(sourceBytesToCopy)); } Memmove((byte*)destination, (byte*)source, checked((nuint)sourceBytesToCopy)); } // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static unsafe void MemoryCopy(void* source, void* destination, ulong destinationSizeInBytes, ulong sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { throw new ArgumentOutOfRangeException(nameof(sourceBytesToCopy)); } Memmove((byte*)destination, (byte*)source, checked((nuint)sourceBytesToCopy)); } internal unsafe static void Memcpy(byte* dest, byte* src, int len) { Debug.Assert(len >= 0, "Negative length in memcpy!"); Memmove(dest, src, (nuint)len); } // This method has different signature for x64 and other platforms and is done for performance reasons. internal unsafe static void Memmove(byte* dest, byte* src, nuint len) { #if AMD64 || (BIT32 && !ARM) const nuint CopyThreshold = 2048; #else const nuint CopyThreshold = 512; #endif // AMD64 || (BIT32 && !ARM) // P/Invoke into the native version when the buffers are overlapping. if (((nuint)dest - (nuint)src < len) || ((nuint)src - (nuint)dest < len)) goto PInvoke; byte* srcEnd = src + len; byte* destEnd = dest + len; if (len <= 16) goto MCPY02; if (len > 64) goto MCPY05; MCPY00: // Copy bytes which are multiples of 16 and leave the remainder for MCPY01 to handle. Debug.Assert(len > 16 && len <= 64); #if HAS_CUSTOM_BLOCKS *(Block16*)dest = *(Block16*)src; // [0,16] #elif BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); // [0,16] #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); // [0,16] #endif if (len <= 32) goto MCPY01; #if HAS_CUSTOM_BLOCKS *(Block16*)(dest + 16) = *(Block16*)(src + 16); // [0,32] #elif BIT64 *(long*)(dest + 16) = *(long*)(src + 16); *(long*)(dest + 24) = *(long*)(src + 24); // [0,32] #else *(int*)(dest + 16) = *(int*)(src + 16); *(int*)(dest + 20) = *(int*)(src + 20); *(int*)(dest + 24) = *(int*)(src + 24); *(int*)(dest + 28) = *(int*)(src + 28); // [0,32] #endif if (len <= 48) goto MCPY01; #if HAS_CUSTOM_BLOCKS *(Block16*)(dest + 32) = *(Block16*)(src + 32); // [0,48] #elif BIT64 *(long*)(dest + 32) = *(long*)(src + 32); *(long*)(dest + 40) = *(long*)(src + 40); // [0,48] #else *(int*)(dest + 32) = *(int*)(src + 32); *(int*)(dest + 36) = *(int*)(src + 36); *(int*)(dest + 40) = *(int*)(src + 40); *(int*)(dest + 44) = *(int*)(src + 44); // [0,48] #endif MCPY01: // Unconditionally copy the last 16 bytes using destEnd and srcEnd and return. Debug.Assert(len > 16 && len <= 64); #if HAS_CUSTOM_BLOCKS *(Block16*)(destEnd - 16) = *(Block16*)(srcEnd - 16); #elif BIT64 *(long*)(destEnd - 16) = *(long*)(srcEnd - 16); *(long*)(destEnd - 8) = *(long*)(srcEnd - 8); #else *(int*)(destEnd - 16) = *(int*)(srcEnd - 16); *(int*)(destEnd - 12) = *(int*)(srcEnd - 12); *(int*)(destEnd - 8) = *(int*)(srcEnd - 8); *(int*)(destEnd - 4) = *(int*)(srcEnd - 4); #endif return; MCPY02: // Copy the first 8 bytes and then unconditionally copy the last 8 bytes and return. if ((len & 24) == 0) goto MCPY03; Debug.Assert(len >= 8 && len <= 16); #if BIT64 *(long*)dest = *(long*)src; *(long*)(destEnd - 8) = *(long*)(srcEnd - 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(destEnd - 8) = *(int*)(srcEnd - 8); *(int*)(destEnd - 4) = *(int*)(srcEnd - 4); #endif return; MCPY03: // Copy the first 4 bytes and then unconditionally copy the last 4 bytes and return. if ((len & 4) == 0) goto MCPY04; Debug.Assert(len >= 4 && len < 8); *(int*)dest = *(int*)src; *(int*)(destEnd - 4) = *(int*)(srcEnd - 4); return; MCPY04: // Copy the first byte. For pending bytes, do an unconditionally copy of the last 2 bytes and return. Debug.Assert(len < 4); if (len == 0) return; *dest = *src; if ((len & 2) == 0) return; *(short*)(destEnd - 2) = *(short*)(srcEnd - 2); return; MCPY05: // PInvoke to the native version when the copy length exceeds the threshold. if (len > CopyThreshold) { goto PInvoke; } // Copy 64-bytes at a time until the remainder is less than 64. // If remainder is greater than 16 bytes, then jump to MCPY00. Otherwise, unconditionally copy the last 16 bytes and return. Debug.Assert(len > 64 && len <= CopyThreshold); nuint n = len >> 6; MCPY06: #if HAS_CUSTOM_BLOCKS *(Block64*)dest = *(Block64*)src; #elif BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); *(long*)(dest + 16) = *(long*)(src + 16); *(long*)(dest + 24) = *(long*)(src + 24); *(long*)(dest + 32) = *(long*)(src + 32); *(long*)(dest + 40) = *(long*)(src + 40); *(long*)(dest + 48) = *(long*)(src + 48); *(long*)(dest + 56) = *(long*)(src + 56); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); *(int*)(dest + 16) = *(int*)(src + 16); *(int*)(dest + 20) = *(int*)(src + 20); *(int*)(dest + 24) = *(int*)(src + 24); *(int*)(dest + 28) = *(int*)(src + 28); *(int*)(dest + 32) = *(int*)(src + 32); *(int*)(dest + 36) = *(int*)(src + 36); *(int*)(dest + 40) = *(int*)(src + 40); *(int*)(dest + 44) = *(int*)(src + 44); *(int*)(dest + 48) = *(int*)(src + 48); *(int*)(dest + 52) = *(int*)(src + 52); *(int*)(dest + 56) = *(int*)(src + 56); *(int*)(dest + 60) = *(int*)(src + 60); #endif dest += 64; src += 64; n--; if (n != 0) goto MCPY06; len %= 64; if (len > 16) goto MCPY00; #if HAS_CUSTOM_BLOCKS *(Block16*)(destEnd - 16) = *(Block16*)(srcEnd - 16); #elif BIT64 *(long*)(destEnd - 16) = *(long*)(srcEnd - 16); *(long*)(destEnd - 8) = *(long*)(srcEnd - 8); #else *(int*)(destEnd - 16) = *(int*)(srcEnd - 16); *(int*)(destEnd - 12) = *(int*)(srcEnd - 12); *(int*)(destEnd - 8) = *(int*)(srcEnd - 8); *(int*)(destEnd - 4) = *(int*)(srcEnd - 4); #endif return; PInvoke: _Memmove(dest, src, len); } // This method has different signature for x64 and other platforms and is done for performance reasons. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void Memmove<T>(ref T destination, ref T source, nuint elementCount) { if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { // Blittable memmove #if PROJECTN unsafe { fixed (byte* pDestination = &Unsafe.As<T, byte>(ref destination), pSource = &Unsafe.As<T, byte>(ref source)) Memmove(pDestination, pSource, elementCount * (nuint)Unsafe.SizeOf<T>()); } #else Memmove( new ByReference<byte>(ref Unsafe.As<T, byte>(ref destination)), new ByReference<byte>(ref Unsafe.As<T, byte>(ref source)), elementCount * (nuint)Unsafe.SizeOf<T>()); #endif } else { // Non-blittable memmove // Try to avoid calling RhBulkMoveWithWriteBarrier if we can get away // with a no-op. if (!Unsafe.AreSame(ref destination, ref source) && elementCount != 0) { RuntimeImports.RhBulkMoveWithWriteBarrier( ref Unsafe.As<T, byte>(ref destination), ref Unsafe.As<T, byte>(ref source), elementCount * (nuint)Unsafe.SizeOf<T>()); } } } #if !PROJECTN // This method has different signature for x64 and other platforms and is done for performance reasons. private static void Memmove(ByReference<byte> dest, ByReference<byte> src, nuint len) { #if AMD64 || (BIT32 && !ARM) const nuint CopyThreshold = 2048; #elif ARM64 #if PLATFORM_WINDOWS // Determined optimal value for Windows. // https://github.com/dotnet/coreclr/issues/13843 const nuint CopyThreshold = UInt64.MaxValue; #else // PLATFORM_WINDOWS // Managed code is currently faster than glibc unoptimized memmove // TODO-ARM64-UNIX-OPT revisit when glibc optimized memmove is in Linux distros // https://github.com/dotnet/coreclr/issues/13844 const nuint CopyThreshold = UInt64.MaxValue; #endif // PLATFORM_WINDOWS #else const nuint CopyThreshold = 512; #endif // AMD64 || (BIT32 && !ARM) // P/Invoke into the native version when the buffers are overlapping. if (((nuint)Unsafe.ByteOffset(ref src.Value, ref dest.Value) < len) || ((nuint)Unsafe.ByteOffset(ref dest.Value, ref src.Value) < len)) { goto BuffersOverlap; } // Use "(IntPtr)(nint)len" to avoid overflow checking on the explicit cast to IntPtr ref byte srcEnd = ref Unsafe.Add(ref src.Value, (IntPtr)(nint)len); ref byte destEnd = ref Unsafe.Add(ref dest.Value, (IntPtr)(nint)len); if (len <= 16) goto MCPY02; if (len > 64) goto MCPY05; MCPY00: // Copy bytes which are multiples of 16 and leave the remainder for MCPY01 to handle. Debug.Assert(len > 16 && len <= 64); #if HAS_CUSTOM_BLOCKS Unsafe.As<byte, Block16>(ref dest.Value) = Unsafe.As<byte, Block16>(ref src.Value); // [0,16] #elif BIT64 Unsafe.As<byte, long>(ref dest.Value) = Unsafe.As<byte, long>(ref src.Value); Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 8)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 8)); // [0,16] #else Unsafe.As<byte, int>(ref dest.Value) = Unsafe.As<byte, int>(ref src.Value); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 4)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 4)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 8)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 8)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 12)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 12)); // [0,16] #endif if (len <= 32) goto MCPY01; #if HAS_CUSTOM_BLOCKS Unsafe.As<byte, Block16>(ref Unsafe.Add(ref dest.Value, 16)) = Unsafe.As<byte, Block16>(ref Unsafe.Add(ref src.Value, 16)); // [0,32] #elif BIT64 Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 16)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 16)); Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 24)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 24)); // [0,32] #else Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 16)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 16)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 20)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 20)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 24)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 24)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 28)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 28)); // [0,32] #endif if (len <= 48) goto MCPY01; #if HAS_CUSTOM_BLOCKS Unsafe.As<byte, Block16>(ref Unsafe.Add(ref dest.Value, 32)) = Unsafe.As<byte, Block16>(ref Unsafe.Add(ref src.Value, 32)); // [0,48] #elif BIT64 Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 32)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 32)); Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 40)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 40)); // [0,48] #else Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 32)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 32)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 36)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 36)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 40)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 40)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 44)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 44)); // [0,48] #endif MCPY01: // Unconditionally copy the last 16 bytes using destEnd and srcEnd and return. Debug.Assert(len > 16 && len <= 64); #if HAS_CUSTOM_BLOCKS Unsafe.As<byte, Block16>(ref Unsafe.Add(ref destEnd, -16)) = Unsafe.As<byte, Block16>(ref Unsafe.Add(ref srcEnd, -16)); #elif BIT64 Unsafe.As<byte, long>(ref Unsafe.Add(ref destEnd, -16)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref srcEnd, -16)); Unsafe.As<byte, long>(ref Unsafe.Add(ref destEnd, -8)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref srcEnd, -8)); #else Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -16)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -16)); Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -12)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -12)); Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -8)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -8)); Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -4)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -4)); #endif return; MCPY02: // Copy the first 8 bytes and then unconditionally copy the last 8 bytes and return. if ((len & 24) == 0) goto MCPY03; Debug.Assert(len >= 8 && len <= 16); #if BIT64 Unsafe.As<byte, long>(ref dest.Value) = Unsafe.As<byte, long>(ref src.Value); Unsafe.As<byte, long>(ref Unsafe.Add(ref destEnd, -8)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref srcEnd, -8)); #else Unsafe.As<byte, int>(ref dest.Value) = Unsafe.As<byte, int>(ref src.Value); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 4)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 4)); Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -8)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -8)); Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -4)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -4)); #endif return; MCPY03: // Copy the first 4 bytes and then unconditionally copy the last 4 bytes and return. if ((len & 4) == 0) goto MCPY04; Debug.Assert(len >= 4 && len < 8); Unsafe.As<byte, int>(ref dest.Value) = Unsafe.As<byte, int>(ref src.Value); Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -4)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -4)); return; MCPY04: // Copy the first byte. For pending bytes, do an unconditionally copy of the last 2 bytes and return. Debug.Assert(len < 4); if (len == 0) return; dest.Value = src.Value; if ((len & 2) == 0) return; Unsafe.As<byte, short>(ref Unsafe.Add(ref destEnd, -2)) = Unsafe.As<byte, short>(ref Unsafe.Add(ref srcEnd, -2)); return; MCPY05: // PInvoke to the native version when the copy length exceeds the threshold. if (len > CopyThreshold) { goto PInvoke; } // Copy 64-bytes at a time until the remainder is less than 64. // If remainder is greater than 16 bytes, then jump to MCPY00. Otherwise, unconditionally copy the last 16 bytes and return. Debug.Assert(len > 64 && len <= CopyThreshold); nuint n = len >> 6; MCPY06: #if HAS_CUSTOM_BLOCKS Unsafe.As<byte, Block64>(ref dest.Value) = Unsafe.As<byte, Block64>(ref src.Value); #elif BIT64 Unsafe.As<byte, long>(ref dest.Value) = Unsafe.As<byte, long>(ref src.Value); Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 8)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 8)); Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 16)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 16)); Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 24)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 24)); Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 32)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 32)); Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 40)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 40)); Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 48)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 48)); Unsafe.As<byte, long>(ref Unsafe.Add(ref dest.Value, 56)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref src.Value, 56)); #else Unsafe.As<byte, int>(ref dest.Value) = Unsafe.As<byte, int>(ref src.Value); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 4)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 4)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 8)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 8)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 12)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 12)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 16)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 16)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 20)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 20)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 24)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 24)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 28)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 28)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 32)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 32)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 36)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 36)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 40)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 40)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 44)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 44)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 48)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 48)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 52)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 52)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 56)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 56)); Unsafe.As<byte, int>(ref Unsafe.Add(ref dest.Value, 60)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref src.Value, 60)); #endif dest = new ByReference<byte>(ref Unsafe.Add(ref dest.Value, 64)); src = new ByReference<byte>(ref Unsafe.Add(ref src.Value, 64)); n--; if (n != 0) goto MCPY06; len %= 64; if (len > 16) goto MCPY00; #if HAS_CUSTOM_BLOCKS Unsafe.As<byte, Block16>(ref Unsafe.Add(ref destEnd, -16)) = Unsafe.As<byte, Block16>(ref Unsafe.Add(ref srcEnd, -16)); #elif BIT64 Unsafe.As<byte, long>(ref Unsafe.Add(ref destEnd, -16)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref srcEnd, -16)); Unsafe.As<byte, long>(ref Unsafe.Add(ref destEnd, -8)) = Unsafe.As<byte, long>(ref Unsafe.Add(ref srcEnd, -8)); #else Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -16)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -16)); Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -12)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -12)); Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -8)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -8)); Unsafe.As<byte, int>(ref Unsafe.Add(ref destEnd, -4)) = Unsafe.As<byte, int>(ref Unsafe.Add(ref srcEnd, -4)); #endif return; BuffersOverlap: // If the buffers overlap perfectly, there's no point to copying the data. if (Unsafe.AreSame(ref dest.Value, ref src.Value)) { return; } PInvoke: _Memmove(ref dest.Value, ref src.Value, len); } #endif // !PROJECTN // Non-inlinable wrapper around the QCall that avoids poluting the fast path // with P/Invoke prolog/epilog. [MethodImplAttribute(MethodImplOptions.NoInlining)] private static unsafe void _Memmove(byte* dest, byte* src, nuint len) { RuntimeImports.memmove(dest, src, len); } // Non-inlinable wrapper around the QCall that avoids polluting the fast path // with P/Invoke prolog/epilog. [MethodImplAttribute(MethodImplOptions.NoInlining)] private unsafe static void _Memmove(ref byte dest, ref byte src, nuint len) { fixed (byte* pDest = &dest) fixed (byte* pSrc = &src) RuntimeImports.memmove(pDest, pSrc, len); } #if HAS_CUSTOM_BLOCKS [StructLayout(LayoutKind.Explicit, Size = 16)] private struct Block16 { } [StructLayout(LayoutKind.Explicit, Size = 64)] private struct Block64 { } #endif // HAS_CUSTOM_BLOCKS } }
using System; namespace Fonet.Pdf.Gdi { /// <summary> /// Maps a Unicode character to a WinAnsi codepoint value. /// </summary> internal class WinAnsiMapping { /// <summary> /// First column is codepoint value. Second column is unicode value. /// </summary> private static readonly int[] winAnsiEncoding = { 0x20, 0x0020, // space 0x20, 0x00A0, // space 0x21, 0x0021, // exclam 0x22, 0x0022, // quotedbl 0x23, 0x0023, // numbersign 0x24, 0x0024, // dollar 0x25, 0x0025, // percent 0x26, 0x0026, // ampersand 0x27, 0x0027, // quotesingle 0x28, 0x0028, // parenleft 0x29, 0x0029, // parenright 0x2a, 0x002A, // asterisk 0x2b, 0x002B, // plus 0x2c, 0x002C, // comma 0x2d, 0x002D, // hyphen 0x2d, 0x00AD, // hyphen 0x2e, 0x002E, // period 0x2f, 0x002F, // slash 0x30, 0x0030, // zero 0x31, 0x0031, // one 0x32, 0x0032, // two 0x33, 0x0033, // three 0x34, 0x0034, // four 0x35, 0x0035, // five 0x36, 0x0036, // six 0x37, 0x0037, // seven 0x38, 0x0038, // eight 0x39, 0x0039, // nine 0x3a, 0x003A, // colon 0x3b, 0x003B, // semicolon 0x3c, 0x003C, // less 0x3d, 0x003D, // equal 0x3e, 0x003E, // greater 0x3f, 0x003F, // question 0x40, 0x0040, // at 0x41, 0x0041, // A 0x42, 0x0042, // B 0x43, 0x0043, // C 0x44, 0x0044, // D 0x45, 0x0045, // E 0x46, 0x0046, // F 0x47, 0x0047, // G 0x48, 0x0048, // H 0x49, 0x0049, // I 0x4a, 0x004A, // J 0x4b, 0x004B, // K 0x4c, 0x004C, // L 0x4d, 0x004D, // M 0x4e, 0x004E, // N 0x4f, 0x004F, // O 0x50, 0x0050, // P 0x51, 0x0051, // Q 0x52, 0x0052, // R 0x53, 0x0053, // S 0x54, 0x0054, // T 0x55, 0x0055, // U 0x56, 0x0056, // V 0x57, 0x0057, // W 0x58, 0x0058, // X 0x59, 0x0059, // Y 0x5a, 0x005A, // Z 0x5b, 0x005B, // bracketleft 0x5c, 0x005C, // backslash 0x5d, 0x005D, // bracketright 0x5e, 0x005E, // asciicircum 0x5f, 0x005F, // underscore 0x60, 0x0060, // grave 0x61, 0x0061, // a 0x62, 0x0062, // b 0x63, 0x0063, // c 0x64, 0x0064, // d 0x65, 0x0065, // e 0x66, 0x0066, // f 0x67, 0x0067, // g 0x68, 0x0068, // h 0x69, 0x0069, // i 0x6a, 0x006A, // j 0x6b, 0x006B, // k 0x6c, 0x006C, // l 0x6d, 0x006D, // m 0x6e, 0x006E, // n 0x6f, 0x006F, // o 0x70, 0x0070, // p 0x71, 0x0071, // q 0x72, 0x0072, // r 0x73, 0x0073, // s 0x74, 0x0074, // t 0x75, 0x0075, // u 0x76, 0x0076, // v 0x77, 0x0077, // w 0x78, 0x0078, // x 0x79, 0x0079, // y 0x7a, 0x007A, // z 0x7b, 0x007B, // braceleft 0x7c, 0x007C, // bar 0x7d, 0x007D, // braceright 0x7e, 0x007E, // asciitilde 0x80, 0x20AC, // Euro 0x82, 0x201A, // quotesinglbase 0x83, 0x0192, // florin 0x84, 0x201E, // quotedblbase 0x85, 0x2026, // ellipsis 0x86, 0x2020, // dagger 0x87, 0x2021, // daggerdbl 0x88, 0x02C6, // circumflex 0x89, 0x2030, // perthousand 0x8a, 0x0160, // Scaron 0x8b, 0x2039, // guilsinglleft 0x8c, 0x0152, // OE 0x8e, 0x017D, // Zcaron 0x91, 0x2018, // quoteleft 0x92, 0x2019, // quoteright 0x93, 0x201C, // quotedblleft 0x94, 0x201D, // quotedblright 0x95, 0x2022, // bullet 0x96, 0x2013, // endash 0x97, 0x2014, // emdash 0x98, 0x02DC, // tilde 0x99, 0x2122, // trademark 0x9a, 0x0161, // scaron 0x9b, 0x203A, // guilsinglright 0x9c, 0x0153, // oe 0x9e, 0x017E, // zcaron 0x9f, 0x0178, // Ydieresis 0xa1, 0x00A1, // exclamdown 0xa2, 0x00A2, // cent 0xa3, 0x00A3, // sterling 0xa4, 0x00A4, // currency 0xa5, 0x00A5, // yen 0xa6, 0x00A6, // brokenbar 0xa7, 0x00A7, // section 0xa8, 0x00A8, // dieresis 0xa9, 0x00A9, // copyright 0xaa, 0x00AA, // ordfeminine 0xab, 0x00AB, // guillemotleft 0xac, 0x00AC, // logicalnot 0xae, 0x00AE, // registered 0xaf, 0x00AF, // macron 0xaf, 0x02C9, // macron 0xb0, 0x00B0, // degree 0xb1, 0x00B1, // plusminus 0xb2, 0x00B2, // twosuperior 0xb3, 0x00B3, // threesuperior 0xb4, 0x00B4, // acute 0xb5, 0x00B5, // mu 0xb5, 0x03BC, // mu 0xb6, 0x00B6, // paragraph 0xb7, 0x00B7, // periodcentered 0xb7, 0x2219, // periodcentered 0xb8, 0x00B8, // cedilla 0xb9, 0x00B9, // onesuperior 0xba, 0x00BA, // ordmasculine 0xbb, 0x00BB, // guillemotright 0xbc, 0x00BC, // onequarter 0xbd, 0x00BD, // onehalf 0xbe, 0x00BE, // threequarters 0xbf, 0x00BF, // questiondown 0xc0, 0x00C0, // Agrave 0xc1, 0x00C1, // Aacute 0xc2, 0x00C2, // Acircumflex 0xc3, 0x00C3, // Atilde 0xc4, 0x00C4, // Adieresis 0xc5, 0x00C5, // Aring 0xc6, 0x00C6, // AE 0xc7, 0x00C7, // Ccedilla 0xc8, 0x00C8, // Egrave 0xc9, 0x00C9, // Eacute 0xca, 0x00CA, // Ecircumflex 0xcb, 0x00CB, // Edieresis 0xcc, 0x00CC, // Igrave 0xcd, 0x00CD, // Iacute 0xce, 0x00CE, // Icircumflex 0xcf, 0x00CF, // Idieresis 0xd0, 0x00D0, // Eth 0xd1, 0x00D1, // Ntilde 0xd2, 0x00D2, // Ograve 0xd3, 0x00D3, // Oacute 0xd4, 0x00D4, // Ocircumflex 0xd5, 0x00D5, // Otilde 0xd6, 0x00D6, // Odieresis 0xd7, 0x00D7, // multiply 0xd8, 0x00D8, // Oslash 0xd9, 0x00D9, // Ugrave 0xda, 0x00DA, // Uacute 0xdb, 0x00DB, // Ucircumflex 0xdc, 0x00DC, // Udieresis 0xdd, 0x00DD, // Yacute 0xde, 0x00DE, // Thorn 0xdf, 0x00DF, // germandbls 0xe0, 0x00E0, // agrave 0xe1, 0x00E1, // aacute 0xe2, 0x00E2, // acircumflex 0xe3, 0x00E3, // atilde 0xe4, 0x00E4, // adieresis 0xe5, 0x00E5, // aring 0xe6, 0x00E6, // ae 0xe7, 0x00E7, // ccedilla 0xe8, 0x00E8, // egrave 0xe9, 0x00E9, // eacute 0xea, 0x00EA, // ecircumflex 0xeb, 0x00EB, // edieresis 0xec, 0x00EC, // igrave 0xed, 0x00ED, // iacute 0xee, 0x00EE, // icircumflex 0xef, 0x00EF, // idieresis 0xf0, 0x00F0, // eth 0xf1, 0x00F1, // ntilde 0xf2, 0x00F2, // ograve 0xf3, 0x00F3, // oacute 0xf4, 0x00F4, // ocircumflex 0xf5, 0x00F5, // otilde 0xf6, 0x00F6, // odieresis 0xf7, 0x00F7, // divide 0xf8, 0x00F8, // oslash 0xf9, 0x00F9, // ugrave 0xfa, 0x00FA, // uacute 0xfb, 0x00FB, // ucircumflex 0xfc, 0x00FC, // udieresis 0xfd, 0x00FD, // yacute 0xfe, 0x00FE, // thorn 0xff, 0x00FF, // ydieresis }; public static readonly WinAnsiMapping Mapping = new WinAnsiMapping(); private ushort[] latin1Map; private WinAnsiMapping() { latin1Map = new ushort[256]; for (int i = 0; i < winAnsiEncoding.Length; i += 2) { if (winAnsiEncoding[i + 1] < 256) { latin1Map[winAnsiEncoding[i + 1]] = (char) winAnsiEncoding[i]; } } } public ushort MapCharacter(char c) { if (c > Byte.MaxValue) { return 0; } return latin1Map[c]; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Windows.Browser; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using Microsoft.Scripting.Hosting.Providers; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace Microsoft.Scripting.Silverlight { public static class ErrorFormatter { #region Error HTML Template private const string _errorReportId = "silverlightDlrErrorReport"; private const string _errorMessageId = "silverlightDlrErrorMessage"; private const string _errorSourceId = "silverlightDlrErrorSource"; private const string _errorSourceFileId = "silverlightDlrErrorSourceFile"; private const string _errorSourceCodeId = "silverlightDlrErrorSourceCode"; private const string _errorDetailsId = "silverlightDlrErrorDetails"; private const string _errorTypeId = "silverlightDlrErrorType"; private const string _errorStackTraceId = "silverlightDlrErrorStackTrace"; private const string _errorLineId = "silverlightDlrErrorLine"; // Template for generating error HTML. Parameters are: // 0 - message // 1 - source file // 2 - source code at error location // 3 - error type // 4 - stack trace // 5 - error report id/class // 6 - error message id/class // 7 - error source id/class // 8 - error file id/class // 9 - error source code id/class // 10 - error details id/class // 11 - error type id/class // 12 - error stack trace id/class private static string _errorHtmlTemplate = @" <!-- error report html --> <h2 class=""{6}"" id=""{6}"">{0}</h2> <div class=""{7}""> <div class=""{8}"" id=""{8}"">{1}</div> <code class=""{9}"" id=""{9}""> {2} </code> </div> <div class=""{10}""> <div class=""{11}"" id=""{11}"">{3}</div> <code class=""{12}"" id=""{12}""> {4} </code> </div>"; // template for highlighted error line, inserted into the silverlightDlrErrorSourceCode div in the template above private const string _errorLineTemplate = @"<span id=""{1}"" class=""{1}"">{0}</span>"; #endregion static volatile bool _displayedError = false; static ScriptRuntime _runtime; /// <summary> /// Displays an error /// </summary> /// <param name="targetElementId">HTML id to put error information into</param> /// <param name="e">Exception to get error info out of</param> internal static void DisplayError(string targetElementId, Exception e) { // we only support displaying one error if (_displayedError) { return; } _displayedError = true; // keep track of the runtime if it exists if (DynamicApplication.Current.Engine != null) { _runtime = DynamicApplication.Current.Engine.Runtime; } // show the window in the targetElementId Window.Show(targetElementId); // show the Repl if we can get to the current engine if (DynamicApplication.Current.Engine != null) { Repl.Show(); } // format the Exception string result; try { result = FormatErrorAsHtml(e); } catch (Exception ex) { result = EscapeHtml(ex.ToString()); } // Create a "div" with class/id set as the _errorReportId, and put // formatted exception into it. var report = HtmlPage.Document.CreateElement("div"); report.Id = report.CssClass = _errorReportId; report.SetProperty("innerHTML", result); // Adds a new panel to the "Window", initialize it, and force the panel to be shown. Window.Current.AddPanel("Error Report (" + EscapeHtml(new DynamicExceptionInfo(e).ErrorTypeName) + ")", report); Window.Current.Initialize(); Window.Current.ShowPanel(report.Id); } /// <summary> /// Get the dynamic exception info from the CLR exception, and format /// it with the _errorHtmlTemplate. /// </summary> internal static string FormatErrorAsHtml(Exception e) { // Get information about this exception object DynamicExceptionInfo err = new DynamicExceptionInfo(e); return string.Format( _errorHtmlTemplate, EscapeHtml(err.Message), err.SourceFileName != null ? EscapeHtml(err.SourceFileName) : "", FormatSourceCode(err), EscapeHtml(err.ErrorTypeName), FormatStackTrace(err), _errorReportId, _errorMessageId, _errorSourceId, _errorSourceFileId, _errorSourceCodeId, _errorDetailsId, _errorTypeId, _errorStackTraceId ); } /// <summary> /// Render the line with the error plus some context lines /// </summary> private static string FormatSourceCode(DynamicExceptionInfo err) { var sourceFile = err.SourceFileName; int line = err.SourceLine; if (sourceFile == null || line <= 0) { return ""; } Stream stream = null; try { stream = _runtime.Host.PlatformAdaptationLayer.OpenInputFileStream(sourceFile); if (stream == null) { return ""; } } catch (IOException) { return ""; } int maxLen = (line + 2).ToString().Length; var text = new StringBuilder(); using (StreamReader reader = new StreamReader(stream)) { for (int i = 1; i <= line + 2; ++i) { string lineText = reader.ReadLine(); if (null == lineText) { break; } if (i < line - 2) { continue; } string lineNum = i.ToString(); text.Append("Line ").Append(' ', maxLen - lineNum.Length).Append(lineNum).Append(": "); lineText = EscapeHtml(lineText); if (i == line) { text.AppendFormat(_errorLineTemplate, lineText, _errorLineId); } else { text.Append(lineText); } if (i != line + 2) { text.Append("<br />"); } } } return text.ToString(); } /// <summary> /// Gets the stack trace using whatever information we have available /// </summary> private static string FormatStackTrace(DynamicExceptionInfo err) { Exception ex = err.Exception; if (ex is SyntaxErrorException) { return ""; // no meaningful stack trace for syntax errors } DynamicStackFrame[] dynamicFrames = err.DynamicStackFrames; if (dynamicFrames != null && dynamicFrames.Length > 0) { // We have a stack trace, either dynamic or directly from the exception StringBuilder html = new StringBuilder(); foreach (DynamicStackFrame frame in dynamicFrames) { if (html.Length != 0) { html.Append("<br />"); } html.AppendFormat( " at {0} in {1}, line {2}", EscapeHtml(frame.GetMethodName()), frame.GetFileName() != null ? EscapeHtml(frame.GetFileName()) : null, frame.GetFileLineNumber() ); } if (Settings.ExceptionDetail) { html.Append("<br/>CLR Stack Trace:<br/>"); html.Append(EscapeHtml(ex.StackTrace != null ? ex.StackTrace : ex.ToString())); } return html.ToString(); } return EscapeHtml(ex.StackTrace != null ? ex.StackTrace : ex.ToString()); } /// <summary> /// HtmlEncode, and escape spaces and newlines. /// </summary> public static string EscapeHtml(string str) { return HttpUtility.HtmlEncode(str).Replace(" ", "&nbsp;").Replace("\n", "<br />"); } /// <summary> /// Class used to handle syntax errors and throw the proper exception. /// </summary> public class Sink : ErrorListener { public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity) { throw new SyntaxErrorException(message, HostingHelpers.GetSourceUnit(source), span, errorCode, severity); } } /// <summary> /// Utility class to encapsulate all of the information we retrieve, starting from /// the Exception object. /// </summary> public class DynamicExceptionInfo { public Exception Exception { get { return _exception; } } public DynamicStackFrame[] DynamicStackFrames { get { return _dynamicStackFrames; } } public string SourceFileName { get { return _sourceFileName; } } public int SourceLine { get { return _sourceLine; } } public string Message { get { return _message; } } public string ErrorTypeName { get { return _errorTypeName; } } private Exception _exception; private DynamicStackFrame[] _dynamicStackFrames; private string _sourceFileName, _message, _errorTypeName; private int _sourceLine; public DynamicExceptionInfo(Exception e) { ContractUtils.RequiresNotNull(e, "e"); _exception = e; if (DynamicApplication.Current != null && DynamicApplication.Current.Engine != null && DynamicApplication.Current.Engine.Engine != null) _dynamicStackFrames = ArrayUtils.ToArray(DynamicApplication.Current.Engine.Engine.GetService<ExceptionOperations>().GetStackFrames(e)); // We can get the file name and line number from either the // DynamicStackFrame or from a SyntaxErrorException SyntaxErrorException se = e as SyntaxErrorException; if (null != se) { _sourceFileName = se.GetSymbolDocumentName(); _sourceLine = se.Line; } else if (_dynamicStackFrames != null && _dynamicStackFrames.Length > 0) { _sourceFileName = _dynamicStackFrames[0].GetFileName(); _sourceLine = _dynamicStackFrames[0].GetFileLineNumber(); } // Try to get the ScriptEngine from the source file's extension; // if that fails just use the current ScriptEngine ScriptEngine engine = null; try { if (_sourceFileName != null) { var extension = System.IO.Path.GetExtension(_sourceFileName); _runtime.TryGetEngineByFileExtension(extension, out engine); } else { throw new Exception(); } } catch { if (DynamicApplication.Current.Engine != null) { engine = DynamicApplication.Current.Engine.Engine; } } // If we have the file name and the engine, use ExceptionOperations // to generate the exception message. if (_sourceFileName != null && engine != null) { ExceptionOperations es = engine.GetService<ExceptionOperations>(); es.GetExceptionMessage(_exception, out _message, out _errorTypeName); // Special case error message for needing to upgrade to SL4 } else if (_exception.Message.Contains("Method not found: 'Void System.Threading.Monitor.Enter(System.Object, Boolean ByRef)'")) { _errorTypeName = "Silverlight 4 required"; _message = "Silverlight version error: this Silverlight application requires Silverlight 4 to run, please upgrade."; // Otherwise, create it by hand } else { _errorTypeName = _exception.GetType().Name; _message = _errorTypeName + ": " + _exception.Message; } } } } }
//--------------------------------------------------------------------- // Author: jachymko, Reinhard Lehrbaum // // Description: Base class representing an entry object class. // // Creation Date: 29 Jan 2007 //--------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.DirectoryServices; using System.Reflection; namespace Pscx.DirectoryServices { public class DirectoryEntryType { private readonly bool _isContainer; private readonly string _className; private DirectoryEntry _currentEntry; private List<DirectoryEntryProperty> _properties; protected DirectoryEntryType(string ldapName, bool container) { _className = ldapName; _isContainer = container; } protected DirectoryEntryType(string ldapName) : this(ldapName, false) { } private DirectoryEntryType() { } public ICollection<DirectoryEntryProperty> GetProperties(DirectoryEntry entry) { List<DirectoryEntryProperty> retval = new List<DirectoryEntryProperty>(); _properties = retval; _currentEntry = entry; try { OnCreateProperties(); } finally { _properties = null; _currentEntry = null; } return retval; } public virtual string Name { get { return _className; } } public virtual bool IsContainer { get { return _isContainer; } } public virtual DirectoryEntry NewItem(DirectoryEntry parent, string name) { return parent.Children.Add(NamePrefix + name, _className); } public override string ToString() { return _className; } protected virtual string NamePrefix { get { return "CN="; } } protected virtual void OnCreateProperties() { } protected void AddDNProperty(string name, string attributeName) { AddProperty(new DNSimpleDirectoryEntryProperty(name, attributeName, DirectoryEntryPropertyAccess.ReadWrite)); } protected void AddReadOnlyProperty(string name) { AddSimpleProperty(name, DirectoryEntryPropertyAccess.Read); } protected void AddReadOnlyProperty(string name, string attribute) { AddSimpleProperty(name, attribute, DirectoryEntryPropertyAccess.Read); } protected void AddWriteOnlyProperty(string name) { AddSimpleProperty(name, DirectoryEntryPropertyAccess.Write); } protected void AddSimpleProperty(string name) { AddSimpleProperty(name, name); } protected void AddSimpleProperty(string name, string attributeName) { AddSimpleProperty(name, attributeName, DirectoryEntryPropertyAccess.ReadWrite); } protected void AddSimpleProperty(string name, DirectoryEntryPropertyAccess access) { AddSimpleProperty(name, name, access); } protected void AddSimpleProperty(string name, string attributeName, DirectoryEntryPropertyAccess access) { AddProperty(new SimpleDirectoryEntryProperty(name, attributeName, access)); } protected void AddSetMethodProperty(string name, string method) { AddProperty(new SetMethodDirectoryEntryProperty(name, method)); } protected void AddProperty(DirectoryEntryProperty property) { if (_properties == null) { throw new InvalidOperationException(); } property.Entry = _currentEntry; _properties.Add(property); } internal DirectoryEntry ProcessedEntry { get { return _currentEntry; } } static DirectoryEntryType() { _classes = new Dictionary<String, DirectoryEntryType>(StringComparer.OrdinalIgnoreCase); BuiltinDomain = RegisterContainer("builtinDomain"); Computer = Register("computer"); Contact = Register("contact"); Container = RegisterContainer("container"); DomainDns = RegisterContainer("domainDNS"); Group = Register(new ActiveDirectory.GroupClass()); InetOrgPerson = Register("inetOrgPerson"); LostAndFound = RegisterContainer("lostAndFound"); MsExchSystemObjectsContainer = RegisterContainer("msExchSystemObjectsContainer"); MsmqRecipient = Register("msMQ-Custom-Recipient"); OrganizationalUnit = Register(new ActiveDirectory.OrganizationalUnitClass()); Printer = Register("printQueue"); User = Register(new ActiveDirectory.UserClass()); Volume = Register("volume"); } public static readonly DirectoryEntryType BuiltinDomain; public static readonly DirectoryEntryType Computer; public static readonly DirectoryEntryType Contact; public static readonly DirectoryEntryType Container; public static readonly DirectoryEntryType DomainDns; public static readonly DirectoryEntryType Group; public static readonly DirectoryEntryType InetOrgPerson; public static readonly DirectoryEntryType LostAndFound; public static readonly DirectoryEntryType MsExchSystemObjectsContainer; public static readonly DirectoryEntryType MsmqRecipient; public static readonly DirectoryEntryType OrganizationalUnit; public static readonly DirectoryEntryType Printer; public static readonly DirectoryEntryType User; public static readonly DirectoryEntryType Volume; public static DirectoryEntryType FromClassName(string name) { if (_classes.ContainsKey(name)) { return _classes[name]; } if (!string.IsNullOrEmpty(name)) { return new DirectoryEntryType(name, false); } return null; } public static DirectoryEntryType FindByPrefix(string prefix) { List<String> matches = new List<string>(); foreach (string name in _classes.Keys) { if (name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { matches.Add(name); } } if (matches.Count != 1) { return null; } return _classes[matches[0]]; } public static DirectoryEntry NewItem(DirectoryEntry parent, string name, string classNamePrefix) { PscxArgumentException.ThrowIfIsNull(parent, "parent"); DirectoryEntryType entryType = FindByPrefix(classNamePrefix); if (entryType == null) { return null; } return entryType.NewItem(parent, name); } public static ICollection<DirectoryEntryProperty> GetRawProperties(DirectoryEntry entry) { return RawView.GetProperties(entry); } protected static DirectoryEntryType Register(string name) { return Register(new DirectoryEntryType(name, false)); } protected static DirectoryEntryType RegisterContainer(string name) { return Register(new DirectoryEntryType(name, true)); } protected static DirectoryEntryType Register(DirectoryEntryType entryClass) { return _classes[entryClass._className] = entryClass; } private static DirectoryEntryType RawView { get { if (_rawView == null) { _rawView = new GenericDirectoryEntryType(); } return _rawView; } } [ThreadStatic] private static DirectoryEntryType _rawView; private static readonly Dictionary<String, DirectoryEntryType> _classes; class GenericDirectoryEntryType : DirectoryEntryType { protected override void OnCreateProperties() { using (DirectoryEntry schemaEntry = ProcessedEntry.SchemaEntry) { ICollection mandatory = GetSchemaEntryPropertyAsCollection(schemaEntry, "MandatoryProperties"); foreach (string name in mandatory) { AddSimpleProperty(name); } ICollection optional = GetSchemaEntryPropertyAsCollection(schemaEntry, "OptionalProperties"); foreach (string name in optional) { AddSimpleProperty(name); } } } private ICollection GetSchemaEntryPropertyAsCollection(DirectoryEntry schemaEntry, string member) { object native = schemaEntry.NativeObject; Type nativeType = native.GetType(); object retval = nativeType.InvokeMember( member, BindingFlags.Public | BindingFlags.GetProperty, Type.DefaultBinder, native, new object[0]); return retval as ICollection; } } } }
namespace android.content { [global::MonoJavaBridge.JavaClass()] public partial class ContextWrapper : android.content.Context { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ContextWrapper() { InitJNI(); } protected ContextWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getClassLoader1435; public override global::java.lang.ClassLoader getClassLoader() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getClassLoader1435)) as java.lang.ClassLoader; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getClassLoader1435)) as java.lang.ClassLoader; } internal static global::MonoJavaBridge.MethodId _checkPermission1436; public override int checkPermission(java.lang.String arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContextWrapper._checkPermission1436, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._checkPermission1436, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _getResources1437; public override global::android.content.res.Resources getResources() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getResources1437)) as android.content.res.Resources; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getResources1437)) as android.content.res.Resources; } internal static global::MonoJavaBridge.MethodId _getPackageName1438; public override global::java.lang.String getPackageName() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getPackageName1438)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getPackageName1438)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _attachBaseContext1439; protected virtual void attachBaseContext(android.content.Context arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._attachBaseContext1439, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._attachBaseContext1439, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getBaseContext1440; public virtual global::android.content.Context getBaseContext() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getBaseContext1440)) as android.content.Context; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getBaseContext1440)) as android.content.Context; } internal static global::MonoJavaBridge.MethodId _getAssets1441; public override global::android.content.res.AssetManager getAssets() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getAssets1441)) as android.content.res.AssetManager; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getAssets1441)) as android.content.res.AssetManager; } internal static global::MonoJavaBridge.MethodId _getPackageManager1442; public override global::android.content.pm.PackageManager getPackageManager() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getPackageManager1442)) as android.content.pm.PackageManager; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getPackageManager1442)) as android.content.pm.PackageManager; } internal static global::MonoJavaBridge.MethodId _getContentResolver1443; public override global::android.content.ContentResolver getContentResolver() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getContentResolver1443)) as android.content.ContentResolver; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getContentResolver1443)) as android.content.ContentResolver; } internal static global::MonoJavaBridge.MethodId _getMainLooper1444; public override global::android.os.Looper getMainLooper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getMainLooper1444)) as android.os.Looper; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getMainLooper1444)) as android.os.Looper; } internal static global::MonoJavaBridge.MethodId _getApplicationContext1445; public override global::android.content.Context getApplicationContext() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getApplicationContext1445)) as android.content.Context; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getApplicationContext1445)) as android.content.Context; } internal static global::MonoJavaBridge.MethodId _setTheme1446; public override void setTheme(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._setTheme1446, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._setTheme1446, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getTheme1447; public override global::android.content.res.Resources.Theme getTheme() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getTheme1447)) as android.content.res.Resources.Theme; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getTheme1447)) as android.content.res.Resources.Theme; } internal static global::MonoJavaBridge.MethodId _getApplicationInfo1448; public override global::android.content.pm.ApplicationInfo getApplicationInfo() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getApplicationInfo1448)) as android.content.pm.ApplicationInfo; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getApplicationInfo1448)) as android.content.pm.ApplicationInfo; } internal static global::MonoJavaBridge.MethodId _getPackageResourcePath1449; public override global::java.lang.String getPackageResourcePath() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getPackageResourcePath1449)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getPackageResourcePath1449)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getPackageCodePath1450; public override global::java.lang.String getPackageCodePath() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getPackageCodePath1450)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getPackageCodePath1450)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getSharedPreferences1451; public override global::android.content.SharedPreferences getSharedPreferences(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.SharedPreferences>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getSharedPreferences1451, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.SharedPreferences; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.SharedPreferences>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getSharedPreferences1451, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.SharedPreferences; } internal static global::MonoJavaBridge.MethodId _openFileInput1452; public override global::java.io.FileInputStream openFileInput(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._openFileInput1452, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.FileInputStream; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._openFileInput1452, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.FileInputStream; } internal static global::MonoJavaBridge.MethodId _openFileOutput1453; public override global::java.io.FileOutputStream openFileOutput(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._openFileOutput1453, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.io.FileOutputStream; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._openFileOutput1453, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.io.FileOutputStream; } internal static global::MonoJavaBridge.MethodId _deleteFile1454; public override bool deleteFile(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper._deleteFile1454, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._deleteFile1454, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getFileStreamPath1455; public override global::java.io.File getFileStreamPath(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getFileStreamPath1455, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.File; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getFileStreamPath1455, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.File; } internal static global::MonoJavaBridge.MethodId _fileList1456; public override global::java.lang.String[] fileList() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._fileList1456)) as java.lang.String[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._fileList1456)) as java.lang.String[]; } internal static global::MonoJavaBridge.MethodId _getFilesDir1457; public override global::java.io.File getFilesDir() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getFilesDir1457)) as java.io.File; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getFilesDir1457)) as java.io.File; } internal static global::MonoJavaBridge.MethodId _getExternalFilesDir1458; public override global::java.io.File getExternalFilesDir(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getExternalFilesDir1458, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.File; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getExternalFilesDir1458, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.File; } internal static global::MonoJavaBridge.MethodId _getCacheDir1459; public override global::java.io.File getCacheDir() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getCacheDir1459)) as java.io.File; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getCacheDir1459)) as java.io.File; } internal static global::MonoJavaBridge.MethodId _getExternalCacheDir1460; public override global::java.io.File getExternalCacheDir() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getExternalCacheDir1460)) as java.io.File; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getExternalCacheDir1460)) as java.io.File; } internal static global::MonoJavaBridge.MethodId _getDir1461; public override global::java.io.File getDir(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getDir1461, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.io.File; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getDir1461, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.io.File; } internal static global::MonoJavaBridge.MethodId _openOrCreateDatabase1462; public override global::android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String arg0, int arg1, android.database.sqlite.SQLiteDatabase.CursorFactory arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._openOrCreateDatabase1462, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.database.sqlite.SQLiteDatabase; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._openOrCreateDatabase1462, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.database.sqlite.SQLiteDatabase; } internal static global::MonoJavaBridge.MethodId _deleteDatabase1463; public override bool deleteDatabase(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper._deleteDatabase1463, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._deleteDatabase1463, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDatabasePath1464; public override global::java.io.File getDatabasePath(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getDatabasePath1464, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.File; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getDatabasePath1464, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.File; } internal static global::MonoJavaBridge.MethodId _databaseList1465; public override global::java.lang.String[] databaseList() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._databaseList1465)) as java.lang.String[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._databaseList1465)) as java.lang.String[]; } internal static global::MonoJavaBridge.MethodId _getWallpaper1466; public override global::android.graphics.drawable.Drawable getWallpaper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getWallpaper1466)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getWallpaper1466)) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _peekWallpaper1467; public override global::android.graphics.drawable.Drawable peekWallpaper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._peekWallpaper1467)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._peekWallpaper1467)) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _getWallpaperDesiredMinimumWidth1468; public override int getWallpaperDesiredMinimumWidth() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContextWrapper._getWallpaperDesiredMinimumWidth1468); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getWallpaperDesiredMinimumWidth1468); } internal static global::MonoJavaBridge.MethodId _getWallpaperDesiredMinimumHeight1469; public override int getWallpaperDesiredMinimumHeight() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContextWrapper._getWallpaperDesiredMinimumHeight1469); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getWallpaperDesiredMinimumHeight1469); } internal static global::MonoJavaBridge.MethodId _setWallpaper1470; public override void setWallpaper(java.io.InputStream arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._setWallpaper1470, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._setWallpaper1470, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setWallpaper1471; public override void setWallpaper(android.graphics.Bitmap arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._setWallpaper1471, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._setWallpaper1471, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _clearWallpaper1472; public override void clearWallpaper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._clearWallpaper1472); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._clearWallpaper1472); } internal static global::MonoJavaBridge.MethodId _startActivity1473; public override void startActivity(android.content.Intent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._startActivity1473, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._startActivity1473, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _startIntentSender1474; public override void startIntentSender(android.content.IntentSender arg0, android.content.Intent arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._startIntentSender1474, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._startIntentSender1474, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } internal static global::MonoJavaBridge.MethodId _sendBroadcast1475; public override void sendBroadcast(android.content.Intent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._sendBroadcast1475, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._sendBroadcast1475, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _sendBroadcast1476; public override void sendBroadcast(android.content.Intent arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._sendBroadcast1476, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._sendBroadcast1476, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _sendOrderedBroadcast1477; public override void sendOrderedBroadcast(android.content.Intent arg0, java.lang.String arg1, android.content.BroadcastReceiver arg2, android.os.Handler arg3, int arg4, java.lang.String arg5, android.os.Bundle arg6) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._sendOrderedBroadcast1477, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._sendOrderedBroadcast1477, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6)); } internal static global::MonoJavaBridge.MethodId _sendOrderedBroadcast1478; public override void sendOrderedBroadcast(android.content.Intent arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._sendOrderedBroadcast1478, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._sendOrderedBroadcast1478, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _sendStickyBroadcast1479; public override void sendStickyBroadcast(android.content.Intent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._sendStickyBroadcast1479, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._sendStickyBroadcast1479, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _sendStickyOrderedBroadcast1480; public override void sendStickyOrderedBroadcast(android.content.Intent arg0, android.content.BroadcastReceiver arg1, android.os.Handler arg2, int arg3, java.lang.String arg4, android.os.Bundle arg5) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._sendStickyOrderedBroadcast1480, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._sendStickyOrderedBroadcast1480, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } internal static global::MonoJavaBridge.MethodId _removeStickyBroadcast1481; public override void removeStickyBroadcast(android.content.Intent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._removeStickyBroadcast1481, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._removeStickyBroadcast1481, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _registerReceiver1482; public override global::android.content.Intent registerReceiver(android.content.BroadcastReceiver arg0, android.content.IntentFilter arg1, java.lang.String arg2, android.os.Handler arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._registerReceiver1482, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.content.Intent; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._registerReceiver1482, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.content.Intent; } internal static global::MonoJavaBridge.MethodId _registerReceiver1483; public override global::android.content.Intent registerReceiver(android.content.BroadcastReceiver arg0, android.content.IntentFilter arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._registerReceiver1483, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.Intent; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._registerReceiver1483, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.Intent; } internal static global::MonoJavaBridge.MethodId _unregisterReceiver1484; public override void unregisterReceiver(android.content.BroadcastReceiver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._unregisterReceiver1484, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._unregisterReceiver1484, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _startService1485; public override global::android.content.ComponentName startService(android.content.Intent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._startService1485, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.ComponentName; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._startService1485, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.ComponentName; } internal static global::MonoJavaBridge.MethodId _stopService1486; public override bool stopService(android.content.Intent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper._stopService1486, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._stopService1486, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _bindService1487; public override bool bindService(android.content.Intent arg0, android.content.ServiceConnection arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper._bindService1487, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._bindService1487, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _unbindService1488; public override void unbindService(android.content.ServiceConnection arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._unbindService1488, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._unbindService1488, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _startInstrumentation1489; public override bool startInstrumentation(android.content.ComponentName arg0, java.lang.String arg1, android.os.Bundle arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper._startInstrumentation1489, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._startInstrumentation1489, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _getSystemService1490; public override global::java.lang.Object getSystemService(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._getSystemService1490, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._getSystemService1490, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _checkCallingPermission1491; public override int checkCallingPermission(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContextWrapper._checkCallingPermission1491, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._checkCallingPermission1491, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _checkCallingOrSelfPermission1492; public override int checkCallingOrSelfPermission(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContextWrapper._checkCallingOrSelfPermission1492, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._checkCallingOrSelfPermission1492, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _enforcePermission1493; public override void enforcePermission(java.lang.String arg0, int arg1, int arg2, java.lang.String arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._enforcePermission1493, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._enforcePermission1493, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _enforceCallingPermission1494; public override void enforceCallingPermission(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._enforceCallingPermission1494, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._enforceCallingPermission1494, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _enforceCallingOrSelfPermission1495; public override void enforceCallingOrSelfPermission(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._enforceCallingOrSelfPermission1495, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._enforceCallingOrSelfPermission1495, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _grantUriPermission1496; public override void grantUriPermission(java.lang.String arg0, android.net.Uri arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._grantUriPermission1496, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._grantUriPermission1496, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _revokeUriPermission1497; public override void revokeUriPermission(android.net.Uri arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._revokeUriPermission1497, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._revokeUriPermission1497, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _checkUriPermission1498; public override int checkUriPermission(android.net.Uri arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContextWrapper._checkUriPermission1498, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._checkUriPermission1498, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _checkUriPermission1499; public override int checkUriPermission(android.net.Uri arg0, java.lang.String arg1, java.lang.String arg2, int arg3, int arg4, int arg5) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContextWrapper._checkUriPermission1499, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._checkUriPermission1499, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } internal static global::MonoJavaBridge.MethodId _checkCallingUriPermission1500; public override int checkCallingUriPermission(android.net.Uri arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContextWrapper._checkCallingUriPermission1500, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._checkCallingUriPermission1500, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _checkCallingOrSelfUriPermission1501; public override int checkCallingOrSelfUriPermission(android.net.Uri arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContextWrapper._checkCallingOrSelfUriPermission1501, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._checkCallingOrSelfUriPermission1501, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _enforceUriPermission1502; public override void enforceUriPermission(android.net.Uri arg0, int arg1, int arg2, int arg3, java.lang.String arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._enforceUriPermission1502, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._enforceUriPermission1502, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } internal static global::MonoJavaBridge.MethodId _enforceUriPermission1503; public override void enforceUriPermission(android.net.Uri arg0, java.lang.String arg1, java.lang.String arg2, int arg3, int arg4, int arg5, java.lang.String arg6) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._enforceUriPermission1503, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._enforceUriPermission1503, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6)); } internal static global::MonoJavaBridge.MethodId _enforceCallingUriPermission1504; public override void enforceCallingUriPermission(android.net.Uri arg0, int arg1, java.lang.String arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._enforceCallingUriPermission1504, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._enforceCallingUriPermission1504, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _enforceCallingOrSelfUriPermission1505; public override void enforceCallingOrSelfUriPermission(android.net.Uri arg0, int arg1, java.lang.String arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContextWrapper._enforceCallingOrSelfUriPermission1505, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._enforceCallingOrSelfUriPermission1505, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _createPackageContext1506; public override global::android.content.Context createPackageContext(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContextWrapper._createPackageContext1506, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.Context; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._createPackageContext1506, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.Context; } internal static global::MonoJavaBridge.MethodId _isRestricted1507; public override bool isRestricted() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper._isRestricted1507); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._isRestricted1507); } internal static global::MonoJavaBridge.MethodId _ContextWrapper1508; public ContextWrapper(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.ContextWrapper.staticClass, global::android.content.ContextWrapper._ContextWrapper1508, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.ContextWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/ContextWrapper")); global::android.content.ContextWrapper._getClassLoader1435 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getClassLoader", "()Ljava/lang/ClassLoader;"); global::android.content.ContextWrapper._checkPermission1436 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "checkPermission", "(Ljava/lang/String;II)I"); global::android.content.ContextWrapper._getResources1437 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getResources", "()Landroid/content/res/Resources;"); global::android.content.ContextWrapper._getPackageName1438 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getPackageName", "()Ljava/lang/String;"); global::android.content.ContextWrapper._attachBaseContext1439 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "attachBaseContext", "(Landroid/content/Context;)V"); global::android.content.ContextWrapper._getBaseContext1440 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getBaseContext", "()Landroid/content/Context;"); global::android.content.ContextWrapper._getAssets1441 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getAssets", "()Landroid/content/res/AssetManager;"); global::android.content.ContextWrapper._getPackageManager1442 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getPackageManager", "()Landroid/content/pm/PackageManager;"); global::android.content.ContextWrapper._getContentResolver1443 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getContentResolver", "()Landroid/content/ContentResolver;"); global::android.content.ContextWrapper._getMainLooper1444 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getMainLooper", "()Landroid/os/Looper;"); global::android.content.ContextWrapper._getApplicationContext1445 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getApplicationContext", "()Landroid/content/Context;"); global::android.content.ContextWrapper._setTheme1446 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "setTheme", "(I)V"); global::android.content.ContextWrapper._getTheme1447 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getTheme", "()Landroid/content/res/Resources$Theme;"); global::android.content.ContextWrapper._getApplicationInfo1448 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getApplicationInfo", "()Landroid/content/pm/ApplicationInfo;"); global::android.content.ContextWrapper._getPackageResourcePath1449 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getPackageResourcePath", "()Ljava/lang/String;"); global::android.content.ContextWrapper._getPackageCodePath1450 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getPackageCodePath", "()Ljava/lang/String;"); global::android.content.ContextWrapper._getSharedPreferences1451 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getSharedPreferences", "(Ljava/lang/String;I)Landroid/content/SharedPreferences;"); global::android.content.ContextWrapper._openFileInput1452 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "openFileInput", "(Ljava/lang/String;)Ljava/io/FileInputStream;"); global::android.content.ContextWrapper._openFileOutput1453 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "openFileOutput", "(Ljava/lang/String;I)Ljava/io/FileOutputStream;"); global::android.content.ContextWrapper._deleteFile1454 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "deleteFile", "(Ljava/lang/String;)Z"); global::android.content.ContextWrapper._getFileStreamPath1455 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getFileStreamPath", "(Ljava/lang/String;)Ljava/io/File;"); global::android.content.ContextWrapper._fileList1456 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "fileList", "()[Ljava/lang/String;"); global::android.content.ContextWrapper._getFilesDir1457 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getFilesDir", "()Ljava/io/File;"); global::android.content.ContextWrapper._getExternalFilesDir1458 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;"); global::android.content.ContextWrapper._getCacheDir1459 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getCacheDir", "()Ljava/io/File;"); global::android.content.ContextWrapper._getExternalCacheDir1460 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getExternalCacheDir", "()Ljava/io/File;"); global::android.content.ContextWrapper._getDir1461 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getDir", "(Ljava/lang/String;I)Ljava/io/File;"); global::android.content.ContextWrapper._openOrCreateDatabase1462 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "openOrCreateDatabase", "(Ljava/lang/String;ILandroid/database/sqlite/SQLiteDatabase$CursorFactory;)Landroid/database/sqlite/SQLiteDatabase;"); global::android.content.ContextWrapper._deleteDatabase1463 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "deleteDatabase", "(Ljava/lang/String;)Z"); global::android.content.ContextWrapper._getDatabasePath1464 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getDatabasePath", "(Ljava/lang/String;)Ljava/io/File;"); global::android.content.ContextWrapper._databaseList1465 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "databaseList", "()[Ljava/lang/String;"); global::android.content.ContextWrapper._getWallpaper1466 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getWallpaper", "()Landroid/graphics/drawable/Drawable;"); global::android.content.ContextWrapper._peekWallpaper1467 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "peekWallpaper", "()Landroid/graphics/drawable/Drawable;"); global::android.content.ContextWrapper._getWallpaperDesiredMinimumWidth1468 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getWallpaperDesiredMinimumWidth", "()I"); global::android.content.ContextWrapper._getWallpaperDesiredMinimumHeight1469 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getWallpaperDesiredMinimumHeight", "()I"); global::android.content.ContextWrapper._setWallpaper1470 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "setWallpaper", "(Ljava/io/InputStream;)V"); global::android.content.ContextWrapper._setWallpaper1471 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "setWallpaper", "(Landroid/graphics/Bitmap;)V"); global::android.content.ContextWrapper._clearWallpaper1472 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "clearWallpaper", "()V"); global::android.content.ContextWrapper._startActivity1473 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "startActivity", "(Landroid/content/Intent;)V"); global::android.content.ContextWrapper._startIntentSender1474 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "startIntentSender", "(Landroid/content/IntentSender;Landroid/content/Intent;III)V"); global::android.content.ContextWrapper._sendBroadcast1475 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "sendBroadcast", "(Landroid/content/Intent;)V"); global::android.content.ContextWrapper._sendBroadcast1476 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "sendBroadcast", "(Landroid/content/Intent;Ljava/lang/String;)V"); global::android.content.ContextWrapper._sendOrderedBroadcast1477 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "sendOrderedBroadcast", "(Landroid/content/Intent;Ljava/lang/String;Landroid/content/BroadcastReceiver;Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V"); global::android.content.ContextWrapper._sendOrderedBroadcast1478 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "sendOrderedBroadcast", "(Landroid/content/Intent;Ljava/lang/String;)V"); global::android.content.ContextWrapper._sendStickyBroadcast1479 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "sendStickyBroadcast", "(Landroid/content/Intent;)V"); global::android.content.ContextWrapper._sendStickyOrderedBroadcast1480 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "sendStickyOrderedBroadcast", "(Landroid/content/Intent;Landroid/content/BroadcastReceiver;Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V"); global::android.content.ContextWrapper._removeStickyBroadcast1481 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "removeStickyBroadcast", "(Landroid/content/Intent;)V"); global::android.content.ContextWrapper._registerReceiver1482 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;Ljava/lang/String;Landroid/os/Handler;)Landroid/content/Intent;"); global::android.content.ContextWrapper._registerReceiver1483 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;"); global::android.content.ContextWrapper._unregisterReceiver1484 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "unregisterReceiver", "(Landroid/content/BroadcastReceiver;)V"); global::android.content.ContextWrapper._startService1485 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "startService", "(Landroid/content/Intent;)Landroid/content/ComponentName;"); global::android.content.ContextWrapper._stopService1486 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "stopService", "(Landroid/content/Intent;)Z"); global::android.content.ContextWrapper._bindService1487 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "bindService", "(Landroid/content/Intent;Landroid/content/ServiceConnection;I)Z"); global::android.content.ContextWrapper._unbindService1488 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "unbindService", "(Landroid/content/ServiceConnection;)V"); global::android.content.ContextWrapper._startInstrumentation1489 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "startInstrumentation", "(Landroid/content/ComponentName;Ljava/lang/String;Landroid/os/Bundle;)Z"); global::android.content.ContextWrapper._getSystemService1490 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); global::android.content.ContextWrapper._checkCallingPermission1491 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "checkCallingPermission", "(Ljava/lang/String;)I"); global::android.content.ContextWrapper._checkCallingOrSelfPermission1492 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "checkCallingOrSelfPermission", "(Ljava/lang/String;)I"); global::android.content.ContextWrapper._enforcePermission1493 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "enforcePermission", "(Ljava/lang/String;IILjava/lang/String;)V"); global::android.content.ContextWrapper._enforceCallingPermission1494 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "enforceCallingPermission", "(Ljava/lang/String;Ljava/lang/String;)V"); global::android.content.ContextWrapper._enforceCallingOrSelfPermission1495 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "enforceCallingOrSelfPermission", "(Ljava/lang/String;Ljava/lang/String;)V"); global::android.content.ContextWrapper._grantUriPermission1496 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "grantUriPermission", "(Ljava/lang/String;Landroid/net/Uri;I)V"); global::android.content.ContextWrapper._revokeUriPermission1497 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "revokeUriPermission", "(Landroid/net/Uri;I)V"); global::android.content.ContextWrapper._checkUriPermission1498 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "checkUriPermission", "(Landroid/net/Uri;III)I"); global::android.content.ContextWrapper._checkUriPermission1499 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "checkUriPermission", "(Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;III)I"); global::android.content.ContextWrapper._checkCallingUriPermission1500 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "checkCallingUriPermission", "(Landroid/net/Uri;I)I"); global::android.content.ContextWrapper._checkCallingOrSelfUriPermission1501 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "checkCallingOrSelfUriPermission", "(Landroid/net/Uri;I)I"); global::android.content.ContextWrapper._enforceUriPermission1502 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "enforceUriPermission", "(Landroid/net/Uri;IIILjava/lang/String;)V"); global::android.content.ContextWrapper._enforceUriPermission1503 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "enforceUriPermission", "(Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;IIILjava/lang/String;)V"); global::android.content.ContextWrapper._enforceCallingUriPermission1504 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "enforceCallingUriPermission", "(Landroid/net/Uri;ILjava/lang/String;)V"); global::android.content.ContextWrapper._enforceCallingOrSelfUriPermission1505 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "enforceCallingOrSelfUriPermission", "(Landroid/net/Uri;ILjava/lang/String;)V"); global::android.content.ContextWrapper._createPackageContext1506 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "createPackageContext", "(Ljava/lang/String;I)Landroid/content/Context;"); global::android.content.ContextWrapper._isRestricted1507 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "isRestricted", "()Z"); global::android.content.ContextWrapper._ContextWrapper1508 = @__env.GetMethodIDNoThrow(global::android.content.ContextWrapper.staticClass, "<init>", "(Landroid/content/Context;)V"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Sql.Fluent { using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.Sql.Fluent.Models; using Microsoft.Azure.Management.Sql.Fluent.SqlEncryptionProtector.Update; /// <summary> /// Implementation for SqlEncryptionProtector interface. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LnNxbC5pbXBsZW1lbnRhdGlvbi5TcWxFbmNyeXB0aW9uUHJvdGVjdG9ySW1wbA== internal partial class SqlEncryptionProtectorImpl : ChildResource< Models.EncryptionProtectorInner, Microsoft.Azure.Management.Sql.Fluent.SqlServerImpl, Microsoft.Azure.Management.Sql.Fluent.ISqlServer>, ISqlEncryptionProtector, IUpdate { private ISqlManager sqlServerManager; private string resourceGroupName; private string sqlServerName; private string serverKeyName; /// <summary> /// Creates an instance of external child resource in-memory. /// </summary> /// <param name="parent">Reference to the parent of this external child resource.</param> /// <param name="innerObject">Reference to the inner object representing this external child resource.</param> /// <param name="sqlServerManager">Reference to the SQL server manager that accesses firewall rule operations.</param> ///GENMHASH:037B6E72FFBB7224CDF82D509814DF07:925E12E2AB778ADEA6FAE0AE9F9184C7 internal SqlEncryptionProtectorImpl(SqlServerImpl parent, EncryptionProtectorInner innerObject, ISqlManager sqlServerManager) : base(innerObject, parent) { this.sqlServerManager = sqlServerManager; this.resourceGroupName = parent.ResourceGroupName; this.sqlServerName = parent.Name; this.serverKeyName = innerObject?.Name; } /// <summary> /// Creates an instance of external child resource in-memory. /// </summary> /// <param name="resourceGroupName">The resource group name.</param> /// <param name="sqlServerName">The parent SQL server name.</param> /// <param name="innerObject">Reference to the inner object representing this external child resource.</param> /// <param name="sqlServerManager">Reference to the SQL server manager that accesses firewall rule operations.</param> ///GENMHASH:B9BEF73056A0E29FFD8BF2E062D7BC15:43162FE085CFEAFDA76E5D4BC4A00355 internal SqlEncryptionProtectorImpl(string resourceGroupName, string sqlServerName, EncryptionProtectorInner innerObject, ISqlManager sqlServerManager) : base(innerObject, null) { this.sqlServerManager = sqlServerManager; this.resourceGroupName = resourceGroupName; this.sqlServerName = sqlServerName; this.serverKeyName = innerObject?.Name; } /// <summary> /// Creates an instance of external child resource in-memory. /// </summary> /// <param name="innerObject">Reference to the inner object representing this external child resource.</param> /// <param name="sqlServerManager">Reference to the SQL server manager that accesses firewall rule operations.</param> ///GENMHASH:4DD6445361F09E0B185DE0E8D24170D3:81D0EDB620000F6B86DC1403C1548E6A internal SqlEncryptionProtectorImpl(EncryptionProtectorInner innerObject, ISqlManager sqlServerManager) : base(innerObject, null) { this.sqlServerManager = sqlServerManager; if (innerObject?.Id != null) { ResourceId resourceId = ResourceId.FromString(innerObject.Id); this.resourceGroupName = resourceId.ResourceGroupName; this.sqlServerName = resourceId.Parent.Name; } this.serverKeyName = innerObject?.Name; } public override string Name() { return this.Inner?.Name; } ///GENMHASH:E9EDBD2E8DC2C547D1386A58778AA6B9:7EBD4102FEBFB0AD7091EA1ACBD84F8B public string ResourceGroupName() { return this.resourceGroupName; } ///GENMHASH:6485A67119B54B835368ADA812A96C10:EEFF62BBC201203BB09A9D9FE63B14EC public string ServerKeyName() { return this.Inner.ServerKeyName; } ///GENMHASH:61F5809AB3B985C61AC40B98B1FBC47E:03B7E74B9CEC907229FC7E3E3FC8EFC4 public string SqlServerName() { return this.serverKeyName; } ///GENMHASH:C4C0D4751CA4E1904C31CE6DF0B02AC3:B30E59DD4D927FB508DCE8588A7B6C5E public string Kind() { return this.Inner.Kind; } ///GENMHASH:8F04665E49050E6C5BD8AE7B8E51D285:48C470FF98C85D0D802E5FBBD537EFBE public string Thumbprint() { return this.Inner.Thumbprint; } ///GENMHASH:6BCE517E09457FF033728269C8936E64:40A980295F5EA8FF8304DA8C06E899BF public SqlEncryptionProtectorImpl Update() { return this; } ///GENMHASH:39E79EEEBE800C0263D7785D2CDD0C8F:AA25005E7A9BAF367EA281FE0DB49192 public string Uri() { return this.Inner.Uri; } ///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:2EA6F22A1E9075415416C51D51B2ED7C protected async Task<Models.EncryptionProtectorInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await this.sqlServerManager.Inner.EncryptionProtectors .GetAsync(this.resourceGroupName, this.sqlServerName, cancellationToken); } ///GENMHASH:7A0398C4BB6EBF42CC817EE638D40E9C:2DC6B3BEB4C8A428A0339820143BFEB3 public string ParentId() { var resourceId = ResourceId.FromString(this.Id()); return resourceId?.Parent?.Id; } ///GENMHASH:6A5C79A9C5D9A772C2F79EEC7408E4A4:13FE8C3F53ABBA3F908A2B33CEEFD2C4 public Models.ServerKeyType ServerKeyType() { return Models.ServerKeyType.Parse(this.Inner.ServerKeyType); } ///GENMHASH:2688473C4BAFA54B9FD7ABA11C3C5F8B:D566CA13B0B70C2E92E17CAEA81BBA31 public SqlEncryptionProtectorImpl WithServiceManagedServerKey() { this.Inner.ServerKeyName = "ServiceManaged"; this.Inner.ServerKeyType = Models.ServerKeyType.ServiceManaged.Value; return this; } ///GENMHASH:E24A9768E91CD60E963E43F00AA1FDFE:AC7D8FFF4C733C02A85F39DEEAB80B76 public Task DeleteResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException("Operation not supported"); } ///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:899F2B088BBBD76CCBC31221756265BC public string Id() { return this.Inner.Id; } ///GENMHASH:BF5A6EF11B034B3808270F4EF75EB5E0:12F32780E905DD94F4F7DE7FBFB88FCE public SqlEncryptionProtectorImpl WithAzureKeyVaultServerKey(string serverKeyName) { this.Inner.ServerKeyName = serverKeyName; this.Inner.ServerKeyType = Models.ServerKeyType.AzureKeyVault.Value; return this; } ///GENMHASH:6A2970A94B2DD4A859B00B9B9D9691AD:6475F0E6B085A35B081FA09FFCBDDBF8 public Region Region() { return Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region.Create(this.Inner.Location); } ///GENMHASH:507A92D4DCD93CE9595A78198DEBDFCF:4C4C4336C86119672D7AD1E0D4BD29CB public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlEncryptionProtector> UpdateResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await CreateResourceAsync(cancellationToken); } ///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:06F8F4D881AC3D94F49CECB6153B5A83 public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlEncryptionProtector> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { var encryptionProtectorInner = await this.sqlServerManager.Inner.EncryptionProtectors .CreateOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.Inner, cancellationToken); this.SetInner(encryptionProtectorInner); return this; } public ISqlEncryptionProtector Refresh() { return Extensions.Synchronize(() => this.RefreshAsync()); } public async Task<ISqlEncryptionProtector> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken)) { this.SetInner(await this.GetInnerAsync(cancellationToken)); return this; } public ISqlEncryptionProtector Apply() { return Extensions.Synchronize(() => this.ApplyAsync()); } public async Task<ISqlEncryptionProtector> ApplyAsync(CancellationToken cancellationToken = default(CancellationToken), bool multiThreaded = true) { return await this.UpdateResourceAsync(cancellationToken); } } }
#region Imported Types using DeviceSQL.SQLTypes.ROC.Data; using Microsoft.SqlServer.Server; using System; using System.Data.SqlTypes; using System.IO; using System.Linq; #endregion namespace DeviceSQL.SQLTypes.ROC { [Serializable()] [SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, IsFixedLength = false, MaxByteSize = 27)] public struct EventRecord : INullable, IBinarySerialize { #region Fields private byte[] data; #endregion #region Properties public bool IsNull { get; internal set; } public static EventRecord Null { get { return new EventRecord() { IsNull = true }; } } public byte[] Data { get { if (data == null) { data = new byte[22]; } return data; } internal set { data = value; } } public SqlDateTime DateTimeStamp { get { var dateTimeStamp = new Data.EventRecord(Convert.ToUInt16(Index), Data).DateTimeStamp; return dateTimeStamp.HasValue ? dateTimeStamp.Value : SqlDateTime.Null; } } public int Index { get; internal set; } public SqlByte FstNumber { get { var fstNumber = new Data.EventRecord(Convert.ToUInt16(Index), Data).FstNumber; return fstNumber.HasValue ? fstNumber.Value : SqlByte.Null; } } public SqlByte PointType { get { var pointType = new Data.EventRecord(Convert.ToUInt16(Index), Data).PointType; return pointType.HasValue ? pointType.Value : SqlByte.Null; } } public SqlByte LogicalNumber { get { var logicalNumber = new Data.EventRecord(Convert.ToUInt16(Index), Data).LogicalNumber; return logicalNumber.HasValue ? logicalNumber.Value : SqlByte.Null; } } public SqlByte ParameterNumber { get { var parameterNumber = new Data.EventRecord(Convert.ToUInt16(Index), Data).ParameterNumber; return parameterNumber.HasValue ? parameterNumber.Value : SqlByte.Null; } } public SqlInt32 Tag { get { var tag = new Data.EventRecord(Convert.ToUInt16(Index), Data).Tag; return tag.HasValue ? tag.Value : SqlInt32.Null; } } public SqlDateTime PowerRemovedDateTime { get { var powerRemovedDateTime = new Data.EventRecord(Convert.ToUInt16(Index), Data).PowerRemovedDateTime; return powerRemovedDateTime.HasValue ? powerRemovedDateTime.Value : SqlDateTime.Null; } } public SqlString CalibrationPointType { get { var calibrationPointType = new Data.EventRecord(Convert.ToUInt16(Index), Data).CalibrationPointType; return calibrationPointType.HasValue ? calibrationPointType.Value.ToString() : SqlString.Null; } } public SqlString CalibrationMultivariableSensorInput { get { var calibrationMultivariableSensorInput = new Data.EventRecord(Convert.ToUInt16(Index), Data).CalibrationMultivariableSensorInput; return calibrationMultivariableSensorInput.HasValue ? calibrationMultivariableSensorInput.Value.ToString() : SqlString.Null; } } public SqlString CalibrationType { get { var calibrationType = new Data.EventRecord(Convert.ToUInt16(Index), Data).CalibrationType; return calibrationType.HasValue ? calibrationType.Value.ToString() : SqlString.Null; } } public SqlString EventCode { get { return new Data.EventRecord(Convert.ToUInt16(Index), Data).EventCode.ToString(); } } public SqlString OperatorId { get { return new Data.EventRecord(Convert.ToUInt16(Index), Data).OperatorId; } } public SqlString EventText { get { return new Data.EventRecord(Convert.ToUInt16(Index), Data).EventText; } } public SqlBinary OldValue { get { return new Data.EventRecord(Convert.ToUInt16(Index), Data).OldValue; } } public SqlSingle FstFloatValue { get { var fstFloatValue = new Data.EventRecord(Convert.ToUInt16(Index), Data).FstFloatValue; return fstFloatValue.HasValue ? fstFloatValue.Value : SqlSingle.Null; } } public SqlBinary NewValue { get { return new Data.EventRecord(Convert.ToUInt16(Index), Data).NewValue; } } public Parameter OldParameterValue { get { if (!PointType.IsNull && !ParameterNumber.IsNull) { var pointType = PointType.Value; var parameterNumber = ParameterNumber.Value; var parameterDefinition = ParameterDatabase.ParameterDefinitions.Where(pd => pd.PointType == pointType && pd.Parameter == parameterNumber).FirstOrDefault(); switch (parameterDefinition.DataType) { case "AC": switch (parameterDefinition.Length) { case 3: return new Parameter() { RawType = ParameterType.AC3, RawValue = OldValue.Value.Take(3).ToArray() }; default: return Parameter.Null; } case "BIN": return new Parameter() { RawType = ParameterType.BIN, RawValue = OldValue.Value.Take(1).ToArray() }; case "FL": return new Parameter() { RawType = ParameterType.FL, RawValue = OldValue.Value }; case "INT16": return new Parameter() { RawType = ParameterType.INT16, RawValue = OldValue.Value.Take(2).ToArray() }; case "INT32": return new Parameter() { RawType = ParameterType.INT32, RawValue = OldValue.Value }; case "INT8": return new Parameter() { RawType = ParameterType.INT8, RawValue = OldValue.Value.Take(1).ToArray() }; case "TLP": return new Parameter() { RawType = ParameterType.TLP, RawValue = OldValue.Value.Take(3).ToArray() }; case "UINT16": return new Parameter() { RawType = ParameterType.UINT16, RawValue = OldValue.Value.Take(2).ToArray() }; case "UINT32": return new Parameter() { RawType = ParameterType.UINT32, RawValue = OldValue.Value }; case "TIME": return new Parameter() { RawType = ParameterType.TIME, RawValue = OldValue.Value }; case "UINT8": return new Parameter() { RawType = ParameterType.UINT8, RawValue = OldValue.Value.Take(1).ToArray() }; default: return Parameter.Null; } } else { return Parameter.Null; } } } public Parameter NewParameterValue { get { if (!PointType.IsNull && !ParameterNumber.IsNull) { var pointType = PointType.Value; var parameterNumber = ParameterNumber.Value; var parameterDefinition = ParameterDatabase.ParameterDefinitions.Where(pd => pd.PointType == pointType && pd.Parameter == parameterNumber).FirstOrDefault(); switch (parameterDefinition.DataType) { case "AC": switch (parameterDefinition.Length) { case 3: return new Parameter() { RawType = ParameterType.AC3, RawValue = NewValue.Value.Take(3).ToArray() }; case 7: return new Parameter() { RawType = ParameterType.AC7, RawValue = NewValue.Value.Union(new byte[3]).ToArray() }; case 10: return new Parameter() { RawType = ParameterType.AC10, RawValue = OldValue.Value.Union(NewValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Tag.Value))).ToArray() }; case 12: return new Parameter() { RawType = ParameterType.AC12, RawValue = OldValue.Value.Union(NewValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Tag.Value))).Union(new byte[2]).ToArray() }; case 20: return new Parameter() { RawType = ParameterType.AC20, RawValue = OldValue.Value.Union(NewValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Tag.Value))).Union(new byte[10]).ToArray() }; case 30: return new Parameter() { RawType = ParameterType.AC30, RawValue = OldValue.Value.Union(NewValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Tag.Value))).Union(new byte[20]).ToArray() }; case 40: return new Parameter() { RawType = ParameterType.AC40, RawValue = OldValue.Value.Union(NewValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Tag.Value))).Union(new byte[30]).ToArray() }; default: return Parameter.Null; } case "BIN": return new Parameter() { RawType = ParameterType.BIN, RawValue = NewValue.Value.Take(1).ToArray() }; case "FL": return new Parameter() { RawType = ParameterType.FL, RawValue = NewValue.Value }; case "INT16": return new Parameter() { RawType = ParameterType.INT16, RawValue = NewValue.Value.Take(2).ToArray() }; case "INT32": return new Parameter() { RawType = ParameterType.INT32, RawValue = NewValue.Value }; case "INT8": return new Parameter() { RawType = ParameterType.INT8, RawValue = NewValue.Value.Take(1).ToArray() }; case "TLP": return new Parameter() { RawType = ParameterType.TLP, RawValue = NewValue.Value.Take(3).ToArray() }; case "UINT16": return new Parameter() { RawType = ParameterType.UINT16, RawValue = NewValue.Value.Take(2).ToArray() }; case "UINT32": return new Parameter() { RawType = ParameterType.UINT32, RawValue = NewValue.Value }; case "TIME": return new Parameter() { RawType = ParameterType.TIME, RawValue = NewValue.Value }; case "UINT8": return new Parameter() { RawType = ParameterType.UINT8, RawValue = NewValue.Value.Take(1).ToArray() }; default: return Parameter.Null; } } else { return Parameter.Null; } } } #endregion #region Helper Methods public static EventRecord Parse(SqlString stringToParse) { var parsedEventRecord = stringToParse.Value.Split(",".ToCharArray()); var base64Bytes = Convert.FromBase64String(parsedEventRecord[1]); if (base64Bytes.Length == 22) { return new EventRecord() { Index = ushort.Parse(parsedEventRecord[0]), Data = base64Bytes }; } else { throw new ArgumentException("Input must be exactly 22 bytes"); } } public override string ToString() { return string.Format("{0},{1}", Index, Convert.ToBase64String(Data)); } #endregion #region Serialization Methods public void Read(BinaryReader binaryReader) { IsNull = binaryReader.ReadBoolean(); Index = binaryReader.ReadInt32(); if (!IsNull) { Data = binaryReader.ReadBytes(22); } } public void Write(BinaryWriter binaryWriter) { binaryWriter.Write(IsNull); binaryWriter.Write(Index); if (!IsNull) { binaryWriter.Write(Data, 0, 22); } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.Management.Automation; using System.Security.Permissions; namespace Microsoft.PowerShell.ScheduledJob { /// <summary> /// This class contains Windows Task Scheduler options. /// </summary> [Serializable] public sealed class ScheduledJobOptions : ISerializable { #region Private Members // Power settings private bool _startIfOnBatteries; private bool _stopIfGoingOnBatteries; private bool _wakeToRun; // Idle settings private bool _startIfNotIdle; private bool _stopIfGoingOffIdle; private bool _restartOnIdleResume; private TimeSpan _idleDuration; private TimeSpan _idleTimeout; // Security settings private bool _showInTaskScheduler; private bool _runElevated; // Misc private bool _runWithoutNetwork; private bool _donotAllowDemandStart; private TaskMultipleInstancePolicy _multipleInstancePolicy; // ScheduledJobDefinition object associated with this options object. private ScheduledJobDefinition _jobDefAssociation; #endregion #region Public Properties /// <summary> /// Start task if on batteries. /// </summary> public bool StartIfOnBatteries { get { return _startIfOnBatteries; } set { _startIfOnBatteries = value; } } /// <summary> /// Stop task if computer is going on batteries. /// </summary> public bool StopIfGoingOnBatteries { get { return _stopIfGoingOnBatteries; } set { _stopIfGoingOnBatteries = value; } } /// <summary> /// Wake computer to run task. /// </summary> public bool WakeToRun { get { return _wakeToRun; } set { _wakeToRun = value; } } /// <summary> /// Start task only if computer is not idle. /// </summary> public bool StartIfNotIdle { get { return _startIfNotIdle; } set { _startIfNotIdle = value; } } /// <summary> /// Stop task if computer is no longer idle. /// </summary> public bool StopIfGoingOffIdle { get { return _stopIfGoingOffIdle; } set { _stopIfGoingOffIdle = value; } } /// <summary> /// Restart task on idle resuming. /// </summary> public bool RestartOnIdleResume { get { return _restartOnIdleResume; } set { _restartOnIdleResume = value; } } /// <summary> /// How long computer must be idle before task starts. /// </summary> public TimeSpan IdleDuration { get { return _idleDuration; } set { _idleDuration = value; } } /// <summary> /// How long task manager will wait for required idle duration. /// </summary> public TimeSpan IdleTimeout { get { return _idleTimeout; } set { _idleTimeout = value; } } /// <summary> /// When true task is not shown in Task Scheduler UI. /// </summary> public bool ShowInTaskScheduler { get { return _showInTaskScheduler; } set { _showInTaskScheduler = value; } } /// <summary> /// Run task with elevated privileges. /// </summary> public bool RunElevated { get { return _runElevated; } set { _runElevated = value; } } /// <summary> /// Run task even if network is not available. /// </summary> public bool RunWithoutNetwork { get { return _runWithoutNetwork; } set { _runWithoutNetwork = value; } } /// <summary> /// Do not allow a task to be started on demand. /// </summary> public bool DoNotAllowDemandStart { get { return _donotAllowDemandStart; } set { _donotAllowDemandStart = value; } } /// <summary> /// Multiple task instance policy. /// </summary> public TaskMultipleInstancePolicy MultipleInstancePolicy { get { return _multipleInstancePolicy; } set { _multipleInstancePolicy = value; } } /// <summary> /// ScheduledJobDefinition object associated with this options object. /// </summary> public ScheduledJobDefinition JobDefinition { get { return _jobDefAssociation; } internal set { _jobDefAssociation = value; } } #endregion #region Constructors /// <summary> /// Default constructor. /// </summary> public ScheduledJobOptions() { _startIfOnBatteries = false; _stopIfGoingOnBatteries = true; _wakeToRun = false; _startIfNotIdle = true; _stopIfGoingOffIdle = false; _restartOnIdleResume = false; _idleDuration = new TimeSpan(0, 10, 0); _idleTimeout = new TimeSpan(1, 0, 0); _showInTaskScheduler = true; _runElevated = false; _runWithoutNetwork = true; _donotAllowDemandStart = false; _multipleInstancePolicy = TaskMultipleInstancePolicy.IgnoreNew; } /// <summary> /// Constructor. /// </summary> /// <param name="startIfOnBatteries"></param> /// <param name="stopIfGoingOnBatters"></param> /// <param name="wakeToRun"></param> /// <param name="startIfNotIdle"></param> /// <param name="stopIfGoingOffIdle"></param> /// <param name="restartOnIdleResume"></param> /// <param name="idleDuration"></param> /// <param name="idleTimeout"></param> /// <param name="showInTaskScheduler"></param> /// <param name="runElevated"></param> /// <param name="runWithoutNetwork"></param> /// <param name="donotAllowDemandStart"></param> /// <param name="multipleInstancePolicy"></param> internal ScheduledJobOptions( bool startIfOnBatteries, bool stopIfGoingOnBatters, bool wakeToRun, bool startIfNotIdle, bool stopIfGoingOffIdle, bool restartOnIdleResume, TimeSpan idleDuration, TimeSpan idleTimeout, bool showInTaskScheduler, bool runElevated, bool runWithoutNetwork, bool donotAllowDemandStart, TaskMultipleInstancePolicy multipleInstancePolicy) { _startIfOnBatteries = startIfOnBatteries; _stopIfGoingOnBatteries = stopIfGoingOnBatters; _wakeToRun = wakeToRun; _startIfNotIdle = startIfNotIdle; _stopIfGoingOffIdle = stopIfGoingOffIdle; _restartOnIdleResume = restartOnIdleResume; _idleDuration = idleDuration; _idleTimeout = idleTimeout; _showInTaskScheduler = showInTaskScheduler; _runElevated = runElevated; _runWithoutNetwork = runWithoutNetwork; _donotAllowDemandStart = donotAllowDemandStart; _multipleInstancePolicy = multipleInstancePolicy; } /// <summary> /// Copy Constructor. /// </summary> /// <param name="copyOptions">Copy from.</param> internal ScheduledJobOptions( ScheduledJobOptions copyOptions) { if (copyOptions == null) { throw new PSArgumentNullException("copyOptions"); } _startIfOnBatteries = copyOptions.StartIfOnBatteries; _stopIfGoingOnBatteries = copyOptions.StopIfGoingOnBatteries; _wakeToRun = copyOptions.WakeToRun; _startIfNotIdle = copyOptions.StartIfNotIdle; _stopIfGoingOffIdle = copyOptions.StopIfGoingOffIdle; _restartOnIdleResume = copyOptions.RestartOnIdleResume; _idleDuration = copyOptions.IdleDuration; _idleTimeout = copyOptions.IdleTimeout; _showInTaskScheduler = copyOptions.ShowInTaskScheduler; _runElevated = copyOptions.RunElevated; _runWithoutNetwork = copyOptions.RunWithoutNetwork; _donotAllowDemandStart = copyOptions.DoNotAllowDemandStart; _multipleInstancePolicy = copyOptions.MultipleInstancePolicy; _jobDefAssociation = copyOptions.JobDefinition; } #endregion #region ISerializable Implementation /// <summary> /// Serialization constructor. /// </summary> /// <param name="info">SerializationInfo.</param> /// <param name="context">StreamingContext.</param> [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] private ScheduledJobOptions( SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException("info"); } _startIfOnBatteries = info.GetBoolean("StartIfOnBatteries_Value"); _stopIfGoingOnBatteries = info.GetBoolean("StopIfGoingOnBatteries_Value"); _wakeToRun = info.GetBoolean("WakeToRun_Value"); _startIfNotIdle = info.GetBoolean("StartIfNotIdle_Value"); _stopIfGoingOffIdle = info.GetBoolean("StopIfGoingOffIdle_Value"); _restartOnIdleResume = info.GetBoolean("RestartOnIdleResume_Value"); _idleDuration = (TimeSpan)info.GetValue("IdleDuration_Value", typeof(TimeSpan)); _idleTimeout = (TimeSpan)info.GetValue("IdleTimeout_Value", typeof(TimeSpan)); _showInTaskScheduler = info.GetBoolean("ShowInTaskScheduler_Value"); _runElevated = info.GetBoolean("RunElevated_Value"); _runWithoutNetwork = info.GetBoolean("RunWithoutNetwork_Value"); _donotAllowDemandStart = info.GetBoolean("DoNotAllowDemandStart_Value"); _multipleInstancePolicy = (TaskMultipleInstancePolicy)info.GetValue("TaskMultipleInstancePolicy_Value", typeof(TaskMultipleInstancePolicy)); // Runtime reference and not saved to store. _jobDefAssociation = null; } /// <summary> /// GetObjectData for ISerializable implementation. /// </summary> /// <param name="info">SerializationInfo.</param> /// <param name="context">StreamingContext.</param> [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException("info"); } info.AddValue("StartIfOnBatteries_Value", _startIfOnBatteries); info.AddValue("StopIfGoingOnBatteries_Value", _stopIfGoingOnBatteries); info.AddValue("WakeToRun_Value", _wakeToRun); info.AddValue("StartIfNotIdle_Value", _startIfNotIdle); info.AddValue("StopIfGoingOffIdle_Value", _stopIfGoingOffIdle); info.AddValue("RestartOnIdleResume_Value", _restartOnIdleResume); info.AddValue("IdleDuration_Value", _idleDuration); info.AddValue("IdleTimeout_Value", _idleTimeout); info.AddValue("ShowInTaskScheduler_Value", _showInTaskScheduler); info.AddValue("RunElevated_Value", _runElevated); info.AddValue("RunWithoutNetwork_Value", _runWithoutNetwork); info.AddValue("DoNotAllowDemandStart_Value", _donotAllowDemandStart); info.AddValue("TaskMultipleInstancePolicy_Value", _multipleInstancePolicy); } #endregion #region Public Methods /// <summary> /// Update the associated ScheduledJobDefinition object with the /// current properties of this object. /// </summary> public void UpdateJobDefinition() { if (_jobDefAssociation == null) { string msg = StringUtil.Format(ScheduledJobErrorStrings.NoAssociatedJobDefinitionForOption); throw new RuntimeException(msg); } _jobDefAssociation.UpdateOptions(this, true); } #endregion } #region Public Enums /// <summary> /// Enumerates Task Scheduler options for multiple instance polices of /// scheduled tasks (jobs). /// </summary> public enum TaskMultipleInstancePolicy { /// <summary> /// None. /// </summary> None = 0, /// <summary> /// Ignore a new instance of the task (job) /// </summary> IgnoreNew = 1, /// <summary> /// Allow parallel running of a task (job) /// </summary> Parallel = 2, /// <summary> /// Queue up multiple instances of a task (job) /// </summary> Queue = 3, /// <summary> /// Stop currently running task (job) and start a new one. /// </summary> StopExisting = 4 } #endregion }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset { public class LocalAssetServicesConnector : ISharedRegionModule, IAssetService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IImprovedAssetCache m_Cache = null; private IAssetService m_AssetService; private bool m_Enabled = false; public Type ReplaceableInterface { get { return null; } } public string Name { get { return "LocalAssetServicesConnector"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AssetServices", ""); if (name == Name) { IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[LOCAL ASSET SERVICES CONNECTOR]: AssetService missing from OpenSim.ini"); return; } string serviceDll = assetConfig.GetString("LocalServiceModule", String.Empty); if (serviceDll == String.Empty) { m_log.Error("[LOCAL ASSET SERVICES CONNECTOR]: No LocalServiceModule named in section AssetService"); return; } Object[] args = new Object[] { source }; m_AssetService = ServerUtils.LoadPlugin<IAssetService>(serviceDll, args); if (m_AssetService == null) { m_log.Error("[LOCAL ASSET SERVICES CONNECTOR]: Can't load asset service"); return; } m_Enabled = true; m_log.Info("[LOCAL ASSET SERVICES CONNECTOR]: Local asset connector enabled"); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; scene.RegisterModuleInterface<IAssetService>(this); } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_Cache == null) { m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>(); if (!(m_Cache is ISharedRegionModule)) m_Cache = null; } m_log.InfoFormat("[LOCAL ASSET SERVICES CONNECTOR]: Enabled local assets for region {0}", scene.RegionInfo.RegionName); if (m_Cache != null) { m_log.InfoFormat("[LOCAL ASSET SERVICES CONNECTOR]: Enabled asset caching for region {0}", scene.RegionInfo.RegionName); } else { // Short-circuit directly to storage layer // scene.UnregisterModuleInterface<IAssetService>(this); scene.RegisterModuleInterface<IAssetService>(m_AssetService); } } public AssetBase Get(string id) { // m_log.DebugFormat("[LOCAL ASSET SERVICES CONNECTOR]: Synchronously requesting asset {0}", id); AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { asset = m_AssetService.Get(id); if ((m_Cache != null) && (asset != null)) m_Cache.Cache(asset); // if (null == asset) // m_log.WarnFormat("[LOCAL ASSET SERVICES CONNECTOR]: Could not synchronously find asset with id {0}", id); } return asset; } public AssetBase GetCached(string id) { if (m_Cache != null) return m_Cache.Get(id); return null; } public AssetMetadata GetMetadata(string id) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset != null) return asset.Metadata; asset = m_AssetService.Get(id); if (asset != null) { if (m_Cache != null) m_Cache.Cache(asset); return asset.Metadata; } return null; } public byte[] GetData(string id) { // m_log.DebugFormat("[LOCAL ASSET SERVICES CONNECTOR]: Requesting data for asset {0}", id); AssetBase asset = m_Cache.Get(id); if (asset != null) return asset.Data; asset = m_AssetService.Get(id); if (asset != null) { if (m_Cache != null) m_Cache.Cache(asset); return asset.Data; } return null; } public bool Get(string id, Object sender, AssetRetrieved handler) { // m_log.DebugFormat("[LOCAL ASSET SERVICES CONNECTOR]: Asynchronously requesting asset {0}", id); if (m_Cache != null) { AssetBase asset = m_Cache.Get(id); if (asset != null) { Util.FireAndForget(delegate { handler(id, sender, asset); }); return true; } } return m_AssetService.Get(id, sender, delegate (string assetID, Object s, AssetBase a) { if ((a != null) && (m_Cache != null)) m_Cache.Cache(a); // if (null == a) // m_log.WarnFormat("[LOCAL ASSET SERVICES CONNECTOR]: Could not asynchronously find asset with id {0}", id); Util.FireAndForget(delegate { handler(assetID, s, a); }); }); } public string Store(AssetBase asset) { if (m_Cache != null) m_Cache.Cache(asset); if (asset.Temporary || asset.Local) return asset.ID; return m_AssetService.Store(asset); } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) m_Cache.Get(id); if (asset != null) { asset.Data = data; if (m_Cache != null) m_Cache.Cache(asset); } return m_AssetService.UpdateContent(id, data); } public bool Delete(string id) { if (m_Cache != null) m_Cache.Expire(id); return m_AssetService.Delete(id); } } }
namespace FakeItEasy.Specs { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using FakeItEasy.Core; using FakeItEasy.Creation; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xbehave; using Xunit; public abstract class CreationSpecsBase { [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "It's just used for testing.")] public interface ICollectionItem { } public interface IInterfaceWithSimilarMethods { void Test1<T>(IEnumerable<T> enumerable); void Test1<T>(IList<T> enumerable); } [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "It's just used for testing.")] public interface IInterface { } public interface IFakeCreator { Type FakeType { get; } object CreateFake(CreationSpecsBase specs); } [Scenario] [MemberData(nameof(SupportedTypes))] public void FakingSupportedTypes(IFakeCreator fakeCreator, object fake) { "Given a supported fake type" .See(fakeCreator.FakeType.ToString()); "When I create a fake of the supported type" .x(() => fake = fakeCreator.CreateFake(this)); "Then the result is a fake" .x(() => Fake.GetFakeManager(fake).Should().NotBeNull()); "And the fake is of the correct type" .x(() => fake.Should().BeAssignableTo(fakeCreator.FakeType)); } [Scenario] public void ThrowingConstructor( Exception exception) { "Given a class with a parameterless constructor" .See<ClassWhoseConstructorThrows>(); "And the constructor throws an exception" .See(() => new ClassWhoseConstructorThrows()); "When I create a fake of the class" .x(() => exception = Record.Exception(() => this.CreateFake<ClassWhoseConstructorThrows>())); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates why construction failed" .x(() => exception.Message.Should().StartWithModuloLineEndings(@" Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+ClassWhoseConstructorThrows: Below is a list of reasons for failure per attempted constructor: Constructor with signature () failed: No usable default constructor was found on the type FakeItEasy.Specs.CreationSpecsBase+ClassWhoseConstructorThrows. An exception of type System.NotSupportedException was caught during this call. Its message was: I don't like being constructed. ")); "And the exception message includes the original exception stack trace" .x(() => exception.Message.Should().Contain("FakeItEasy.Specs.CreationSpecsBase.ClassWhoseConstructorThrows..ctor()")); } [Scenario] public void FailureViaMultipleConstructors( Exception exception) { "Given a class with multiple constructors" .See<ClassWithMultipleConstructors>(); "And one constructor throws" .See(() => new ClassWithMultipleConstructors()); "And another constructor throws" .See(() => new ClassWithMultipleConstructors(string.Empty)); "And a third constructor has an argument that cannot be resolved" .See(() => new ClassWithMultipleConstructors(new UnresolvableArgument(), string.Empty)); "When I create a fake of the class" .x(() => exception = Record.Exception(() => this.CreateFake<ClassWithMultipleConstructors>())); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates why construction failed" .x(() => exception.Message.Should().MatchModuloLineEndings(@" Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+ClassWithMultipleConstructors: Below is a list of reasons for failure per attempted constructor: Constructor with signature () failed: No usable default constructor was found on the type FakeItEasy.Specs.CreationSpecsBase+ClassWithMultipleConstructors. An exception of type System.Exception was caught during this call. Its message was: parameterless constructor failed *FakeItEasy.Specs.CreationSpecsBase.ClassWithMultipleConstructors..ctor()* Constructor with signature (System.String) failed: No constructor matches the passed arguments for constructor. An exception of type System.Exception was caught during this call. Its message was: string constructor failed with reason on two lines *FakeItEasy.Specs.CreationSpecsBase.ClassWithMultipleConstructors..ctor(String s)* The constructors with the following signatures were not tried: (*FakeItEasy.Specs.CreationSpecsBase+UnresolvableArgument, System.String) Types marked with * could not be resolved. Please provide a Dummy Factory to enable these constructors. ")); } // This spec proves that we can cope with throwing constructors (e.g. ensures that FakeManagers won't be reused): [Scenario] public void UseSuccessfulConstructor( FakedClass fake, IEnumerable<int> parameterListLengthsForAttemptedConstructors) { "Given a class with multiple constructors" .See<FakedClass>(); "And the parameterless constructor throws" .See(() => new FakedClass()); "And the class has a one-parameter constructor" .See(() => new FakedClass(new ArgumentThatShouldNeverBeResolved())); "And the class has a two-parameter constructor" .See(() => new FakedClass(A.Dummy<IDisposable>(), string.Empty)); "When I create a fake of the class" .x(() => { lock (FakedClass.ParameterListLengthsForAttemptedConstructors) { FakedClass.ParameterListLengthsForAttemptedConstructors.Clear(); fake = this.CreateFake<FakedClass>(); parameterListLengthsForAttemptedConstructors = new List<int>(FakedClass.ParameterListLengthsForAttemptedConstructors); } }); "Then the fake is instantiated using the two-parameter constructor" .x(() => fake.WasTwoParameterConstructorCalled.Should().BeTrue()); "And the fake doesn't remember the failing constructor call" .x(() => fake.WasParameterlessConstructorCalled .Should().BeFalse("because the parameterless constructor was called for a different fake object")); "And the one-parameter constructor was not tried" .x(() => parameterListLengthsForAttemptedConstructors.Should().NotContain(1)); "And the argument for the unused constructor was never resolved" .x(() => ArgumentThatShouldNeverBeResolved.WasResolved.Should().BeFalse()); } [Scenario] public void CacheSuccessfulConstructor( ClassWhosePreferredConstructorsThrow fake1, ClassWhosePreferredConstructorsThrow fake2) { "Given a class with multiple constructors" .See<ClassWhosePreferredConstructorsThrow>(); "And the class has a parameterless constructor that throws" .See(() => new ClassWhosePreferredConstructorsThrow()); "And the class has a two-parameter constructor that throws" .See(() => new ClassWhosePreferredConstructorsThrow(A.Dummy<IDisposable>(), string.Empty)); "And the class has a one-parameter constructor that succeeds" .See(() => new ClassWhosePreferredConstructorsThrow(default)); // If multiple theads attempt to create the fake at the same time, the // unsuccessful constructors may be called more than once, so serialize fake // creation for this test. "And nobody else is trying to fake the class right now" .x(() => Monitor.TryEnter(typeof(ClassWhosePreferredConstructorsThrow), TimeSpan.FromSeconds(30)).Should().BeTrue("we must enter the monitor")) .Teardown(() => Monitor.Exit(typeof(ClassWhosePreferredConstructorsThrow))); "When I create a fake of the class" .x(() => fake1 = this.CreateFake<ClassWhosePreferredConstructorsThrow>()); "And I create another fake of the class" .x(() => fake2 = this.CreateFake<ClassWhosePreferredConstructorsThrow>()); "Then the two fakes are distinct" .x(() => fake1.Should().NotBeSameAs(fake2)); "And the parameterless constructor was only called once" .x(() => ClassWhosePreferredConstructorsThrow.NumberOfTimesParameterlessConstructorWasCalled.Should().Be(1)); "And the two-parameter constructor was only called once" .x(() => ClassWhosePreferredConstructorsThrow.NumberOfTimesTwoParameterConstructorWasCalled.Should().Be(1)); } public class ClassWhosePreferredConstructorsThrow { public static int NumberOfTimesParameterlessConstructorWasCalled => numberOfTimesParameterlessConstructorWasCalled; public static int NumberOfTimesTwoParameterConstructorWasCalled => numberOfTimesTwoParameterConstructorWasCalled; private static int numberOfTimesTwoParameterConstructorWasCalled; private static int numberOfTimesParameterlessConstructorWasCalled; public ClassWhosePreferredConstructorsThrow() { Interlocked.Increment(ref numberOfTimesParameterlessConstructorWasCalled); throw new NotImplementedException(); } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "anInt", Justification = "This is just a dummy argument.")] public ClassWhosePreferredConstructorsThrow(int anInt) { } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "disposable", Justification = "This is just a dummy argument.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "aString", Justification = "This is just a dummy argument.")] public ClassWhosePreferredConstructorsThrow(IDisposable disposable, string aString) { Interlocked.Increment(ref numberOfTimesTwoParameterConstructorWasCalled); throw new NotImplementedException(); } } [Scenario] [Example(2)] [Example(10)] public void CollectionOfFake( int count, IList<ICollectionItem> fakes) { "When I create a collection of {0} fakes" .x(() => fakes = this.CreateCollectionOfFake<ICollectionItem>(count)); "Then {0} items are created" .x(() => fakes.Should().HaveCount(count)); "And all items extend the specified type" .x(() => fakes.Should().ContainItemsAssignableTo<ICollectionItem>()); "And all items are fakes" .x(() => fakes.Should().OnlyContain(item => Fake.GetFakeManager(item) is object)); } [Scenario] [Example(2)] [Example(10)] public void CollectionOfFakeWithOptionBuilder( int count, IList<ICollectionItem> fakes) { "When I create a collection of {0} fakes that also implement another interface" .x(() => fakes = this.CreateCollectionOfFake<ICollectionItem>(count, options => options.Implements<IDisposable>())); "Then {0} items are created" .x(() => fakes.Should().HaveCount(count)); "And all items extend the specified type and the extra interface" .x(() => fakes.Should().ContainItemsAssignableTo<ICollectionItem>().And.ContainItemsAssignableTo<IDisposable>()); "And all items are fakes" .x(() => fakes.Should().OnlyContain(item => Fake.GetFakeManager(item) is object)); } [Scenario] public void InterfaceWithAlikeGenericMethod(IInterfaceWithSimilarMethods fake) { "Given an interface with an overloaded methods containing generic arguments" .See<IInterfaceWithSimilarMethods>(); "When I create a fake of the interface" .x(() => fake = this.CreateFake<IInterfaceWithSimilarMethods>()); "Then the fake is created" .x(() => fake.Should().BeAFake()); } [Scenario] public void PrivateClassCannotBeFaked(Exception exception) { "Given a private class" .See<PrivateClass>(); "When I create a fake of the class" .x(() => exception = Record.Exception(this.CreateFake<PrivateClass>)); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().MatchModuloLineEndings(@" Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+PrivateClass: Below is a list of reasons for failure per attempted constructor: Constructor with signature () failed: No usable default constructor was found on the type FakeItEasy.Specs.CreationSpecsBase+PrivateClass. An exception of type Castle.DynamicProxy.Generators.GeneratorException was caught during this call. Its message was: Can not create proxy for type FakeItEasy.Specs.CreationSpecsBase+PrivateClass because it is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo(*DynamicProxyGenAssembly2*)] attribute* ")); } [Scenario] public void PrivateDelegateCannotBeFaked(Exception exception) { "Given a private delegate" .See<PrivateDelegate>(); "When I create a fake of the delegate" .x(() => exception = Record.Exception(this.CreateFake<PrivateDelegate>)); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().MatchModuloLineEndings(@" Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+PrivateDelegate: Can not create proxy for type FakeItEasy.Specs.CreationSpecsBase+PrivateDelegate because it is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo(*DynamicProxyGenAssembly2*)] attribute* ")); } [Scenario] public void PublicDelegateWithPrivateTypeArgumentCannotBeFaked(Exception exception) { "Given a public delegate with a private type argument" .See<Func<PrivateClass>>(); "When I create a fake of the delegate" .x(() => exception = Record.Exception(this.CreateFake<Func<PrivateClass>>)); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().MatchModuloLineEndings(@" Failed to create fake of type System.Func`1[FakeItEasy.Specs.CreationSpecsBase+PrivateClass]: Can not create proxy for type System.Func`1[[FakeItEasy.Specs.CreationSpecsBase+PrivateClass, FakeItEasy.Specs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=eff28e2146d5fd2c]] because type FakeItEasy.Specs.CreationSpecsBase+PrivateClass is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo(*DynamicProxyGenAssembly2*)] attribute* ")); } [Scenario] public void ClassWithPrivateConstructorCannotBeFaked(Exception exception) { "Given a class with a private constructor" .See<ClassWithPrivateConstructor>(); "When I create a fake of the class" .x(() => exception = Record.Exception(this.CreateFake<ClassWithPrivateConstructor>)); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().StartWithModuloLineEndings(@" Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+ClassWithPrivateConstructor: Below is a list of reasons for failure per attempted constructor: Constructor with signature () failed: No usable default constructor was found on the type FakeItEasy.Specs.CreationSpecsBase+ClassWithPrivateConstructor. An exception of type Castle.DynamicProxy.InvalidProxyConstructorArgumentsException was caught during this call. Its message was: Can not instantiate proxy of class: FakeItEasy.Specs.CreationSpecsBase+ClassWithPrivateConstructor. Could not find a parameterless constructor. ")); } [Scenario] public void SealedClassCannotBeFaked(Exception exception) { "Given a sealed class" .See<SealedClass>(); "When I create a fake of the class" .x(() => exception = Record.Exception(() => this.CreateFake<SealedClass>())); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().BeModuloLineEndings(@" Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+SealedClass: The type of proxy FakeItEasy.Specs.CreationSpecsBase+SealedClass is sealed. ")); } [Scenario] public void CannotFakeInterfaceWithConstructorArguments(Exception exception) { "Given a fakeable interface" .See<IInterface>(); "When I create a fake of the interface supplying constructor arguments" .x(() => exception = Record.Exception(() => this.CreateFake<IInterface>(options => options.WithArgumentsForConstructor(new object[] { 7 })))); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<ArgumentException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().Be("Arguments for constructor specified for interface type.")); } [Scenario] public void SuppliedConstructorArgumentsArePassedToClassConstructor(AClassThatCouldBeFakedWithTheRightConstructorArguments fake) { "Given a fakeable class" .See<AClassThatCouldBeFakedWithTheRightConstructorArguments>(); "When I create a fake of the class supplying valid constructor arguments" .x(() => fake = this.CreateFake<AClassThatCouldBeFakedWithTheRightConstructorArguments>(options => options.WithArgumentsForConstructor(() => new AClassThatCouldBeFakedWithTheRightConstructorArguments(17)))); "Then it passes the supplied arguments to the constructor" .x(() => fake.ID.Should().Be(17)); } [Scenario] public void CannotFakeWithBadConstructorArguments(Exception exception) { "Given a fakeable class" .See<AClassThatCouldBeFakedWithTheRightConstructorArguments>(); "When I create a fake of the class supplying invalid constructor arguments" .x(() => exception = Record.Exception(() => this.CreateFake<AClassThatCouldBeFakedWithTheRightConstructorArguments>(options => options.WithArgumentsForConstructor(new object[] { 7, "magenta" })))); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().StartWithModuloLineEndings(@" Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+AClassThatCouldBeFakedWithTheRightConstructorArguments: No constructor matches the passed arguments for constructor. An exception of type Castle.DynamicProxy.InvalidProxyConstructorArgumentsException was caught during this call. Its message was: Can not instantiate proxy of class: FakeItEasy.Specs.CreationSpecsBase+AClassThatCouldBeFakedWithTheRightConstructorArguments. Could not find a constructor that would match given arguments: System.Int32 System.String")); } [Scenario] public void FakeDelegateCreation(Func<int> fake) { "Given a delegate" .See<Func<int>>(); "When I create a fake of the delegate" .x(() => fake = this.CreateFake<Func<int>>()); "Then it creates the fake" .x(() => fake.Should().NotBeNull()); } [Scenario] public void FakeDelegateCreationWithAttributes(Exception exception) { "Given a delegate" .See<Func<int>>(); "When I create a fake of the delegate with custom attributes" .x(() => exception = Record.Exception(() => this.CreateFake<Func<int>>(options => options.WithAttributes(() => new ObsoleteAttribute())))); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().BeModuloLineEndings(@" Failed to create fake of type System.Func`1[System.Int32]: Faked delegates cannot have custom attributes applied to them. ")); } [Scenario] public void FakeDelegateCreationWithArgumentsForConstructor(Exception exception) { "Given a delegate" .See<Func<int>>(); "When I create a fake of the delegate using explicit constructor arguments" .x(() => exception = Record.Exception(() => this.CreateFake<Func<int>>(options => options.WithArgumentsForConstructor(new object[] { 7 })))); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().BeModuloLineEndings(@" Failed to create fake of type System.Func`1[System.Int32]: Faked delegates cannot be made using explicit constructor arguments. ")); } [Scenario] public void FakeDelegateCreationWithAdditionalInterfaces(Exception exception) { "Given a delegate" .See<Func<int>>(); "When I create a fake of the delegate with additional implemented interfaces" .x(() => exception = Record.Exception(() => this.CreateFake<Func<int>>(options => options.Implements<IList<string>>()))); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().BeModuloLineEndings(@" Failed to create fake of type System.Func`1[System.Int32]: Faked delegates cannot be made to implement additional interfaces. ")); } [Scenario] public void NamedFakeToString(object fake, string? toStringResult) { "Given a named fake" .x(() => fake = A.Fake<object>(o => o.Named("Foo"))); "When I call ToString() on the fake" .x(() => toStringResult = fake.ToString()); "Then it returns the configured name of the fake" .x(() => toStringResult.Should().Be("Foo")); } [Scenario] public void NamedFakeAsArgument(object fake, Action<object> fakeAction, Exception exception) { "Given a named fake" .x(() => fake = A.Fake<object>(o => o.Named("Foo"))); "And a fake action that takes an object as the parameter" .x(() => fakeAction = A.Fake<Action<object>>()); "When I assert that the fake action was called with the named fake" .x(() => exception = Record.Exception(() => A.CallTo(() => fakeAction(fake)).MustHaveHappened())); "Then the exception message describes the named fake by its name" .x(() => exception.Message.Should().Contain(".Invoke(obj: Foo)")); } [Scenario] public void NamedFakeDelegateToString(Action fake, string? toStringResult) { "Given a named delegate fake" .x(() => fake = A.Fake<Action>(o => o.Named("Foo"))); "When I call ToString() on the fake" .x(() => toStringResult = fake.ToString()); "Then it returns the name of the faked object type, because ToString() can't be faked for a delegate" .x(() => toStringResult.Should().Be("System.Action")); } [Scenario] public void NamedFakeDelegateAsArgument(Action fake, Action<Action> fakeAction, Exception exception) { "Given a named delegate fake" .x(() => fake = A.Fake<Action>(o => o.Named("Foo"))); "And a fake action that takes an action as the parameter" .x(() => fakeAction = A.Fake<Action<Action>>()); "When I assert that the fake action was called with the named fake" .x(() => exception = Record.Exception(() => A.CallTo(() => fakeAction(fake)).MustHaveHappened())); "Then the exception message describes the named fake by its name" .x(() => exception.Message.Should().Contain(".Invoke(obj: Foo)")); } [Scenario] public void AvoidLongSelfReferentialConstructor( ClassWithLongSelfReferentialConstructor fake1, ClassWithLongSelfReferentialConstructor fake2) { "Given a class with multiple constructors" .See<ClassWithLongSelfReferentialConstructor>(); "And the class has a one-parameter constructor not using its own type" .See(() => new ClassWithLongSelfReferentialConstructor(typeof(object))); "And the class has a two-parameter constructor using its own type" .See(() => new ClassWithLongSelfReferentialConstructor(typeof(object), A.Dummy<ClassWithLongSelfReferentialConstructor>())); "When I create a fake of the class" .x(() => fake1 = A.Fake<ClassWithLongSelfReferentialConstructor>()); "And I create another fake of the class" .x(() => fake2 = A.Fake<ClassWithLongSelfReferentialConstructor>()); "Then the first fake is not null" .x(() => fake1.Should().NotBeNull()); "And it was created using the one-parameter constructor" .x(() => fake1.NumberOfConstructorParameters.Should().Be(1)); "And the second fake is not null" .x(() => fake2.Should().NotBeNull()); "And it was created using the one-parameter constructor" .x(() => fake2.NumberOfConstructorParameters.Should().Be(1)); } protected abstract T CreateFake<T>() where T : class; protected abstract T CreateFake<T>(Action<IFakeOptions<T>> optionsBuilder) where T : class; protected abstract IList<T> CreateCollectionOfFake<T>(int numberOfFakes) where T : class; protected abstract IList<T> CreateCollectionOfFake<T>(int numberOfFakes, Action<IFakeOptions<T>> optionsBuilder) where T : class; public class ClassWhoseConstructorThrows { public ClassWhoseConstructorThrows() { throw new NotSupportedException("I don't like being constructed."); } } public class FakedClass { [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This anti-pattern is part of the the tested scenario.")] public FakedClass() { ParameterListLengthsForAttemptedConstructors.Add(0); this.WasParameterlessConstructorCalled = true; throw new InvalidOperationException(); } [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This anti-pattern is part of the the tested scenario.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "someInterface", Justification = "This is just a dummy argument.")] public FakedClass(ArgumentThatShouldNeverBeResolved argument) { ParameterListLengthsForAttemptedConstructors.Add(1); } [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This anti-pattern is part of the the tested scenario.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "someInterface", Justification = "This is just a dummy argument.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "someName", Justification = "This is just a dummy argument.")] public FakedClass(IDisposable someInterface, string someName) { ParameterListLengthsForAttemptedConstructors.Add(2); this.WasTwoParameterConstructorCalled = true; } public static ISet<int> ParameterListLengthsForAttemptedConstructors { get; } = new SortedSet<int>(); public bool WasParameterlessConstructorCalled { get; set; } public bool WasTwoParameterConstructorCalled { get; set; } } public sealed class ArgumentThatShouldNeverBeResolved { public static bool WasResolved { get; private set; } public ArgumentThatShouldNeverBeResolved() { WasResolved = true; } } public sealed class SealedClass { } public struct Struct { } public class AClassThatCouldBeFakedWithTheRightConstructorArguments { public AClassThatCouldBeFakedWithTheRightConstructorArguments(int id) { this.ID = id; } public int ID { get; } } public sealed class UnresolvableArgument { public UnresolvableArgument() => throw new InvalidOperationException(); } public class ClassWithMultipleConstructors { public ClassWithMultipleConstructors() => throw new Exception("parameterless constructor failed"); [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "s", Justification = "Required for testing.")] public ClassWithMultipleConstructors(string s) => throw new Exception("string constructor failed" + Environment.NewLine + "with reason on two lines"); [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "u", Justification = "Required for testing.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "s", Justification = "Required for testing.")] public ClassWithMultipleConstructors(UnresolvableArgument u, string s) { } } public abstract class AbstractClass { } public class ClassWithProtectedConstructor { protected ClassWithProtectedConstructor() { } } public class ClassWithPrivateConstructor { private ClassWithPrivateConstructor() { } } private static IEnumerable<object?[]> SupportedTypes() => TestCases.FromObject( new FakeCreator<IInterface>(), new FakeCreator<AbstractClass>(), new FakeCreator<ClassWithProtectedConstructor>(), new FakeCreator<ClassWithInternalConstructorVisibleToDynamicProxy>(), new FakeCreator<InternalClassVisibleToDynamicProxy>(), new FakeCreator<Action>(), new FakeCreator<Func<int, string>>(), new FakeCreator<EventHandler<EventArgs>>()); private class FakeCreator<TFake> : IFakeCreator where TFake : class { public Type FakeType => typeof(TFake); public object CreateFake(CreationSpecsBase testRunner) { return testRunner.CreateFake<TFake>(); } public override string ToString() => typeof(TFake).Name; } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Required for testing.")] private class PrivateClass { } private delegate void PrivateDelegate(); } public class GenericCreationSpecs : CreationSpecsBase { protected override T CreateFake<T>() { return A.Fake<T>(); } protected override T CreateFake<T>(Action<IFakeOptions<T>> optionsBuilder) { return A.Fake(optionsBuilder); } protected override IList<T> CreateCollectionOfFake<T>(int numberOfFakes) { return A.CollectionOfFake<T>(numberOfFakes); } protected override IList<T> CreateCollectionOfFake<T>(int numberOfFakes, Action<IFakeOptions<T>> optionsBuilder) { return A.CollectionOfFake(numberOfFakes, optionsBuilder); } } public class NonGenericCreationSpecs : CreationSpecsBase { [Scenario] public void StructCannotBeFaked(Exception exception) { "Given a struct" .See<Struct>(); "When I create a fake of the struct" .x(() => exception = Record.Exception(() => (Struct)Sdk.Create.Fake(typeof(Struct)))); "Then it throws a fake creation exception" .x(() => exception.Should().BeOfType<FakeCreationException>()); "And the exception message indicates the reason for failure" .x(() => exception.Message.Should().StartWithModuloLineEndings(@" Failed to create fake of type FakeItEasy.Specs.CreationSpecsBase+Struct: The type of proxy must be an interface or a class but it was FakeItEasy.Specs.CreationSpecsBase+Struct. ")); } protected override T CreateFake<T>() { return (T)Sdk.Create.Fake(typeof(T)); } protected override T CreateFake<T>(Action<IFakeOptions<T>> optionsBuilder) { return (T)Sdk.Create.Fake(typeof(T), options => optionsBuilder((IFakeOptions<T>)options)); } protected override IList<T> CreateCollectionOfFake<T>(int numberOfFakes) { return Sdk.Create.CollectionOfFake(typeof(T), numberOfFakes).Cast<T>().ToList(); } protected override IList<T> CreateCollectionOfFake<T>(int numberOfFakes, Action<IFakeOptions<T>> optionsBuilder) { return Sdk.Create.CollectionOfFake(typeof(T), numberOfFakes, options => optionsBuilder((IFakeOptions<T>)options)).Cast<T>().ToList(); } } }
// Copyright (c) 2017 Jan Pluskal, Miroslav Slivka, Viliam Letavay // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Netfox.Framework.Models; using Netfox.Framework.Models.Enums; using Netfox.Framework.Models.PmLib; using Netfox.Framework.Models.PmLib.Frames; namespace Netfox.Framework.ApplicationProtocolExport.PDUProviders { public class ByteArrayComparer : IEqualityComparer<byte[]> { public bool Equals(Byte[] a, Byte[] b) { return a.SequenceEqual(b); } public int GetHashCode(Byte[] key) { if(key == null) throw new ArgumentNullException(nameof(key)); return key.Sum(b => b); } } #region DecryptedData class public class DecryptedData { public int DataOffset; public Byte[] Data { get; set; } public int DataLength { get { return this.Data.Length; } } public Boolean IsAllRead { get { return this.DataLength == this.DataOffset; } } public int RemainingBytes { get { return this.DataLength - this.DataOffset; } } public L7PDU PDU { get; set; } } #endregion public class PDUDecrypterBase : PDUStreamBasedProvider { #region Constructors, Constants and Private Properties // Version Major public const Byte Ssl3VerMajor = 3; // SSL Protocols identifications public const Byte ChangeCipherSpec = 20; public const Byte Alert = 21; public const Byte Handshake = 22; public const Byte Record = 23; // Handshake messages identifications public const Byte ClientHello = 1; public const Byte ServerHello = 2; public const Byte ClientKeyExchange = 16; public const Byte Finished = 20; // Change Cipher Spec messages identifications public const Byte ChangeCipherSpecMessage = 1; public enum SslSessionState { NegotiationInit, Negotiation, NegotiationChangeCipherSpec, NegotiationFinished, Intermezzo, DataExchange } public List<DecryptedData> DataList { get; } = new List<DecryptedData>(); private Int32 _decryptedDataCnt; private Int32 _decryptedDataOffset; private SslSessionState _state; private Int32 _msgUnderReview; private readonly L7Conversation _conversation; private L7PDU[] Pdus { get; set; } private Byte[] _decryptedBytes; private readonly List<L7PDU> _processedPdus = new List<L7PDU>(); private PmFrameBase _previousFrame; private Boolean _dataDecrypted; private Boolean _lastPDU; private static readonly Dictionary<Byte[], Byte[]> SessionsMasterKeys = new Dictionary<Byte[], Byte[]>(new ByteArrayComparer()); private readonly Byte[] _currentSessionID = new byte[32]; private DecryptedData Current =>this.DataList.Any()? this.DataList.ElementAt(this._decryptedDataCnt):null; public PDUDecrypterBase(L7Conversation conversation, EfcPDUProviderType pduProviderType) : base(conversation, pduProviderType) { this._conversation = conversation; //this._frames = this._conversation.Frames.OrderBy(f => f.FrameIndex); switch(pduProviderType) { case EfcPDUProviderType.Mixed: this._next = this.NextMixed; this._previous = this.PreviousMixed; break; case EfcPDUProviderType.Breaked: this._next = this.NextBreaked; this._previous = this.PreviousBreaked; break; case EfcPDUProviderType.ContinueInterlay: this._next = this.NextContinueInterlay; this._previous = this.PreviousContinueInterlay; break; case EfcPDUProviderType.SingleMessage: this._next = this.NextSingleMessage; this._previous = this.PreviousSingleMessage; break; default: throw new ArgumentOutOfRangeException("pduProviderType"); } this.Reset(); } #endregion #region Public Properties public override Int64 Length { get { throw new NotImplementedException(); } } public override Boolean CanRead { get { return true; } } public override Boolean CanSeek { get { return true; } } public override Boolean CanWrite { get { return false; } } public override Int64 Position { get { return this.TotalReadedPDUbytes + ((this.DataList.Any())? this.Current?.DataOffset ?? 0 : 0); } set { this.Seek(value, SeekOrigin.Begin); } } public PDUDecrypter Decrypter { get; private set; } #endregion #region Stream Manipulation public override void Flush() { throw new NotImplementedException(); } public override Int64 Seek(Int64 offset, SeekOrigin origin) { var seeked = 0; switch(origin) { case SeekOrigin.Begin: if(offset <= 0) { this.ResetSoft(); return 0; } return this.Seek(offset - this.Position, SeekOrigin.Current); case SeekOrigin.Current: if(offset < 0) { this.EndOfStream = false; while(-offset > seeked) { if(this.Current == null) return 0; if(-offset > this.Current.DataOffset + seeked) { seeked += (this.Current.DataOffset == 0 && this._decryptedDataCnt != 0)? this.Current.DataLength : this.Current.DataOffset; if(!this.MovePrevious()) { return this.Position; } } else { this.Current.DataOffset = this.Current.DataOffset - (Int32) (-offset) - seeked; return this.Position; } } } else { while(offset > seeked) { if (this.Current == null) return 0; if (offset > this.Current.RemainingBytes + seeked) { seeked += this.Current.RemainingBytes; if(!this.MoveNext()) { this.EndOfStream = true; return this.Position; } } else { this.Current.DataOffset = this.Current.DataOffset + (Int32) (offset - seeked); return this.Position; } } } return this.Position; case SeekOrigin.End: throw new NotSupportedException("Seeking from the end of stream is not supported."); default: throw new ArgumentOutOfRangeException("Not supported origin type."); } } public override Int32 Read(Byte[] buffer, Int32 offset, Int32 requestedCount) { if(this._dataDecrypted == false) { this.DecryptPdus(); } if(!this.DataList.Any()) { this.EndOfStream = true; return 0; } Int64 bufferOffset = offset; Int64 count = requestedCount; do { var decryptedPDU = this.DataList[this._decryptedDataCnt]; var remainLenInPDU = decryptedPDU.DataLength - decryptedPDU.DataOffset; var currentCount = remainLenInPDU > count? count : remainLenInPDU; Array.Copy(decryptedPDU.Data, decryptedPDU.DataOffset, buffer, bufferOffset, currentCount); bufferOffset += currentCount; count -= currentCount; decryptedPDU.DataOffset += (Int32) currentCount; // if (decryptedPDU.RemainingBytes == 0) { this.EndOfPDU = true; } if(count != 0) { this.EndOfStream = !this.MoveNext(); } } while(!this.EndOfStream && count > 0); return (Int32) bufferOffset - offset; } public override Int32 Peek(Byte[] buffer, Int32 bufferOffset, Int32 streamPosition, Int32 requestedCount, SeekOrigin origin) { /* save current position */ var dataCnt = this._decryptedDataCnt; var dataOffset = this._decryptedDataOffset; var sPos = this.Position; /* goto requested position */ this.Seek(streamPosition, origin); /* read from that position */ var len = this.Read(buffer, bufferOffset, requestedCount); /* reset position */ this._decryptedDataCnt = dataCnt; this._decryptedDataOffset = dataOffset; this.Position = sPos; return len; } public override Boolean Reset() { this._state = SslSessionState.NegotiationInit; this._msgUnderReview = 0; this._decryptedDataCnt = 0; this._decryptedDataOffset = 0; this.DataList.Clear(); this._decryptedBytes = null; this._processedPdus.Clear(); this._dataDecrypted = false; this._lastPDU = false; this.Pdus = this._conversation.L7PDUs.ToArray(); this.Decrypter = new PDUDecrypter(); SessionsMasterKeys.Clear(); return this.ResetSoft(); } public Boolean ResetSoft() { this.TotalReadedPDUbytes = 0; this._decryptedDataCnt = 0; this._decryptedDataOffset = 0; this._lastPDU = false; this.EndOfStream = !this.DataList.Any(); return !this.EndOfStream; } public override L7PDU GetCurrentPDU() => this._decryptedDataCnt < this.DataList.Count? this.DataList.ElementAt(this._decryptedDataCnt).PDU : null; public override void SetLength(Int64 value) { throw new NotImplementedException(); } public override void Write(Byte[] buffer, Int32 offset, Int32 count) { throw new NotImplementedException(); } public override Boolean NewMessage() { if(this._dataDecrypted == false) { this.DecryptPdus(); } if(!this.DataList.Any()) { return false; } if(this.Current.DataOffset != 0 || this._decryptedDataCnt == 0) { this.DataList.RemoveAt(this._decryptedDataCnt); } for(var i = this._decryptedDataCnt - 1; i >= 0; i--) { var decryptedData = this.DataList[i]; if(decryptedData.IsAllRead) { this.DataList.RemoveAt(i); } } return this.ResetSoft(); } protected Boolean DecryptPdus() { if(!this.Pdus.Any()) return false; // decrypt next message for(this._msgUnderReview = 0; this._msgUnderReview < this.Pdus.Count(); this._msgUnderReview++) { //if (this._msgUnderReview == this._pdus.Count()) // return false; var pduElement = this.Pdus.ElementAt(this._msgUnderReview); this._processedPdus.Add(pduElement); for(var frameNum = 0; frameNum < pduElement.FrameList.Count(); frameNum++) { //Console.WriteLine("Frame > "+frame.FrameIndex); var frame = pduElement.FrameList.ElementAt(frameNum); if(frame is PmFrameVirtualBlank) continue; var l7Data = new Byte[frame.PmPacket.SegmentPayloadLength]; Array.Copy(frame.L7Data(), 0, l7Data, 0, l7Data.Length); if(this.Decrypter.ContinuationData != null && l7Data.Length != 0 && this._previousFrame != null) { // Check that the frame is in the same direction as previous in processing // when continuation of data happend last decryption ended with false and state change to INTERMEZZO if(Enumerable.SequenceEqual<byte>(frame.SourceEndPoint.Address.GetAddressBytes(), this._previousFrame.SourceEndPoint.Address.GetAddressBytes())) { var tmp = l7Data; l7Data = new Byte[tmp.Length + this.Decrypter.ContinuationData.Length]; Array.Copy(this.Decrypter.ContinuationData, 0, l7Data, 0, this.Decrypter.ContinuationData.Length); Array.Copy(tmp, 0, l7Data, this.Decrypter.ContinuationData.Length, tmp.Length); this.Decrypter.ContinuationData = null; } else { // If not same direction try to decrypt what is left in _continuationData this._msgUnderReview--; frame = this._previousFrame; l7Data = new Byte[this.Decrypter.ContinuationData.Length]; Array.Copy(this.Decrypter.ContinuationData, 0, l7Data, 0, this.Decrypter.ContinuationData.Length); this.Decrypter.ContinuationData = null; } } // Here it is safe to set previous frame this._previousFrame = frame; try { switch(this._state) { case SslSessionState.NegotiationInit: this.AwaitHelloMessages(l7Data, frame); break; case SslSessionState.Negotiation: this.AwaitClientKeyExchange(l7Data, frame); break; case SslSessionState.NegotiationChangeCipherSpec: this.AwaitChangeCipherSpecMessage(l7Data, frame); break; case SslSessionState.NegotiationFinished: this.AwaitFinishedMessage(l7Data, frame); break; case SslSessionState.Intermezzo: this.AwaitEncryptedMessage(l7Data, frame); break; case SslSessionState.DataExchange: this.AwaitEncryptedMessage(l7Data, frame); break; } } catch(NullReferenceException e) { // No L7 data PmConsolePrinter.PrintError("PDUDecrypter : " + e.Message + " : in frame " + frame.FrameIndex); } catch(NotImplementedException e) { ("PDUDecrypterCipher : " + e.Message).PrintInfo(); //return false; } } if(this._decryptedBytes != null) { //this.DataList.Add(new DecryptedData { Data = this._decryptedBytes, pdu = this._processedPdus.Last() }); this.DataList.Add(new DecryptedData { Data = this._decryptedBytes, PDU = this.Pdus.ElementAt(this._msgUnderReview) }); this._decryptedBytes = null; this.EndOfStream = false; } } while(this.Decrypter.ContinuationData != null) //Process remaining data in buffer { var l7Data = new byte[this.Decrypter.ContinuationData.Length]; Array.Copy(this.Decrypter.ContinuationData, l7Data, this.Decrypter.ContinuationData.Length); this.Decrypter.ContinuationData = null; try { this.AwaitEncryptedMessage(l7Data, this._previousFrame); } catch(NullReferenceException e) { // No L7 data PmConsolePrinter.PrintError("PDUDecrypter : " + e.Message + " : in frame " + this._previousFrame.FrameIndex); } catch(NotImplementedException e) { ("PDUDecrypterCipher : " + e.Message).PrintInfo(); //return false; } if(this._decryptedBytes != null) { this.DataList.Add(new DecryptedData { Data = this._decryptedBytes, PDU = this._processedPdus.Last() }); } this._decryptedBytes = null; this.EndOfStream = false; } this._dataDecrypted = true; return true; } private void AwaitEncryptedMessage(Byte[] l7Data, PmFrameBase pdu) { if(l7Data[0] == Record) { // record protocol this._state = this.Decrypter.DoDecryption(l7Data, pdu, ref this._decryptedBytes)? SslSessionState.DataExchange : SslSessionState.Intermezzo; } else if(l7Data[0] == Handshake) { // tls handshaking protocol // renegotiation // TODO could be Finished? this._msgUnderReview--; // TODO isn't renegotiation encrypted?? this._state = SslSessionState.NegotiationInit; } else if(l7Data[0] == ChangeCipherSpec && l7Data.Length > 6) // ChangeCipherSpec message has 6 bytes { // 'Finished' is in this pdu - TODO can be in next pdu? var finished = new Byte[l7Data.Length - 6]; Array.Copy(l7Data, 6, finished, 0, finished.Length); this.Decrypter.DoDecryption(finished, pdu, ref this._decryptedBytes); this._decryptedBytes = null; this._state = SslSessionState.Intermezzo; } else if(l7Data[0] == Alert) { // alert protocol // ignore this._state = SslSessionState.Intermezzo; } // else something wrong } private void AwaitClientKeyExchange(Byte[] l7Data, PmFrameBase pdu) { if(l7Data[0] == Handshake && l7Data[1] == Ssl3VerMajor && l7Data[5] == ClientKeyExchange) { this.Decrypter.ClientDirection = pdu.SrcAddress.GetAddressBytes(); this.Decrypter.KeyDecrypter.ParseClientKeyExchange(l7Data); var preMaster = this.Decrypter.KeyDecrypter.DecryptKey(); // use premaster to get ciphering key var master = this.Decrypter.Prf(preMaster, "master secret", this.Decrypter.ClientRnd, this.Decrypter.ServerRnd, 48, l7Data[2]); // Save Master key for current session SessionsMasterKeys.Add(this._currentSessionID, master); var keyBlock = this.Decrypter.Prf(master, "key expansion", this.Decrypter.ServerRnd, this.Decrypter.ClientRnd, this.Decrypter.DataDecrypter.MacKeyLength * 2 + this.Decrypter.DataDecrypter.KeyLength * 2 + this.Decrypter.DataDecrypter.IvLength * 2, l7Data[2]); this.Decrypter.ClientHMacKey = new Byte[this.Decrypter.DataDecrypter.MacKeyLength]; this.Decrypter.ServerHMacKey = new Byte[this.Decrypter.DataDecrypter.MacKeyLength]; Array.Copy(keyBlock, 0, this.Decrypter.ClientHMacKey, 0, this.Decrypter.DataDecrypter.MacKeyLength); Array.Copy(keyBlock, this.Decrypter.DataDecrypter.MacKeyLength, this.Decrypter.ServerHMacKey, 0, this.Decrypter.DataDecrypter.MacKeyLength); // Only part of key_block is used to encrypt data this.Decrypter.DataDecrypter.Init(keyBlock); // Look for finished - sent immediately after change cipher spec var totalLen = 0; do { var t = new Byte[2]; Array.Copy(l7Data, 3, t, 0, 2); Array.Reverse(t); totalLen += 5; totalLen += BitConverter.ToInt16(t, 0); } while(totalLen < l7Data.Length && l7Data[totalLen] != ChangeCipherSpec); if(totalLen < l7Data.Length) { // 'Finished' is in this pdu totalLen += 6; // ChangeCipherSpec message has 6 bytes var finished = new Byte[l7Data.Length - totalLen]; Array.Copy(l7Data, totalLen, finished, 0, finished.Length); this.Decrypter.DoDecryption(finished, pdu, ref this._decryptedBytes); this._decryptedBytes = null; this._state = SslSessionState.Intermezzo; } else { this._state = SslSessionState.NegotiationChangeCipherSpec; } } } private void AwaitChangeCipherSpecMessage(Byte[] l7Data, PmFrameBase pdu) { if(l7Data[0] == ChangeCipherSpec && l7Data[1] == Ssl3VerMajor && l7Data[5] == ChangeCipherSpecMessage) { //1 byte for content type //2 bytes for protocol version //2 bytes for message length //1 byte for change cypher spec message if(l7Data.Length > 6) //If finished message follows directly after Change Cipher Spec { var l7FinishedMsg = new byte[l7Data.Length - 6]; Array.Copy(l7Data, 6, l7FinishedMsg, 0, l7Data.Length - 6); this.AwaitFinishedMessage(l7FinishedMsg, pdu); } else this._state = SslSessionState.NegotiationFinished; } } private void AwaitFinishedMessage(Byte[] l7Data, PmFrameBase pdu) { if(l7Data[0] == Handshake && l7Data[1] == Ssl3VerMajor) { this.Decrypter.DoDecryption(l7Data, pdu, ref this._decryptedBytes); this._decryptedBytes = null; this._state = SslSessionState.Intermezzo; } } private void AwaitHelloMessages(Byte[] l7Data, PmFrameBase pdu) { // Get server hello message if(l7Data[0] == Handshake && l7Data[1] == Ssl3VerMajor && l7Data[5] == ServerHello) { this.Decrypter.ServerRnd = new Byte[32]; Array.Copy(l7Data, 11, this.Decrypter.ServerRnd, 0, this.Decrypter.ServerRnd.Length); ConversationCipherSuite conversationCipherSuite; KeyDecrypter keyDecrypter; DataDecrypter dataDecrypter; this.Decrypter.ChangeCipherSuite(l7Data, out conversationCipherSuite); this._conversation.CipherSuite = conversationCipherSuite; CipherSuiteInitializer.PrepareDecryptingAlgorithms(this._conversation.Key.ServerPrivateKey, this._conversation.CipherSuite, out keyDecrypter, out dataDecrypter); this.Decrypter.KeyDecrypter = keyDecrypter; this.Decrypter.DataDecrypter = dataDecrypter; // Get SSL Session ID and save it var sessionID = new Byte[32]; Array.Copy(l7Data, 44, sessionID, 0, 32); Array.Copy(sessionID, this._currentSessionID, this._currentSessionID.Length); // Get ServerHello content length var serverHelloContentLengthBytes = new Byte[2]; Array.Copy(l7Data, 3, serverHelloContentLengthBytes, 0, 2); Array.Reverse(serverHelloContentLengthBytes); var serverHelloContentLength = BitConverter.ToUInt16(serverHelloContentLengthBytes, 0); // Get total ServerHello length // ContentType(1B) Version(2B) Length(2B) Content var serverHelloLength = 1 + 2 + 2 + serverHelloContentLength; // Check whether there is something else after ServerHello message and whether it is ChangeCipherSpec message // If yes, session resumption is used if(serverHelloLength < l7Data.Length && l7Data[serverHelloLength + 0] == ChangeCipherSpec && SessionsMasterKeys.ContainsKey(sessionID)) { this.Decrypter.ClientDirection = pdu.DstAddress.GetAddressBytes(); // Load saved Master key for given Session ID var master = SessionsMasterKeys[sessionID]; var keyBlock = this.Decrypter.Prf(master, "key expansion", this.Decrypter.ServerRnd, this.Decrypter.ClientRnd, this.Decrypter.DataDecrypter.MacKeyLength * 2 + this.Decrypter.DataDecrypter.KeyLength * 2 + this.Decrypter.DataDecrypter.IvLength * 2, l7Data[2]); this.Decrypter.ClientHMacKey = new Byte[this.Decrypter.DataDecrypter.MacKeyLength]; this.Decrypter.ServerHMacKey = new Byte[this.Decrypter.DataDecrypter.MacKeyLength]; Array.Copy(keyBlock, 0, this.Decrypter.ClientHMacKey, 0, this.Decrypter.DataDecrypter.MacKeyLength); Array.Copy(keyBlock, this.Decrypter.DataDecrypter.MacKeyLength, this.Decrypter.ServerHMacKey, 0, this.Decrypter.DataDecrypter.MacKeyLength); // Only part of key_block is used to encrypt data this.Decrypter.DataDecrypter.Init(keyBlock); var changeCipherSpecLength = 6; if(serverHelloLength + changeCipherSpecLength < l7Data.Length) { var finishedOffset = serverHelloLength + changeCipherSpecLength; var finished = new Byte[l7Data.Length - finishedOffset]; Array.Copy(l7Data, finishedOffset, finished, 0, finished.Length); this.Decrypter.DoDecryption(finished, pdu, ref this._decryptedBytes); this._decryptedBytes = null; } this._state = SslSessionState.NegotiationChangeCipherSpec; } // Otherwise, new session is made else { this._state = SslSessionState.Negotiation; } } else if(l7Data[0] == Handshake && l7Data[1] == Ssl3VerMajor && l7Data[5] == ClientHello) { // client hello - should be found before server hello message this.Decrypter.ClientRnd = new Byte[32]; Array.Copy(l7Data, 11, this.Decrypter.ClientRnd, 0, this.Decrypter.ClientRnd.Length); } } /// <summary> Moves the given index PDU.</summary> /// <param name="indexPDU"> [in,out] The index PDU. </param> /// <returns> A bool.</returns> private delegate Boolean Move(ref Int32 indexPDU); /// <summary> The next.</summary> private readonly Move _next; private readonly Move _previous; private Boolean MovePrevious() { if(this._decryptedDataCnt <= 0) { return false; } this.DataList[this._decryptedDataCnt].DataOffset = 0; this._lastPDU = false; return this._previous(ref this._decryptedDataCnt); } private Boolean MoveNext() { if(this._lastPDU) { return false; } var readedPDUbytes = this.Current.DataLength; this.Current.DataOffset = this.Current.DataLength; this._lastPDU = !this._next(ref this._decryptedDataCnt); if(this._lastPDU) { return false; } this.TotalReadedPDUbytes += readedPDUbytes; this.Current.DataOffset = 0; return true; } /// <summary> /// Override in derivated classes to reached differant functionality in serving PDUs to stream. /// </summary> /// <param name="indexPDU"> [in,out] The index PDU. </param> /// <returns> true if it succeeds, false if it fails.</returns> private Boolean NextMixed(ref Int32 indexPDU) { Debug.Assert(indexPDU >= 0); if(indexPDU >= this.DataList.Count - 1) return false; indexPDU++; return true; } /// <summary> /// Override in derivated classes to reached differant functionality in serving PDUs to stream. /// </summary> /// <remarks> Pluskal, 2/10/2014.</remarks> /// <param name="indexPDU"> [in,out] The index PDU. </param> /// <returns> true if it succeeds, false if it fails.</returns> private Boolean PreviousMixed(ref Int32 indexPDU) { Debug.Assert(indexPDU >= 0); if(indexPDU == 0) { return false; } indexPDU--; return true; } /// <summary> Next continue interlay.</summary> /// <param name="indexpdu"> [in,out] The indexpdu. </param> /// <returns> true if it succeeds, false if it fails.</returns> private Boolean NextContinueInterlay(ref Int32 indexpdu) { var originalIndex = indexpdu; while(indexpdu != this.DataList.Count - 1) { indexpdu++; if(this.DataList.ElementAt(0).PDU.FlowDirection == this.DataList.ElementAt(indexpdu).PDU.FlowDirection) return true; } indexpdu = originalIndex; return false; } /// <summary> Previous continue interlay.</summary> /// <param name="indexpdu"> [in,out] The indexpdu. </param> /// <returns> true if it succeeds, false if it fails.</returns> private Boolean PreviousContinueInterlay(ref Int32 indexpdu) { while(indexpdu > 0) { indexpdu--; if(this.DataList.ElementAt(0).PDU.FlowDirection == this.DataList.ElementAt(indexpdu).PDU.FlowDirection) { return true; } } return false; } /// <summary> Next breaked.</summary> /// <param name="indexpdu"> [in,out] The indexpdu. </param> /// <returns> true if it succeeds, false if it fails.</returns> private Boolean NextBreaked(ref Int32 indexpdu) { while(indexpdu != this.DataList.Count - 1) { indexpdu++; if(this.DataList.ElementAt(0).PDU.FlowDirection == this.DataList.ElementAt(indexpdu).PDU.FlowDirection) return true; indexpdu--; return false; } return false; } /// <summary> Previous breaked.</summary> /// <param name="indexpdu"> [in,out] The indexpdu. </param> /// <returns> true if it succeeds, false if it fails.</returns> private Boolean PreviousBreaked(ref Int32 indexpdu) { while(indexpdu > 0) { indexpdu--; if(this.DataList.ElementAt(0).PDU.FlowDirection == this.DataList.ElementAt(indexpdu).PDU.FlowDirection) { return true; } indexpdu--; return false; } return false; } /// <summary> Next SingleMessage.</summary> /// <param name="indexpdu"> [in,out] The indexpdu. </param> /// <returns> true if it succeeds, false if it fails.</returns> private Boolean NextSingleMessage(ref Int32 indexpdu) => false; /// <summary> Previous SingleMessage.</summary> /// <param name="indexpdu"> [in,out] The indexpdu. </param> /// <returns> true if it succeeds, false if it fails.</returns> private Boolean PreviousSingleMessage(ref Int32 indexpdu) => false; public new Boolean EndOfStream { get; private set; } #endregion } }
using System; using Microsoft.Xna.Framework; namespace Paradix { public struct RectangleF : IShapeF, IEquatable<RectangleF> { public float X { get; set; } public float Y { get; set; } public float Width { get; set; } public float Height { get; set; } public float Left => X; public float Right => X + Width; public float Top => Y; public float Bottom => Y + Height; public Vector2 Position { get { return new Vector2 (X, Y); } set { X = value.X; Y = value.Y; } } public Vector2 Size { get { return new Vector2 (Width, Height); } set { Width = value.X; Height = value.Y; } } public Vector2 Center => new Vector2 (X + Width / 2f, Y + Height / 2f); public RectangleF BoundingRectangle => this; public RectangleF(float x, float y, float width, float height) { X = x; Y = y; Width = width; Height = height; } public RectangleF (Vector2 position, Vector2 size) : this(position.X, position.Y, size.X, size.Y) { } public RectangleF(Rectangle rectangle) : this (rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height) { } public bool Contains(int x, int y) { return (X <= x) && (x < X + Width) && (Y <= y) && (y < Y + Height); } public bool Contains(float x, float y) { return (X <= x) && (x < X + Width) && (Y <= y) && (y < Y + Height); } public bool Contains(Point value) { return (X <= value.X) && (value.X < X + Width) && (Y <= value.Y) && (value.Y < Y + Height); } public bool Contains(Vector2 value) { return (X <= value.X) && (value.X < X + Width) && (Y <= value.Y) && (value.Y < Y + Height); } public bool Contains(RectangleF value) { return (X <= value.X) && (value.X + value.Width <= X + Width) && (Y <= value.Y) && (value.Y + value.Height <= Y + Height); } public void Inflate (int horizontalAmount, int verticalAmount) { X -= horizontalAmount; Y -= verticalAmount; Width += horizontalAmount * 2; Height += verticalAmount * 2; } public void Inflate (float horizontalAmount, float verticalAmount) { X -= horizontalAmount; Y -= verticalAmount; Width += horizontalAmount * 2f; Height += verticalAmount * 2f; } public void Inflate (Vector2 amount) { Inflate (amount.X, amount.Y); } public bool Intersects (RectangleF value) { return (value.Left < Right) && (Left < value.Right) && (value.Top < Bottom) && (Top < value.Bottom); } public static RectangleF Union (RectangleF value1, RectangleF value2) { var x = Math.Min (value1.X, value2.X); var y = Math.Min (value1.Y, value2.Y); return new RectangleF (x, y, Math.Max (value1.Right, value2.Right) - x, Math.Max (value1.Bottom, value2.Bottom) - y); } public Vector2 IntersectionDepth (RectangleF other) { // Calculate half sizes. var thisHalfWidth = Width / 2.0f; var thisHalfHeight = Height / 2.0f; var otherHalfWidth = other.Width / 2.0f; var otherHalfHeight = other.Height / 2.0f; // Calculate centers. var centerA = new Vector2 (Left + thisHalfWidth, Top + thisHalfHeight); var centerB = new Vector2 (other.Left + otherHalfWidth, other.Top + otherHalfHeight); // Calculate current and minimum-non-intersecting distances between centers. var distanceX = centerA.X - centerB.X; var distanceY = centerA.Y - centerB.Y; var minDistanceX = thisHalfWidth + otherHalfWidth; var minDistanceY = thisHalfHeight + otherHalfHeight; // If we are not intersecting at all, return (0, 0). if ((Math.Abs (distanceX) >= minDistanceX) || (Math.Abs (distanceY) >= minDistanceY)) return Vector2.Zero; // Calculate and return intersection depths. var depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX; var depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY; return new Vector2 (depthX, depthY); } public static implicit operator RectangleF (Rectangle rectangle) { return new RectangleF (rectangle); } public static implicit operator RectangleF? (Rectangle? rect) { if (!rect.HasValue) return null; return new RectangleF (rect.Value); } public static implicit operator Rectangle (RectangleF rect) { return new Rectangle ((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height); } public static bool operator == (RectangleF a, RectangleF b) { return (Math.Abs (a.X - b.X) < float.Epsilon) && (Math.Abs (a.Y - b.Y) < float.Epsilon) && (Math.Abs (a.Width - b.Width) < float.Epsilon) && (Math.Abs (a.Height - b.Height) < float.Epsilon); } public static bool operator != (RectangleF a, RectangleF b) { return !(a == b); } public override bool Equals(object obj) { return obj is RectangleF && (this == (RectangleF) obj); } public bool Equals(RectangleF other) { return this == other; } public override string ToString() { return "{X:" + X + " Y:" + Y + " Width:" + Width + " Height:" + Height + "}"; } public override int GetHashCode () { return X.GetHashCode () ^ Y.GetHashCode () ^ Width.GetHashCode () ^ Height.GetHashCode (); } } }
using CoreAnimation; using CoreGraphics; using CoreVideo; using Foundation; using ObjCRuntime; using OpenGLES; using OpenTK.Graphics.ES20; using System; using UIKit; namespace RosyWriter { public partial class RosyWriterPreview : UIView { // Open GL Stuff private const int UNIFORM_Y = 0; private const int UNIFORM_UV = 1; private const int ATTRIB_VERTEX = 0; private const int ATTRIB_TEXCOORD = 1; private readonly EAGLContext context; private CVOpenGLESTextureCache videoTextureCache; private uint frameBuffer, colorBuffer; private int renderBufferWidth, renderBufferHeight; private int glProgram; public RosyWriterPreview(IntPtr handle) : base(handle) { // Initialize OpenGL ES 2 var eagleLayer = Layer as CAEAGLLayer; eagleLayer.Opaque = true; eagleLayer.DrawableProperties = new NSDictionary(EAGLDrawableProperty.RetainedBacking, false, EAGLDrawableProperty.ColorFormat, EAGLColorFormat.RGBA8); context = new EAGLContext(EAGLRenderingAPI.OpenGLES2); if (!EAGLContext.SetCurrentContext(context)) { throw new ApplicationException("Could not set EAGLContext"); } } [Export("layerClass")] public static Class LayerClass() { return new Class(typeof(CAEAGLLayer)); } #region Setup private bool CreateFrameBuffer() { var success = true; GL.Disable(EnableCap.DepthTest); GL.GenFramebuffers(1, out frameBuffer); GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBuffer); GL.GenRenderbuffers(1, out colorBuffer); GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, colorBuffer); context.RenderBufferStorage((uint)All.Renderbuffer, (CAEAGLLayer)Layer); GL.GetRenderbufferParameter(RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferWidth, out renderBufferWidth); GL.GetRenderbufferParameter(RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferHeight, out renderBufferHeight); GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, RenderbufferTarget.Renderbuffer, colorBuffer); if (GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) { Console.WriteLine("Failure with framebuffer generation"); success = false; } // Create a new CVOpenGLESTexture Cache videoTextureCache = CVOpenGLESTextureCache.FromEAGLContext(context); glProgram = CreateProgram(); return success && (glProgram != 0); } private static int CreateProgram() { // Create shader program int program = GL.CreateProgram(); // Create and Compile Vertex Shader int vertShader = 0; int fragShader = 0; var success = true; success = success && CompileShader(out vertShader, ShaderType.VertexShader, "Shaders/passThrough.vsh"); // Create and Compile fragment shader success = success && CompileShader(out fragShader, ShaderType.FragmentShader, "Shaders/passThrough.fsh"); // Attach Vertext Shader GL.AttachShader(program, vertShader); // Attach fragment shader GL.AttachShader(program, fragShader); // Bind attribute locations GL.BindAttribLocation(program, ATTRIB_VERTEX, "position"); GL.BindAttribLocation(program, ATTRIB_TEXCOORD, "textureCoordinate"); // Link program success = success && LinkProgram(program); if (success) { // Delete these ones, we do not need them anymore GL.DeleteShader(vertShader); GL.DeleteShader(fragShader); } else { Console.WriteLine("Failed to compile and link the shader programs"); GL.DeleteProgram(program); program = 0; } return program; } private static bool LinkProgram(int program) { GL.LinkProgram(program); GL.GetProgram(program, ProgramParameter.LinkStatus, out int status); if (status == 0) { GL.GetProgram(program, ProgramParameter.InfoLogLength, out int len); var sb = new System.Text.StringBuilder(len); GL.GetProgramInfoLog(program, len, out len, sb); Console.WriteLine("Link error: {0}", sb); } return status != 0; } private static bool CompileShader(out int shader, ShaderType type, string path) { string shaderProgram = System.IO.File.ReadAllText(path); int len = shaderProgram.Length; shader = GL.CreateShader(type); GL.ShaderSource(shader, 1, new[] { shaderProgram }, ref len); GL.CompileShader(shader); GL.GetShader(shader, ShaderParameter.CompileStatus, out int status); if (status == 0) { GL.DeleteShader(shader); return false; } return true; } #endregion #region Rendering public void DisplayPixelBuffer(CVImageBuffer imageBuffer) { // First check to make sure we have a FrameBuffer to write to. if (frameBuffer == 0) { var success = CreateFrameBuffer(); if (!success) { Console.WriteLine("Problem initializing OpenGL buffers."); return; } } if (videoTextureCache == null) { Console.WriteLine("Video Texture Cache not initialized"); return; } if (!(imageBuffer is CVPixelBuffer pixelBuffer)) { Console.WriteLine("Could not get Pixel Buffer from Image Buffer"); return; } // Create a CVOpenGLESTexture from the CVImageBuffer var frameWidth = (int)pixelBuffer.Width; var frameHeight = (int)pixelBuffer.Height; using (var texture = videoTextureCache.TextureFromImage(imageBuffer, true, All.Rgba, frameWidth, frameHeight, All.Bgra, DataType.UnsignedByte, 0, out CVReturn ret)) { if (texture == null || ret != CVReturn.Success) { Console.WriteLine("Could not create Texture from Texture Cache"); return; } GL.BindTexture(texture.Target, texture.Name); // Set texture parameters GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBuffer); // Set the view port to the entire view GL.Viewport(0, 0, renderBufferWidth, renderBufferHeight); var squareVerticies = new float[,] { { -1.0F, -1.0F}, { 1.0F, -1.0F }, { -1.0F, 1.0F }, { 1.0F, 1.0F } }; // The texture verticies are setup such that we flip the texture vertically. // This is so that our top left origin buffers match OpenGL's bottom left texture coordinate system. var textureSamplingRect = TextureSamplingRectForCroppingTextureWithAspectRatio(new CGSize(frameWidth, frameHeight), Bounds.Size); var textureVertices = new float[,] { {(float)textureSamplingRect.Left, (float)textureSamplingRect.Bottom}, {(float)textureSamplingRect.Right, (float)textureSamplingRect.Bottom}, {(float)textureSamplingRect.Left, (float)textureSamplingRect.Top}, {(float)textureSamplingRect.Right, (float)textureSamplingRect.Top} }; // Draw the texture on the screen with OpenGL ES 2 RenderWithSquareVerticies(squareVerticies, textureVertices); GL.BindTexture(texture.Target, texture.Name); // Flush the CVOpenGLESTexture cache and release the texture videoTextureCache.Flush(CVOptionFlags.None); } } private static CGRect TextureSamplingRectForCroppingTextureWithAspectRatio(CGSize textureAspectRatio, CGSize croppingAspectRatio) { CGRect normalizedSamplingRect; var cropScaleAmount = new CGSize(croppingAspectRatio.Width / textureAspectRatio.Width, croppingAspectRatio.Height / textureAspectRatio.Height); var maxScale = Math.Max(cropScaleAmount.Width, cropScaleAmount.Height); // HACK: double to nfloat var scaledTextureSize = new CGSize((nfloat)(textureAspectRatio.Width * maxScale), (nfloat)(textureAspectRatio.Height * maxScale)); // Changed the floats width, height to nfloats nfloat width, height; if (cropScaleAmount.Height > cropScaleAmount.Width) { width = croppingAspectRatio.Width / scaledTextureSize.Width; height = 1f; normalizedSamplingRect = new CGRect(0, 0, width, height); } else { height = croppingAspectRatio.Height / scaledTextureSize.Height; width = 1f; normalizedSamplingRect = new CGRect(0, 0, height, width); } // Center crop normalizedSamplingRect.X = (1f - normalizedSamplingRect.Size.Width) / 2f; normalizedSamplingRect.Y = (1f - normalizedSamplingRect.Size.Height) / 2f; return normalizedSamplingRect; } private void RenderWithSquareVerticies(float[,] squareVerticies, float[,] textureVerticies) { // Use Shader Program GL.UseProgram(glProgram); // Update attribute values GL.VertexAttribPointer(ATTRIB_VERTEX, 2, VertexAttribPointerType.Float, false, 0, squareVerticies); GL.EnableVertexAttribArray(ATTRIB_VERTEX); GL.VertexAttribPointer(ATTRIB_TEXCOORD, 2, VertexAttribPointerType.Float, false, 0, textureVerticies); GL.EnableVertexAttribArray(ATTRIB_TEXCOORD); // Validate program before drawing. (For Debugging purposes) #if DEBUG GL.ValidateProgram(glProgram); #endif GL.DrawArrays(BeginMode.TriangleStrip, 0, 4); // Present GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, colorBuffer); context.PresentRenderBuffer((uint)All.Renderbuffer); } #endregion } }
#region Header // // CmdListViews.cs - determine all the view // ports of a drawing sheet and vice versa // // Copyright (C) 2009-2021 by Jeremy Tammik, // Autodesk Inc. All rights reserved. // // Keywords: The Building Coder Revit API C# .NET add-in. // #endregion // Header #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; #endregion // Namespaces namespace BuildingCoder { [Transaction(TransactionMode.ReadOnly)] internal class CmdListViews : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { var app = commandData.Application; var doc = app.ActiveUIDocument.Document; var run_ViewSheetSet_Views_benchmark = true; if (run_ViewSheetSet_Views_benchmark) { var s = GetViewSheetSetViewsBenchmark(doc); var td = new TaskDialog( "ViewSheetSet.Views Benchmark"); td.MainContent = s; td.Show(); return Result.Succeeded; } var sheets = new FilteredElementCollector(doc); sheets.OfClass(typeof(ViewSheet)); // map with key = sheet element id and // value = list of viewport element ids: var mapSheetToViewport = new Dictionary<ElementId, List<ElementId>>(); // map with key = viewport element id and // value = sheet element id: var mapViewportToSheet = new Dictionary<ElementId, ElementId>(); foreach (ViewSheet sheet in sheets) { //int n = sheet.Views.Size; // 2014 var viewIds = sheet.GetAllPlacedViews(); // 2015 var n = viewIds.Count; Debug.Print( "Sheet {0} contains {1} view{2}: ", Util.ElementDescription(sheet), n, Util.PluralSuffix(n)); var idSheet = sheet.Id; var i = 0; foreach (var id in viewIds) { var v = doc.GetElement(id) as View; BoundingBoxXYZ bb; bb = v.get_BoundingBox(doc.ActiveView); Debug.Assert(null == bb, "expected null view bounding box"); bb = v.get_BoundingBox(sheet); Debug.Assert(null == bb, "expected null view bounding box"); var viewport = GetViewport(sheet, v); // null if not in active view: bb = viewport.get_BoundingBox(doc.ActiveView); var outline = v.Outline; Debug.WriteLine(" {0} {1} bb {2} outline {3}", ++i, Util.ElementDescription(v), null == bb ? "<null>" : Util.BoundingBoxString(bb), Util.BoundingBoxString(outline)); if (!mapSheetToViewport.ContainsKey(idSheet)) mapSheetToViewport.Add(idSheet, new List<ElementId>()); mapSheetToViewport[idSheet].Add(v.Id); Debug.Assert( !mapViewportToSheet.ContainsKey(v.Id), "expected viewport to be contained" + " in only one single sheet"); mapViewportToSheet.Add(v.Id, idSheet); } } return Result.Cancelled; } /// <summary> /// Return the viewport on the given /// sheet displaying the given view. /// </summary> private Element GetViewport(ViewSheet sheet, View view) { var doc = sheet.Document; // filter for view name: var bip = BuiltInParameter.VIEW_NAME; var provider = new ParameterValueProvider( new ElementId(bip)); FilterStringRuleEvaluator evaluator = new FilterStringEquals(); //FilterRule rule = new FilterStringRule( // 2021 // provider, evaluator, view.Name, true ); FilterRule rule = new FilterStringRule( // 2022 provider, evaluator, view.Name); var name_filter = new ElementParameterFilter(rule); var bic = BuiltInCategory.OST_Viewports; // retrieve the specific named viewport: //Element viewport // = new FilteredElementCollector( doc ) // .OfCategory( bic ) // .WherePasses( name_filter ) // .FirstElement(); //return viewport; // unfortunately, there are not just one, // but two candidate elements. apparently, // we can distibuish them using the // owner view id property: var viewports = new List<Element>( new FilteredElementCollector(doc) .OfCategory(bic) .WherePasses(name_filter) .ToElements()); Debug.Assert(viewports[0].OwnerViewId.Equals(ElementId.InvalidElementId), "expected the first viewport to have an invalid owner view id"); Debug.Assert(!viewports[1].OwnerViewId.Equals(ElementId.InvalidElementId), "expected the second viewport to have a valid owner view id"); var i = 1; return viewports[i]; } private string GetViewSheetSetViewsBenchmark(Document doc) { var sheetSets = new FilteredElementCollector(doc) .OfClass(typeof(ViewSheetSet)); var n = sheetSets.GetElementCount(); var result = $"Total of {n} sheet sets in this project.\n\n"; var stopWatch = new Stopwatch(); stopWatch.Start(); foreach (ViewSheetSet set in sheetSets) { result += set.Name; // getting the Views property takes around // 1.5 seconds on the given sample.rvt file. var views = set.Views; result += $" has {views.Size} views.\n"; } stopWatch.Stop(); double ms = stopWatch.ElapsedMilliseconds; result += $"\nOperation completed in {Math.Round(ms / 1000.0, 3)} seconds.\nAverage of {ms / n} ms per loop iteration."; return result; } } } // C:\a\j\adn\case\bsd\1266302\attach\rst_basic_sample_project_reinf.rvt
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Cluster { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.Metadata; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute; using Apache.Ignite.Core.Impl.Events; using Apache.Ignite.Core.Impl.Messaging; using Apache.Ignite.Core.Impl.Services; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Services; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Ignite projection implementation. /// </summary> internal class ClusterGroupImpl : PlatformTarget, IClusterGroupEx { /** Attribute: platform. */ private const string AttrPlatform = "org.apache.ignite.platform"; /** Platform. */ private const string Platform = "dotnet"; /** Initial topver; invalid from Java perspective, so update will be triggered when this value is met. */ private const int TopVerInit = 0; /** */ private const int OpAllMetadata = 1; /** */ private const int OpForAttribute = 2; /** */ private const int OpForCache = 3; /** */ private const int OpForClient = 4; /** */ private const int OpForData = 5; /** */ private const int OpForHost = 6; /** */ private const int OpForNodeIds = 7; /** */ private const int OpMetadata = 8; /** */ private const int OpMetrics = 9; /** */ private const int OpMetricsFiltered = 10; /** */ private const int OpNodeMetrics = 11; /** */ private const int OpNodes = 12; /** */ private const int OpPingNode = 13; /** */ private const int OpTopology = 14; /** */ private const int OpSchema = 15; /** Initial Ignite instance. */ private readonly Ignite _ignite; /** Predicate. */ private readonly Func<IClusterNode, bool> _pred; /** Topology version. */ private long _topVer = TopVerInit; /** Nodes for the given topology version. */ private volatile IList<IClusterNode> _nodes; /** Processor. */ private readonly IUnmanagedTarget _proc; /** Compute. */ private readonly Lazy<Compute> _comp; /** Messaging. */ private readonly Lazy<Messaging> _msg; /** Events. */ private readonly Lazy<Events> _events; /** Services. */ private readonly Lazy<IServices> _services; /// <summary> /// Constructor. /// </summary> /// <param name="proc">Processor.</param> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="ignite">Grid.</param> /// <param name="pred">Predicate.</param> [SuppressMessage("Microsoft.Performance", "CA1805:DoNotInitializeUnnecessarily")] public ClusterGroupImpl(IUnmanagedTarget proc, IUnmanagedTarget target, Marshaller marsh, Ignite ignite, Func<IClusterNode, bool> pred) : base(target, marsh) { _proc = proc; _ignite = ignite; _pred = pred; _comp = new Lazy<Compute>(() => new Compute(new ComputeImpl(UU.ProcessorCompute(proc, target), marsh, this, false))); _msg = new Lazy<Messaging>(() => new Messaging(UU.ProcessorMessage(proc, target), marsh, this)); _events = new Lazy<Events>(() => new Events(UU.ProcessorEvents(proc, target), marsh, this)); _services = new Lazy<IServices>(() => new Services(UU.ProcessorServices(proc, target), marsh, this, false, false)); } /** <inheritDoc /> */ public IIgnite Ignite { get { return _ignite; } } /** <inheritDoc /> */ public ICompute GetCompute() { return _comp.Value; } /** <inheritDoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { IgniteArgumentCheck.NotNull(nodes, "nodes"); return ForNodeIds0(nodes, node => node.Id); } /** <inheritDoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { IgniteArgumentCheck.NotNull(nodes, "nodes"); return ForNodeIds0(nodes, node => node.Id); } /** <inheritDoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { IgniteArgumentCheck.NotNull(ids, "ids"); return ForNodeIds0(ids, null); } /** <inheritDoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { IgniteArgumentCheck.NotNull(ids, "ids"); return ForNodeIds0(ids, null); } /// <summary> /// Internal routine to get projection for specific node IDs. /// </summary> /// <param name="items">Items.</param> /// <param name="func">Function to transform item to Guid (optional).</param> /// <returns></returns> private IClusterGroup ForNodeIds0<T>(IEnumerable<T> items, Func<T, Guid> func) { Debug.Assert(items != null); IUnmanagedTarget prj = DoProjetionOutOp(OpForNodeIds, writer => { WriteEnumerable(writer, items, func); }); return GetClusterGroup(prj); } /** <inheritDoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { var newPred = _pred == null ? p : node => _pred(node) && p(node); return new ClusterGroupImpl(_proc, Target, Marshaller, _ignite, newPred); } /** <inheritDoc /> */ public IClusterGroup ForAttribute(string name, string val) { IgniteArgumentCheck.NotNull(name, "name"); IUnmanagedTarget prj = DoProjetionOutOp(OpForAttribute, writer => { writer.WriteString(name); writer.WriteString(val); }); return GetClusterGroup(prj); } /// <summary> /// Creates projection with a specified op. /// </summary> /// <param name="name">Cache name to include into projection.</param> /// <param name="op">Operation id.</param> /// <returns> /// Projection over nodes that have specified cache running. /// </returns> private IClusterGroup ForCacheNodes(string name, int op) { IUnmanagedTarget prj = DoProjetionOutOp(op, writer => { writer.WriteString(name); }); return GetClusterGroup(prj); } /** <inheritDoc /> */ public IClusterGroup ForCacheNodes(string name) { return ForCacheNodes(name, OpForCache); } /** <inheritDoc /> */ public IClusterGroup ForDataNodes(string name) { return ForCacheNodes(name, OpForData); } /** <inheritDoc /> */ public IClusterGroup ForClientNodes(string name) { return ForCacheNodes(name, OpForClient); } /** <inheritDoc /> */ public IClusterGroup ForRemotes() { return GetClusterGroup(UU.ProjectionForRemotes(Target)); } /** <inheritDoc /> */ public IClusterGroup ForHost(IClusterNode node) { IgniteArgumentCheck.NotNull(node, "node"); IUnmanagedTarget prj = DoProjetionOutOp(OpForHost, writer => { writer.WriteGuid(node.Id); }); return GetClusterGroup(prj); } /** <inheritDoc /> */ public IClusterGroup ForRandom() { return GetClusterGroup(UU.ProjectionForRandom(Target)); } /** <inheritDoc /> */ public IClusterGroup ForOldest() { return GetClusterGroup(UU.ProjectionForOldest(Target)); } /** <inheritDoc /> */ public IClusterGroup ForYoungest() { return GetClusterGroup(UU.ProjectionForYoungest(Target)); } /** <inheritDoc /> */ public IClusterGroup ForServers() { return GetClusterGroup(UU.ProjectionForServers(Target)); } /** <inheritDoc /> */ public IClusterGroup ForDotNet() { return ForAttribute(AttrPlatform, Platform); } /** <inheritDoc /> */ public ICollection<IClusterNode> GetNodes() { return RefreshNodes(); } /** <inheritDoc /> */ public IClusterNode GetNode(Guid id) { return GetNodes().FirstOrDefault(node => node.Id == id); } /** <inheritDoc /> */ public IClusterNode GetNode() { return GetNodes().FirstOrDefault(); } /** <inheritDoc /> */ public IClusterMetrics GetMetrics() { if (_pred == null) { return DoInOp(OpMetrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null; }); } return DoOutInOp(OpMetricsFiltered, writer => { WriteEnumerable(writer, GetNodes().Select(node => node.Id)); }, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null; }); } /** <inheritDoc /> */ public IMessaging GetMessaging() { return _msg.Value; } /** <inheritDoc /> */ public IEvents GetEvents() { return _events.Value; } /** <inheritDoc /> */ public IServices GetServices() { return _services.Value; } /// <summary> /// Pings a remote node. /// </summary> /// <param name="nodeId">ID of a node to ping.</param> /// <returns>True if node for a given ID is alive, false otherwise.</returns> internal bool PingNode(Guid nodeId) { return DoOutOp(OpPingNode, nodeId) == True; } /// <summary> /// Predicate (if any). /// </summary> public Func<IClusterNode, bool> Predicate { get { return _pred; } } /// <summary> /// Refresh cluster node metrics. /// </summary> /// <param name="nodeId">Node</param> /// <param name="lastUpdateTime"></param> /// <returns></returns> internal ClusterMetricsImpl RefreshClusterNodeMetrics(Guid nodeId, long lastUpdateTime) { return DoOutInOp(OpNodeMetrics, writer => { writer.WriteGuid(nodeId); writer.WriteLong(lastUpdateTime); }, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null; } ); } /// <summary> /// Gets a topology by version. Returns null if topology history storage doesn't contain /// specified topology version (history currently keeps the last 1000 snapshots). /// </summary> /// <param name="version">Topology version.</param> /// <returns>Collection of Ignite nodes which represented by specified topology version, /// if it is present in history storage, {@code null} otherwise.</returns> /// <exception cref="IgniteException">If underlying SPI implementation does not support /// topology history. Currently only {@link org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi} /// supports topology history.</exception> internal ICollection<IClusterNode> Topology(long version) { return DoOutInOp(OpTopology, writer => writer.WriteLong(version), input => IgniteUtils.ReadNodes(Marshaller.StartUnmarshal(input))); } /// <summary> /// Topology version. /// </summary> internal long TopologyVersion { get { RefreshNodes(); return Interlocked.Read(ref _topVer); } } /// <summary> /// Update topology. /// </summary> /// <param name="newTopVer">New topology version.</param> /// <param name="newNodes">New nodes.</param> internal void UpdateTopology(long newTopVer, List<IClusterNode> newNodes) { lock (this) { // If another thread already advanced topology version further, we still // can safely return currently received nodes, but we will not assign them. if (_topVer < newTopVer) { Interlocked.Exchange(ref _topVer, newTopVer); _nodes = newNodes.AsReadOnly(); } } } /// <summary> /// Get current nodes without refreshing the topology. /// </summary> /// <returns>Current nodes.</returns> internal IList<IClusterNode> NodesNoRefresh() { return _nodes; } /// <summary> /// Creates new Cluster Group from given native projection. /// </summary> /// <param name="prj">Native projection.</param> /// <returns>New cluster group.</returns> private IClusterGroup GetClusterGroup(IUnmanagedTarget prj) { return new ClusterGroupImpl(_proc, prj, Marshaller, _ignite, _pred); } /// <summary> /// Refresh projection nodes. /// </summary> /// <returns>Nodes.</returns> private IList<IClusterNode> RefreshNodes() { long oldTopVer = Interlocked.Read(ref _topVer); List<IClusterNode> newNodes = null; DoOutInOp(OpNodes, writer => { writer.WriteLong(oldTopVer); }, input => { BinaryReader reader = Marshaller.StartUnmarshal(input); if (reader.ReadBoolean()) { // Topology has been updated. long newTopVer = reader.ReadLong(); newNodes = IgniteUtils.ReadNodes(reader, _pred); UpdateTopology(newTopVer, newNodes); } }); if (newNodes != null) return newNodes; // No topology changes. Debug.Assert(_nodes != null, "At least one topology update should have occurred."); return _nodes; } /// <summary> /// Perform synchronous out operation returning value. /// </summary> /// <param name="type">Operation type.</param> /// <param name="action">Action.</param> /// <returns>Native projection.</returns> private IUnmanagedTarget DoProjetionOutOp(int type, Action<BinaryWriter> action) { using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); action(writer); FinishMarshal(writer); return UU.ProjectionOutOpRet(Target, type, stream.SynchronizeOutput()); } } /** <inheritDoc /> */ public IBinaryType GetBinaryType(int typeId) { return DoOutInOp<IBinaryType>(OpMetadata, writer => writer.WriteInt(typeId), stream => { var reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new BinaryType(reader) : null; } ); } /// <summary> /// Gets metadata for all known types. /// </summary> public List<IBinaryType> GetBinaryTypes() { return DoInOp(OpAllMetadata, s => { var reader = Marshaller.StartUnmarshal(s); var size = reader.ReadInt(); var res = new List<IBinaryType>(size); for (var i = 0; i < size; i++) res.Add(reader.ReadBoolean() ? new BinaryType(reader) : null); return res; }); } /// <summary> /// Gets the schema. /// </summary> public int[] GetSchema(int typeId, int schemaId) { return DoOutInOp<int[]>(OpSchema, writer => { writer.WriteInt(typeId); writer.WriteInt(schemaId); }); } } }
//------------------------------------------------------------------------------ // <copyright file="DataGridViewLinkColumn.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System; using System.Text; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using System.Globalization; /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn"]/*' /> [ToolboxBitmapAttribute(typeof(DataGridViewLinkColumn), "DataGridViewLinkColumn.bmp")] public class DataGridViewLinkColumn : DataGridViewColumn { private static Type columnType = typeof(DataGridViewLinkColumn); private string text; /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.DataGridViewLinkColumn"]/*' /> public DataGridViewLinkColumn() : base(new DataGridViewLinkCell()) { } /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.ActiveLinkColor"]/*' /> [ SRCategory(SR.CatAppearance), SRDescription(SR.DataGridView_LinkColumnActiveLinkColorDescr) ] public Color ActiveLinkColor { get { if (this.CellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return ((DataGridViewLinkCell)this.CellTemplate).ActiveLinkColor; } set { if (!this.ActiveLinkColor.Equals(value)) { ((DataGridViewLinkCell)this.CellTemplate).ActiveLinkColorInternal = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.ActiveLinkColorInternal = value; } } this.DataGridView.InvalidateColumn(this.Index); } } } } private bool ShouldSerializeActiveLinkColor() { return !this.ActiveLinkColor.Equals(LinkUtilities.IEActiveLinkColor); } /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.CellTemplate"]/*' /> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public override DataGridViewCell CellTemplate { get { return base.CellTemplate; } set { if (value != null && !(value is System.Windows.Forms.DataGridViewLinkCell)) { throw new InvalidCastException(SR.GetString(SR.DataGridViewTypeColumn_WrongCellTemplateType, "System.Windows.Forms.DataGridViewLinkCell")); } base.CellTemplate = value; } } /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.LinkBehavior"]/*' /> [ DefaultValue(LinkBehavior.SystemDefault), SRCategory(SR.CatBehavior), SRDescription(SR.DataGridView_LinkColumnLinkBehaviorDescr) ] public LinkBehavior LinkBehavior { get { if (this.CellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return ((DataGridViewLinkCell)this.CellTemplate).LinkBehavior; } set { if (!this.LinkBehavior.Equals(value)) { ((DataGridViewLinkCell)this.CellTemplate).LinkBehavior = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.LinkBehaviorInternal = value; } } this.DataGridView.InvalidateColumn(this.Index); } } } } /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.LinkColor"]/*' /> [ SRCategory(SR.CatAppearance), SRDescription(SR.DataGridView_LinkColumnLinkColorDescr) ] public Color LinkColor { get { if (this.CellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return ((DataGridViewLinkCell)this.CellTemplate).LinkColor; } set { if (!this.LinkColor.Equals(value)) { ((DataGridViewLinkCell)this.CellTemplate).LinkColorInternal = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.LinkColorInternal = value; } } this.DataGridView.InvalidateColumn(this.Index); } } } } private bool ShouldSerializeLinkColor() { return !this.LinkColor.Equals(LinkUtilities.IELinkColor); } /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.Text"]/*' /> [ DefaultValue(null), SRCategory(SR.CatAppearance), SRDescription(SR.DataGridView_LinkColumnTextDescr) ] public string Text { get { return this.text; } set { if (!string.Equals(value, this.text, StringComparison.Ordinal)) { this.text = value; if (this.DataGridView != null) { if (this.UseColumnTextForLinkValue) { this.DataGridView.OnColumnCommonChange(this.Index); } else { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; if (dataGridViewCell != null && dataGridViewCell.UseColumnTextForLinkValue) { this.DataGridView.OnColumnCommonChange(this.Index); return; } } this.DataGridView.InvalidateColumn(this.Index); } } } } } /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.TrackVisitedState"]/*' /> [ DefaultValue(true), SRCategory(SR.CatBehavior), SRDescription(SR.DataGridView_LinkColumnTrackVisitedStateDescr) ] public bool TrackVisitedState { get { if (this.CellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return ((DataGridViewLinkCell)this.CellTemplate).TrackVisitedState; } set { if (this.TrackVisitedState != value) { ((DataGridViewLinkCell)this.CellTemplate).TrackVisitedStateInternal = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.TrackVisitedStateInternal = value; } } this.DataGridView.InvalidateColumn(this.Index); } } } } /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.UseColumnTextForLinkValue"]/*' /> [ DefaultValue(false), SRCategory(SR.CatAppearance), SRDescription(SR.DataGridView_LinkColumnUseColumnTextForLinkValueDescr) ] public bool UseColumnTextForLinkValue { get { if (this.CellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return ((DataGridViewLinkCell)this.CellTemplate).UseColumnTextForLinkValue; } set { if (this.UseColumnTextForLinkValue != value) { ((DataGridViewLinkCell)this.CellTemplate).UseColumnTextForLinkValueInternal = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.UseColumnTextForLinkValueInternal = value; } } this.DataGridView.OnColumnCommonChange(this.Index); } } } } /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.VisitedLinkColor"]/*' /> [ SRCategory(SR.CatAppearance), SRDescription(SR.DataGridView_LinkColumnVisitedLinkColorDescr) ] public Color VisitedLinkColor { get { if (this.CellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return ((DataGridViewLinkCell)this.CellTemplate).VisitedLinkColor; } set { if (!this.VisitedLinkColor.Equals(value)) { ((DataGridViewLinkCell)this.CellTemplate).VisitedLinkColorInternal = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.VisitedLinkColorInternal = value; } } this.DataGridView.InvalidateColumn(this.Index); } } } } private bool ShouldSerializeVisitedLinkColor() { return !this.VisitedLinkColor.Equals(LinkUtilities.IEVisitedLinkColor); } /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.Clone"]/*' /> public override object Clone() { DataGridViewLinkColumn dataGridViewColumn; Type thisType = this.GetType(); if (thisType == columnType) //performance improvement { dataGridViewColumn = new DataGridViewLinkColumn(); } else { // SECREVIEW : Late-binding does not represent a security threat, see bug#411899 for more info.. // dataGridViewColumn = (DataGridViewLinkColumn)System.Activator.CreateInstance(thisType); } if (dataGridViewColumn != null) { base.CloneInternal(dataGridViewColumn); dataGridViewColumn.Text = this.text; } return dataGridViewColumn; } /// <include file='doc\DataGridViewLinkColumn.uex' path='docs/doc[@for="DataGridViewLinkColumn.ToString"]/*' /> public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewLinkColumn { Name="); sb.Append(this.Name); sb.Append(", Index="); sb.Append(this.Index.ToString(CultureInfo.CurrentCulture)); sb.Append(" }"); return sb.ToString(); } } }
using System; using LanguageExt; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using LanguageExt.DataTypes.Serialisation; using LanguageExt.TypeClasses; using LanguageExt.ClassInstances; using LanguageExt.Common; using static LanguageExt.Prelude; namespace LanguageExt { public static partial class TryOptionAsyncT { static TryOptionAsync<A> ToTry<A>(Func<Task<OptionalResult<A>>> ma) => new TryOptionAsync<A>(ma); // // Collections // public static TryOptionAsync<Arr<B>> Traverse<A, B>(this Arr<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Arr<B>>> Go(Arr<TryOptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Arr<B>>(b.Exception)).Head() : rb.Exists(d => d.IsNone) ? OptionalResult<Arr<B>>.None : new OptionalResult<Arr<B>>(new Arr<B>(rb.Map(d => d.Value.Value))); } } public static TryOptionAsync<HashSet<B>> Traverse<A, B>(this HashSet<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<HashSet<B>>> Go(HashSet<TryOptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<HashSet<B>>(b.Exception)).Head() : rb.Exists(d => d.IsNone) ? OptionalResult<HashSet<B>>.None : new OptionalResult<HashSet<B>>(new HashSet<B>(rb.Map(d => d.Value.Value))); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static TryOptionAsync<IEnumerable<B>> Traverse<A, B>(this IEnumerable<TryOptionAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static TryOptionAsync<IEnumerable<B>> TraverseSerial<A, B>(this IEnumerable<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<IEnumerable<B>>> Go(IEnumerable<TryOptionAsync<A>> ma, Func<A, B> f) { var rb = new List<B>(); foreach (var a in ma) { var mb = await a.Try().ConfigureAwait(false); if (mb.IsFaulted) return new OptionalResult<IEnumerable<B>>(mb.Exception); if (mb.IsNone) return OptionalResult<IEnumerable<B>>.None; rb.Add(f(mb.Value.Value)); } return new OptionalResult<IEnumerable<B>>(rb); }; } public static TryOptionAsync<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<TryOptionAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, SysInfo.DefaultAsyncSequenceParallelism, f); public static TryOptionAsync<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<TryOptionAsync<A>> ma, int windowSize, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<IEnumerable<B>>> Go(IEnumerable<TryOptionAsync<A>> ma, Func<A, B> f) { var rb = await ma.Map(a => a.Map(f).Try()).WindowMap(windowSize, Prelude.identity).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<IEnumerable<B>>(b.Exception)).Head() : rb.Exists(d => d.IsNone) ? OptionalResult<IEnumerable<B>>.None : new OptionalResult<IEnumerable<B>>(rb.Map(d => d.Value.Value).ToArray()); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static TryOptionAsync<IEnumerable<A>> Sequence<A>(this IEnumerable<TryOptionAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static TryOptionAsync<IEnumerable<A>> SequenceSerial<A>(this IEnumerable<TryOptionAsync<A>> ma) => TraverseSerial(ma, Prelude.identity); public static TryOptionAsync<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<TryOptionAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static TryOptionAsync<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<TryOptionAsync<A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static TryOptionAsync<Lst<B>> Traverse<A, B>(this Lst<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Lst<B>>> Go(Lst<TryOptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Lst<B>>(b.Exception)).Head() : rb.Exists(d => d.IsNone) ? OptionalResult<Lst<B>>.None : new OptionalResult<Lst<B>>(new Lst<B>(rb.Map(d => d.Value.Value))); } } public static TryOptionAsync<Que<B>> Traverse<A, B>(this Que<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Que<B>>> Go(Que<TryOptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Que<B>>(b.Exception)).Head() : rb.Exists(d => d.IsNone) ? OptionalResult<Que<B>>.None : new OptionalResult<Que<B>>(new Que<B>(rb.Map(d => d.Value.Value))); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static TryOptionAsync<Seq<B>> Traverse<A, B>(this Seq<TryOptionAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static TryOptionAsync<Seq<B>> TraverseSerial<A, B>(this Seq<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Seq<B>>> Go(Seq<TryOptionAsync<A>> ma, Func<A, B> f) { var rb = new List<B>(); foreach (var a in ma) { var mb = await a.Try().ConfigureAwait(false); if (mb.IsFaulted) return new OptionalResult<Seq<B>>(mb.Exception); if(mb.IsNone) return OptionalResult<Seq<B>>.None; rb.Add(f(mb.Value.Value)); } return new OptionalResult<Seq<B>>(Seq.FromArray(rb.ToArray())); }; } public static TryOptionAsync<Seq<B>> TraverseParallel<A, B>(this Seq<TryOptionAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, SysInfo.DefaultAsyncSequenceParallelism, f); public static TryOptionAsync<Seq<B>> TraverseParallel<A, B>(this Seq<TryOptionAsync<A>> ma, int windowSize, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Seq<B>>> Go(Seq<TryOptionAsync<A>> ma, Func<A, B> f) { var rb = await ma.Map(a => a.Map(f).Try()).WindowMap(windowSize, Prelude.identity).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Seq<B>>(b.Exception)).Head() : rb.Exists(d => d.IsNone) ? OptionalResult<Seq<B>>.None : new OptionalResult<Seq<B>>(Seq.FromArray(rb.Map(d => d.Value.Value).ToArray())); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static TryOptionAsync<Seq<A>> Sequence<A>(this Seq<TryOptionAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static TryOptionAsync<Seq<A>> SequenceSerial<A>(this Seq<TryOptionAsync<A>> ma) => TraverseSerial(ma, Prelude.identity); public static TryOptionAsync<Seq<A>> SequenceParallel<A>(this Seq<TryOptionAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static TryOptionAsync<Seq<A>> SequenceParallel<A>(this Seq<TryOptionAsync<A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static TryOptionAsync<Set<B>> Traverse<A, B>(this Set<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Set<B>>> Go(Set<TryOptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Set<B>>(b.Exception)).Head() : rb.Exists(d => d.IsNone) ? OptionalResult<Set<B>>.None : new OptionalResult<Set<B>>(new Set<B>(rb.Map(d => d.Value.Value))); } } public static TryOptionAsync<Stck<B>> Traverse<A, B>(this Stck<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Stck<B>>> Go(Stck<TryOptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Reverse().Map(a => a.Map(f).Try())).ConfigureAwait(false); return rb.Exists(d => d.IsFaulted) ? rb.Filter(b => b.IsFaulted).Map(b => new OptionalResult<Stck<B>>(b.Exception)).Head() : rb.Exists(d => d.IsNone) ? OptionalResult<Stck<B>>.None : new OptionalResult<Stck<B>>(new Stck<B>(rb.Map(d => d.Value.Value))); } } // // Async types // public static TryOptionAsync<EitherAsync<L, B>> Traverse<L, A, B>(this EitherAsync<L, TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<EitherAsync<L, B>>> Go(EitherAsync<L, TryOptionAsync<A>> ma, Func<A, B> f) { var da = await ma.Data.ConfigureAwait(false); if (da.State == EitherStatus.IsBottom) return OptionalResult<EitherAsync<L, B>>.Bottom; if (da.State == EitherStatus.IsLeft) return new OptionalResult<EitherAsync<L, B>>(EitherAsync<L,B>.Left(da.Left)); var rb = await da.Right.Try().ConfigureAwait(false); if (rb.IsFaulted) return new OptionalResult<EitherAsync<L, B>>(rb.Exception); if(rb.IsNone) return OptionalResult<EitherAsync<L, B>>.None; return new OptionalResult<EitherAsync<L, B>>(EitherAsync<L, B>.Right(f(rb.Value.Value))); } } public static TryOptionAsync<OptionAsync<B>> Traverse<A, B>(this OptionAsync<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<OptionAsync<B>>> Go(OptionAsync<TryOptionAsync<A>> ma, Func<A, B> f) { var (isSome, value) = await ma.Data.ConfigureAwait(false); if (!isSome) return new OptionalResult<OptionAsync<B>>(OptionAsync<B>.None); var rb = await value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new OptionalResult<OptionAsync<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<OptionAsync<B>>.None; return new OptionalResult<OptionAsync<B>>(OptionAsync<B>.Some(f(rb.Value.Value))); } } public static TryOptionAsync<TryAsync<B>> Traverse<A, B>(this TryAsync<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<TryAsync<B>>> Go(TryAsync<TryOptionAsync<A>> ma, Func<A, B> f) { var ra = await ma.Try().ConfigureAwait(false); if (ra.IsFaulted) return new OptionalResult<TryAsync<B>>(TryAsync<B>(ra.Exception)); var rb = await ra.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new OptionalResult<TryAsync<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<TryAsync<B>>.None; return new OptionalResult<TryAsync<B>>(TryAsync<B>(f(rb.Value.Value))); } } public static TryOptionAsync<TryOptionAsync<B>> Traverse<A, B>(this TryOptionAsync<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<TryOptionAsync<B>>> Go(TryOptionAsync<TryOptionAsync<A>> ma, Func<A, B> f) { var ra = await ma.Try().ConfigureAwait(false); if (ra.IsFaulted) return new OptionalResult<TryOptionAsync<B>>(TryOptionAsync<B>(ra.Exception)); if (ra.IsNone) return new OptionalResult<TryOptionAsync<B>>(TryOptionAsync<B>(None)); var rb = await ra.Value.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new OptionalResult<TryOptionAsync<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<TryOptionAsync<B>>.None; return new OptionalResult<TryOptionAsync<B>>(TryOptionAsync<B>(f(rb.Value.Value))); } } public static TryOptionAsync<Task<B>> Traverse<A, B>(this Task<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Task<B>>> Go(Task<TryOptionAsync<A>> ma, Func<A, B> f) { var ra = await ma.ConfigureAwait(false); var rb = await ra.Try().ConfigureAwait(false); if (rb.IsFaulted) return new OptionalResult<Task<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<Task<B>>.None; return new OptionalResult<Task<B>>(f(rb.Value.Value).AsTask()); } } public static TryOptionAsync<ValueTask<B>> Traverse<A, B>(this ValueTask<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f).AsTask()); async ValueTask<OptionalResult<ValueTask<B>>> Go(ValueTask<TryOptionAsync<A>> ma, Func<A, B> f) { var ra = await ma.ConfigureAwait(false); var rb = await ra.Try().ConfigureAwait(false); if (rb.IsFaulted) return new OptionalResult<ValueTask<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<ValueTask<B>>.None; return new OptionalResult<ValueTask<B>>(f(rb.Value.Value).AsValueTask()); } } public static TryOptionAsync<Aff<B>> Traverse<A, B>(this Aff<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Aff<B>>> Go(Aff<TryOptionAsync<A>> ma, Func<A, B> f) { var ra = await ma.Run().ConfigureAwait(false); if (ra.IsFail) return new OptionalResult<Aff<B>>(FailAff<B>(ra.Error)); var rb = await ra.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new OptionalResult<Aff<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<Aff<B>>.None; return new OptionalResult<Aff<B>>(SuccessAff<B>(f(rb.Value.Value))); } } // // Sync types // public static TryOptionAsync<Either<L, B>> Traverse<L, A, B>(this Either<L, TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Either<L, B>>> Go(Either<L, TryOptionAsync<A>> ma, Func<A, B> f) { if(ma.IsBottom) return OptionalResult<Either<L, B>>.Bottom; if(ma.IsLeft) return new OptionalResult<Either<L, B>>(Left<L, B>(ma.LeftValue)); var rb = await ma.RightValue.Try().ConfigureAwait(false); if(rb.IsFaulted) return new OptionalResult<Either<L, B>>(rb.Exception); if(rb.IsNone) return OptionalResult<Either<L, B>>.None; return OptionalResult<Either<L, B>>.Some(f(rb.Value.Value)); } } public static TryOptionAsync<EitherUnsafe<L, B>> Traverse<L, A, B>(this EitherUnsafe<L, TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<EitherUnsafe<L, B>>> Go(EitherUnsafe<L, TryOptionAsync<A>> ma, Func<A, B> f) { if(ma.IsBottom) return OptionalResult<EitherUnsafe<L, B>>.Bottom; if(ma.IsLeft) return new OptionalResult<EitherUnsafe<L, B>>(LeftUnsafe<L, B>(ma.LeftValue)); var rb = await ma.RightValue.Try().ConfigureAwait(false); if(rb.IsFaulted) return new OptionalResult<EitherUnsafe<L, B>>(rb.Exception); if(rb.IsNone) return OptionalResult<EitherUnsafe<L, B>>.None; return OptionalResult<EitherUnsafe<L, B>>.Some(f(rb.Value.Value)); } } public static TryOptionAsync<Identity<B>> Traverse<A, B>(this Identity<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Identity<B>>> Go(Identity<TryOptionAsync<A>> ma, Func<A, B> f) { if(ma.IsBottom) return OptionalResult<Identity<B>>.Bottom; var rb = await ma.Value.Try().ConfigureAwait(false); if(rb.IsFaulted) return new OptionalResult<Identity<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<Identity<B>>.None; return OptionalResult<Identity<B>>.Some(new Identity<B>(f(rb.Value.Value))); } } public static TryOptionAsync<Fin<B>> Traverse<A, B>(this Fin<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Fin<B>>> Go(Fin<TryOptionAsync<A>> ma, Func<A, B> f) { if(ma.IsFail) return OptionalResult<Fin<B>>.Some(ma.Cast<B>()); var rb = await ma.Value.Try().ConfigureAwait(false); if(rb.IsFaulted) return new OptionalResult<Fin<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<Fin<B>>.None; return OptionalResult<Fin<B>>.Some(FinSucc(f(rb.Value.Value))); } } public static TryOptionAsync<Option<B>> Traverse<A, B>(this Option<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Option<B>>> Go(Option<TryOptionAsync<A>> ma, Func<A, B> f) { if(ma.IsNone) return OptionalResult<Option<B>>.Some(Option<B>.None); var rb = await ma.Value.Try().ConfigureAwait(false); if(rb.IsFaulted) return new OptionalResult<Option<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<Option<B>>.None; return OptionalResult<Option<B>>.Some(Some(f(rb.Value.Value))); } } public static TryOptionAsync<OptionUnsafe<B>> Traverse<A, B>(this OptionUnsafe<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<OptionUnsafe<B>>> Go(OptionUnsafe<TryOptionAsync<A>> ma, Func<A, B> f) { if(ma.IsNone) return OptionalResult<OptionUnsafe<B>>.Some(OptionUnsafe<B>.None); var rb = await ma.Value.Try().ConfigureAwait(false); if(rb.IsFaulted) return new OptionalResult<OptionUnsafe<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<OptionUnsafe<B>>.None; return OptionalResult<OptionUnsafe<B>>.Some(OptionUnsafe<B>.Some(f(rb.Value.Value))); } } public static TryOptionAsync<Try<B>> Traverse<A, B>(this Try<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Try<B>>> Go(Try<TryOptionAsync<A>> ma, Func<A, B> f) { var ra = ma.Try(); if (ra.IsFaulted) return new OptionalResult<Try<B>>(TryFail<B>(ra.Exception)); var rb = await ra.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new OptionalResult<Try<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<Try<B>>.None; return OptionalResult<Try<B>>.Some(Try<B>(f(rb.Value.Value))); } } public static TryOptionAsync<TryOption<B>> Traverse<A, B>(this TryOption<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<TryOption<B>>> Go(TryOption<TryOptionAsync<A>> ma, Func<A, B> f) { var ra = ma.Try(); if (ra.IsBottom) return OptionalResult<TryOption<B>>.Bottom; if (ra.IsNone) return new OptionalResult<TryOption<B>>(TryOptional<B>(None)); if (ra.IsFaulted) return new OptionalResult<TryOption<B>>(TryOptionFail<B>(ra.Exception)); var rb = await ra.Value.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new OptionalResult<TryOption<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<TryOption<B>>.None; return OptionalResult<TryOption<B>>.Some(TryOption<B>(f(rb.Value.Value))); } } public static TryOptionAsync<Validation<Fail, B>> Traverse<Fail, A, B>(this Validation<Fail, TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Validation<Fail, B>>> Go(Validation<Fail, TryOptionAsync<A>> ma, Func<A, B> f) { if(ma.IsFail) return new OptionalResult<Validation<Fail, B>>(Fail<Fail, B>(ma.FailValue)); var rb = await ma.SuccessValue.Try().ConfigureAwait(false); if(rb.IsFaulted) return new OptionalResult<Validation<Fail, B>>(rb.Exception); if(rb.IsNone) return OptionalResult<Validation<Fail, B>>.None; return OptionalResult<Validation<Fail, B>>.Some(f(rb.Value.Value)); } } public static TryOptionAsync<Validation<MonoidFail, Fail, B>> Traverse<MonoidFail, Fail, A, B>(this Validation<MonoidFail, Fail, TryOptionAsync<A>> ma, Func<A, B> f) where MonoidFail : struct, Monoid<Fail>, Eq<Fail> { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Validation<MonoidFail, Fail, B>>> Go(Validation<MonoidFail, Fail, TryOptionAsync<A>> ma, Func<A, B> f) { if(ma.IsFail) return new OptionalResult<Validation<MonoidFail, Fail, B>>(Fail<MonoidFail, Fail, B>(ma.FailValue)); var rb = await ma.SuccessValue.Try().ConfigureAwait(false); if(rb.IsFaulted) return new OptionalResult<Validation<MonoidFail, Fail, B>>(rb.Exception); if(rb.IsNone) return OptionalResult<Validation<MonoidFail, Fail, B>>.None; return OptionalResult<Validation<MonoidFail, Fail, B>>.Some(f(rb.Value.Value)); } } public static TryOptionAsync<Eff<B>> Traverse<A, B>(this Eff<TryOptionAsync<A>> ma, Func<A, B> f) { return ToTry(() => Go(ma, f)); async Task<OptionalResult<Eff<B>>> Go(Eff<TryOptionAsync<A>> ma, Func<A, B> f) { var ra = ma.Run(); if (ra.IsFail) return new OptionalResult<Eff<B>>(FailEff<B>(ra.Error)); var rb = await ra.Value.Try().ConfigureAwait(false); if (rb.IsFaulted) return new OptionalResult<Eff<B>>(rb.Exception); if(rb.IsNone) return OptionalResult<Eff<B>>.None; return OptionalResult<Eff<B>>.Some(SuccessEff<B>(f(rb.Value.Value))); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.TrafficManager; using Microsoft.WindowsAzure.Management.TrafficManager.Models; namespace Microsoft.WindowsAzure.Management.TrafficManager { /// <summary> /// The Windows Azure Traffic Manager management API provides a RESTful set /// of web services that interact with Windows Azure Traffic Manager /// service for creating, updating, listing, and deleting Traffic Manager /// profiles and definitions. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for /// more information) /// </summary> public partial class TrafficManagerManagementClient : ServiceClient<TrafficManagerManagementClient>, ITrafficManagerManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IDefinitionOperations _definitions; /// <summary> /// The Traffic Manager API includes operations for managing /// definitions for a specified profile. /// </summary> public virtual IDefinitionOperations Definitions { get { return this._definitions; } } private IProfileOperations _profiles; /// <summary> /// The Traffic Manager API includes operations for managing Traffic /// Manager profiles. /// </summary> public virtual IProfileOperations Profiles { get { return this._profiles; } } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient /// class. /// </summary> public TrafficManagerManagementClient() : base() { this._definitions = new DefinitionOperations(this); this._profiles = new ProfileOperations(this); this._apiVersion = "2011-10-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public TrafficManagerManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public TrafficManagerManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public TrafficManagerManagementClient(HttpClient httpClient) : base(httpClient) { this._definitions = new DefinitionOperations(this); this._profiles = new ProfileOperations(this); this._apiVersion = "2011-10-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public TrafficManagerManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public TrafficManagerManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// TrafficManagerManagementClient instance /// </summary> /// <param name='client'> /// Instance of TrafficManagerManagementClient to clone to /// </param> protected override void Clone(ServiceClient<TrafficManagerManagementClient> client) { base.Clone(client); if (client is TrafficManagerManagementClient) { TrafficManagerManagementClient clonedClient = ((TrafficManagerManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// Parse enum values for type DefinitionMonitorProtocol. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static DefinitionMonitorProtocol ParseDefinitionMonitorProtocol(string value) { if ("HTTP".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DefinitionMonitorProtocol.Http; } if ("HTTPS".Equals(value, StringComparison.OrdinalIgnoreCase)) { return DefinitionMonitorProtocol.Https; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type DefinitionMonitorProtocol to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string DefinitionMonitorProtocolToString(DefinitionMonitorProtocol value) { if (value == DefinitionMonitorProtocol.Http) { return "HTTP"; } if (value == DefinitionMonitorProtocol.Https) { return "HTTPS"; } throw new ArgumentOutOfRangeException("value"); } } }
using System; using Obscur.Core.Cryptography.Support.Math.EllipticCurve.Endomorphism; using Obscur.Core.Cryptography.Support.Math.EllipticCurve.Multiplier; using Obscur.Core.Cryptography.Support.Math.Field; namespace Obscur.Core.Cryptography.Support.Math.EllipticCurve { public class ECAlgorithms { public static bool IsF2mCurve(ECCurve c) { IFiniteField field = c.Field; return field.Dimension > 1 && field.Characteristic.Equals(BigInteger.Two) && field is IPolynomialExtensionField; } public static bool IsFpCurve(ECCurve c) { return c.Field.Dimension == 1; } public static ECPoint SumOfMultiplies(ECPoint[] ps, BigInteger[] ks) { if (ps == null || ks == null || ps.Length != ks.Length || ps.Length < 1) throw new ArgumentException("point and scalar arrays should be non-null, and of equal, non-zero, length"); int count = ps.Length; switch (count) { case 1: return ps[0].Multiply(ks[0]); case 2: return SumOfTwoMultiplies(ps[0], ks[0], ps[1], ks[1]); default: break; } ECPoint p = ps[0]; ECCurve c = p.Curve; ECPoint[] imported = new ECPoint[count]; imported[0] = p; for (int i = 1; i < count; ++i) { imported[i] = ImportPoint(c, ps[i]); } GlvEndomorphism glvEndomorphism = c.GetEndomorphism() as GlvEndomorphism; if (glvEndomorphism != null) { return ValidatePoint(ImplSumOfMultipliesGlv(imported, ks, glvEndomorphism)); } return ValidatePoint(ImplSumOfMultiplies(imported, ks)); } public static ECPoint SumOfTwoMultiplies(ECPoint P, BigInteger a, ECPoint Q, BigInteger b) { ECCurve cp = P.Curve; Q = ImportPoint(cp, Q); // Point multiplication for Koblitz curves (using WTNAF) beats Shamir's trick if (cp is F2mCurve) { F2mCurve f2mCurve = (F2mCurve)cp; if (f2mCurve.IsKoblitz) { return ValidatePoint(P.Multiply(a).Add(Q.Multiply(b))); } } GlvEndomorphism glvEndomorphism = cp.GetEndomorphism() as GlvEndomorphism; if (glvEndomorphism != null) { return ValidatePoint( ImplSumOfMultipliesGlv(new ECPoint[] { P, Q }, new BigInteger[] { a, b }, glvEndomorphism)); } return ValidatePoint(ImplShamirsTrickWNaf(P, a, Q, b)); } /* * "Shamir's Trick", originally due to E. G. Straus * (Addition chains of vectors. American Mathematical Monthly, * 71(7):806-808, Aug./Sept. 1964) * * Input: The points P, Q, scalar k = (km?, ... , k1, k0) * and scalar l = (lm?, ... , l1, l0). * Output: R = k * P + l * Q. * 1: Z <- P + Q * 2: R <- O * 3: for i from m-1 down to 0 do * 4: R <- R + R {point doubling} * 5: if (ki = 1) and (li = 0) then R <- R + P end if * 6: if (ki = 0) and (li = 1) then R <- R + Q end if * 7: if (ki = 1) and (li = 1) then R <- R + Z end if * 8: end for * 9: return R */ public static ECPoint ShamirsTrick(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { ECCurve cp = P.Curve; Q = ImportPoint(cp, Q); return ValidatePoint(ImplShamirsTrickJsf(P, k, Q, l)); } public static ECPoint ImportPoint(ECCurve c, ECPoint p) { ECCurve cp = p.Curve; if (!c.Equals(cp)) throw new ArgumentException("Point must be on the same curve"); return c.ImportPoint(p); } public static void MontgomeryTrick(ECFieldElement[] zs, int off, int len) { /* * Uses the "Montgomery Trick" to invert many field elements, with only a single actual * field inversion. See e.g. the paper: * "Fast Multi-scalar Multiplication Methods on Elliptic Curves with Precomputation Strategy Using Montgomery Trick" * by Katsuyuki Okeya, Kouichi Sakurai. */ ECFieldElement[] c = new ECFieldElement[len]; c[0] = zs[off]; int i = 0; while (++i < len) { c[i] = c[i - 1].Multiply(zs[off + i]); } ECFieldElement u = c[--i].Invert(); while (i > 0) { int j = off + i--; ECFieldElement tmp = zs[j]; zs[j] = c[i].Multiply(u); u = u.Multiply(tmp); } zs[off] = u; } /** * Simple shift-and-add multiplication. Serves as reference implementation * to verify (possibly faster) implementations, and for very small scalars. * * @param p * The point to multiply. * @param k * The multiplier. * @return The result of the point multiplication <code>kP</code>. */ public static ECPoint ReferenceMultiply(ECPoint p, BigInteger k) { BigInteger x = k.Abs(); ECPoint q = p.Curve.Infinity; int t = x.BitLength; if (t > 0) { if (x.TestBit(0)) { q = p; } for (int i = 1; i < t; i++) { p = p.Twice(); if (x.TestBit(i)) { q = q.Add(p); } } } return k.SignValue < 0 ? q.Negate() : q; } public static ECPoint ValidatePoint(ECPoint p) { if (!p.IsValid()) throw new ArgumentException("Invalid point", "p"); return p; } internal static ECPoint ImplShamirsTrickJsf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { ECCurve curve = P.Curve; ECPoint infinity = curve.Infinity; // TODO conjugate co-Z addition (ZADDC) can return both of these ECPoint PaddQ = P.Add(Q); ECPoint PsubQ = P.Subtract(Q); ECPoint[] points = new ECPoint[] { Q, PsubQ, P, PaddQ }; curve.NormalizeAll(points); ECPoint[] table = new ECPoint[] { points[3].Negate(), points[2].Negate(), points[1].Negate(), points[0].Negate(), infinity, points[0], points[1], points[2], points[3] }; byte[] jsf = WNafUtilities.GenerateJsf(k, l); ECPoint R = infinity; int i = jsf.Length; while (--i >= 0) { int jsfi = jsf[i]; // NOTE: The shifting ensures the sign is extended correctly int kDigit = ((jsfi << 24) >> 28), lDigit = ((jsfi << 28) >> 28); int index = 4 + (kDigit * 3) + lDigit; R = R.TwicePlus(table[index]); } return R; } internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { bool negK = k.SignValue < 0, negL = l.SignValue < 0; k = k.Abs(); l = l.Abs(); int widthP = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(k.BitLength))); int widthQ = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(l.BitLength))); WNafPreCompInfo infoP = WNafUtilities.Precompute(P, widthP, true); WNafPreCompInfo infoQ = WNafUtilities.Precompute(Q, widthQ, true); ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp; ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp; ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg; ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg; byte[] wnafP = WNafUtilities.GenerateWindowNaf(widthP, k); byte[] wnafQ = WNafUtilities.GenerateWindowNaf(widthQ, l); return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ); } internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPointMap pointMapQ, BigInteger l) { bool negK = k.SignValue < 0, negL = l.SignValue < 0; k = k.Abs(); l = l.Abs(); int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(k.BitLength, l.BitLength)))); ECPoint Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMapQ); WNafPreCompInfo infoP = WNafUtilities.GetWNafPreCompInfo(P); WNafPreCompInfo infoQ = WNafUtilities.GetWNafPreCompInfo(Q); ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp; ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp; ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg; ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg; byte[] wnafP = WNafUtilities.GenerateWindowNaf(width, k); byte[] wnafQ = WNafUtilities.GenerateWindowNaf(width, l); return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ); } private static ECPoint ImplShamirsTrickWNaf(ECPoint[] preCompP, ECPoint[] preCompNegP, byte[] wnafP, ECPoint[] preCompQ, ECPoint[] preCompNegQ, byte[] wnafQ) { int len = System.Math.Max(wnafP.Length, wnafQ.Length); ECCurve curve = preCompP[0].Curve; ECPoint infinity = curve.Infinity; ECPoint R = infinity; int zeroes = 0; for (int i = len - 1; i >= 0; --i) { int wiP = i < wnafP.Length ? (int)(sbyte)wnafP[i] : 0; int wiQ = i < wnafQ.Length ? (int)(sbyte)wnafQ[i] : 0; if ((wiP | wiQ) == 0) { ++zeroes; continue; } ECPoint r = infinity; if (wiP != 0) { int nP = System.Math.Abs(wiP); ECPoint[] tableP = wiP < 0 ? preCompNegP : preCompP; r = r.Add(tableP[nP >> 1]); } if (wiQ != 0) { int nQ = System.Math.Abs(wiQ); ECPoint[] tableQ = wiQ < 0 ? preCompNegQ : preCompQ; r = r.Add(tableQ[nQ >> 1]); } if (zeroes > 0) { R = R.TimesPow2(zeroes); zeroes = 0; } R = R.TwicePlus(r); } if (zeroes > 0) { R = R.TimesPow2(zeroes); } return R; } internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, BigInteger[] ks) { int count = ps.Length; bool[] negs = new bool[count]; WNafPreCompInfo[] infos = new WNafPreCompInfo[count]; byte[][] wnafs = new byte[count][]; for (int i = 0; i < count; ++i) { BigInteger ki = ks[i]; negs[i] = ki.SignValue < 0; ki = ki.Abs(); int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(ki.BitLength))); infos[i] = WNafUtilities.Precompute(ps[i], width, true); wnafs[i] = WNafUtilities.GenerateWindowNaf(width, ki); } return ImplSumOfMultiplies(negs, infos, wnafs); } internal static ECPoint ImplSumOfMultipliesGlv(ECPoint[] ps, BigInteger[] ks, GlvEndomorphism glvEndomorphism) { BigInteger n = ps[0].Curve.Order; int len = ps.Length; BigInteger[] abs = new BigInteger[len << 1]; for (int i = 0, j = 0; i < len; ++i) { BigInteger[] ab = glvEndomorphism.DecomposeScalar(ks[i].Mod(n)); abs[j++] = ab[0]; abs[j++] = ab[1]; } ECPointMap pointMap = glvEndomorphism.PointMap; if (glvEndomorphism.HasEfficientPointMap) { return ECAlgorithms.ImplSumOfMultiplies(ps, pointMap, abs); } ECPoint[] pqs = new ECPoint[len << 1]; for (int i = 0, j = 0; i < len; ++i) { ECPoint p = ps[i], q = pointMap.Map(p); pqs[j++] = p; pqs[j++] = q; } return ECAlgorithms.ImplSumOfMultiplies(pqs, abs); } internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, ECPointMap pointMap, BigInteger[] ks) { int halfCount = ps.Length, fullCount = halfCount << 1; bool[] negs = new bool[fullCount]; WNafPreCompInfo[] infos = new WNafPreCompInfo[fullCount]; byte[][] wnafs = new byte[fullCount][]; for (int i = 0; i < halfCount; ++i) { int j0 = i << 1, j1 = j0 + 1; BigInteger kj0 = ks[j0]; negs[j0] = kj0.SignValue < 0; kj0 = kj0.Abs(); BigInteger kj1 = ks[j1]; negs[j1] = kj1.SignValue < 0; kj1 = kj1.Abs(); int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(kj0.BitLength, kj1.BitLength)))); ECPoint P = ps[i], Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMap); infos[j0] = WNafUtilities.GetWNafPreCompInfo(P); infos[j1] = WNafUtilities.GetWNafPreCompInfo(Q); wnafs[j0] = WNafUtilities.GenerateWindowNaf(width, kj0); wnafs[j1] = WNafUtilities.GenerateWindowNaf(width, kj1); } return ImplSumOfMultiplies(negs, infos, wnafs); } private static ECPoint ImplSumOfMultiplies(bool[] negs, WNafPreCompInfo[] infos, byte[][] wnafs) { int len = 0, count = wnafs.Length; for (int i = 0; i < count; ++i) { len = System.Math.Max(len, wnafs[i].Length); } ECCurve curve = infos[0].PreComp[0].Curve; ECPoint infinity = curve.Infinity; ECPoint R = infinity; int zeroes = 0; for (int i = len - 1; i >= 0; --i) { ECPoint r = infinity; for (int j = 0; j < count; ++j) { byte[] wnaf = wnafs[j]; int wi = i < wnaf.Length ? (int)(sbyte)wnaf[i] : 0; if (wi != 0) { int n = System.Math.Abs(wi); WNafPreCompInfo info = infos[j]; ECPoint[] table = (wi < 0 == negs[j]) ? info.PreComp : info.PreCompNeg; r = r.Add(table[n >> 1]); } } if (r == infinity) { ++zeroes; continue; } if (zeroes > 0) { R = R.TimesPow2(zeroes); zeroes = 0; } R = R.TwicePlus(r); } if (zeroes > 0) { R = R.TimesPow2(zeroes); } return R; } } }
using System; using System.IO; namespace NBitcoin.BouncyCastle.Utilities.Encoders { public class Base64Encoder : IEncoder { protected readonly byte[] encodingTable = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; protected byte padding = (byte)'='; /* * set up the decoding table. */ protected readonly byte[] decodingTable = new byte[128]; protected void InitialiseDecodingTable() { Arrays.Fill(decodingTable, (byte)0xff); for (int i = 0; i < encodingTable.Length; i++) { decodingTable[encodingTable[i]] = (byte)i; } } public Base64Encoder() { InitialiseDecodingTable(); } /** * encode the input data producing a base 64 output stream. * * @return the number of bytes produced. */ public int Encode( byte[] data, int off, int length, Stream outStream) { int modulus = length % 3; int dataLength = (length - modulus); int a1, a2, a3; for (int i = off; i < off + dataLength; i += 3) { a1 = data[i] & 0xff; a2 = data[i + 1] & 0xff; a3 = data[i + 2] & 0xff; outStream.WriteByte(encodingTable[(int) ((uint) a1 >> 2) & 0x3f]); outStream.WriteByte(encodingTable[((a1 << 4) | (int) ((uint) a2 >> 4)) & 0x3f]); outStream.WriteByte(encodingTable[((a2 << 2) | (int) ((uint) a3 >> 6)) & 0x3f]); outStream.WriteByte(encodingTable[a3 & 0x3f]); } /* * process the tail end. */ int b1, b2, b3; int d1, d2; switch (modulus) { case 0: /* nothing left to do */ break; case 1: d1 = data[off + dataLength] & 0xff; b1 = (d1 >> 2) & 0x3f; b2 = (d1 << 4) & 0x3f; outStream.WriteByte(encodingTable[b1]); outStream.WriteByte(encodingTable[b2]); outStream.WriteByte(padding); outStream.WriteByte(padding); break; case 2: d1 = data[off + dataLength] & 0xff; d2 = data[off + dataLength + 1] & 0xff; b1 = (d1 >> 2) & 0x3f; b2 = ((d1 << 4) | (d2 >> 4)) & 0x3f; b3 = (d2 << 2) & 0x3f; outStream.WriteByte(encodingTable[b1]); outStream.WriteByte(encodingTable[b2]); outStream.WriteByte(encodingTable[b3]); outStream.WriteByte(padding); break; } return (dataLength / 3) * 4 + ((modulus == 0) ? 0 : 4); } private bool ignore( char c) { return (c == '\n' || c =='\r' || c == '\t' || c == ' '); } /** * decode the base 64 encoded byte data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int Decode( byte[] data, int off, int length, Stream outStream) { byte b1, b2, b3, b4; int outLen = 0; int end = off + length; while (end > off) { if (!ignore((char)data[end - 1])) { break; } end--; } int i = off; int finish = end - 4; i = nextI(data, i, finish); while (i < finish) { b1 = decodingTable[data[i++]]; i = nextI(data, i, finish); b2 = decodingTable[data[i++]]; i = nextI(data, i, finish); b3 = decodingTable[data[i++]]; i = nextI(data, i, finish); b4 = decodingTable[data[i++]]; if ((b1 | b2 | b3 | b4) >= 0x80) throw new IOException("invalid characters encountered in base64 data"); outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4))); outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2))); outStream.WriteByte((byte)((b3 << 6) | b4)); outLen += 3; i = nextI(data, i, finish); } outLen += decodeLastBlock(outStream, (char)data[end - 4], (char)data[end - 3], (char)data[end - 2], (char)data[end - 1]); return outLen; } private int nextI( byte[] data, int i, int finish) { while ((i < finish) && ignore((char)data[i])) { i++; } return i; } /** * decode the base 64 encoded string data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int DecodeString( string data, Stream outStream) { // Platform Implementation // byte[] bytes = Convert.FromBase64String(data); // outStream.Write(bytes, 0, bytes.Length); // return bytes.Length; byte b1, b2, b3, b4; int length = 0; int end = data.Length; while (end > 0) { if (!ignore(data[end - 1])) { break; } end--; } int i = 0; int finish = end - 4; i = nextI(data, i, finish); while (i < finish) { b1 = decodingTable[data[i++]]; i = nextI(data, i, finish); b2 = decodingTable[data[i++]]; i = nextI(data, i, finish); b3 = decodingTable[data[i++]]; i = nextI(data, i, finish); b4 = decodingTable[data[i++]]; if ((b1 | b2 | b3 | b4) >= 0x80) throw new IOException("invalid characters encountered in base64 data"); outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4))); outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2))); outStream.WriteByte((byte)((b3 << 6) | b4)); length += 3; i = nextI(data, i, finish); } length += decodeLastBlock(outStream, data[end - 4], data[end - 3], data[end - 2], data[end - 1]); return length; } private int decodeLastBlock( Stream outStream, char c1, char c2, char c3, char c4) { if (c3 == padding) { byte b1 = decodingTable[c1]; byte b2 = decodingTable[c2]; if ((b1 | b2) >= 0x80) throw new IOException("invalid characters encountered at end of base64 data"); outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4))); return 1; } if (c4 == padding) { byte b1 = decodingTable[c1]; byte b2 = decodingTable[c2]; byte b3 = decodingTable[c3]; if ((b1 | b2 | b3) >= 0x80) throw new IOException("invalid characters encountered at end of base64 data"); outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4))); outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2))); return 2; } { byte b1 = decodingTable[c1]; byte b2 = decodingTable[c2]; byte b3 = decodingTable[c3]; byte b4 = decodingTable[c4]; if ((b1 | b2 | b3 | b4) >= 0x80) throw new IOException("invalid characters encountered at end of base64 data"); outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4))); outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2))); outStream.WriteByte((byte)((b3 << 6) | b4)); return 3; } } private int nextI(string data, int i, int finish) { while ((i < finish) && ignore(data[i])) { i++; } return i; } } }
// 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.Contracts; using System.Security; using Internal.Runtime.CompilerHelpers; using Internal.Runtime.Augments; using Debug = System.Diagnostics.Debug; using System.Collections.Generic; using System.Threading; using System.Runtime.CompilerServices; #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System.Runtime.InteropServices { /// <summary> /// This PInvokeMarshal class should provide full public Marshal /// implementation for all things related to P/Invoke marshalling /// </summary> [CLSCompliant(false)] public partial class PInvokeMarshal { [ThreadStatic] internal static int s_lastWin32Error; public static int GetLastWin32Error() { return s_lastWin32Error; } public static void SetLastWin32Error(int errorCode) { s_lastWin32Error = errorCode; } public static unsafe IntPtr AllocHGlobal(IntPtr cb) { return MemAlloc(cb); } public static unsafe IntPtr AllocHGlobal(int cb) { return AllocHGlobal((IntPtr)cb); } public static void FreeHGlobal(IntPtr hglobal) { MemFree(hglobal); } public static unsafe IntPtr AllocCoTaskMem(int cb) { IntPtr allocatedMemory = CoTaskMemAlloc(new UIntPtr(unchecked((uint)cb))); if (allocatedMemory == IntPtr.Zero) { throw new OutOfMemoryException(); } return allocatedMemory; } public static void FreeCoTaskMem(IntPtr ptr) { CoTaskMemFree(ptr); } public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); return s.MarshalToString(globalAlloc: true, unicode: false); } public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); return s.MarshalToString(globalAlloc: true, unicode: true); ; } public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); return s.MarshalToString(globalAlloc: false, unicode: false); } public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); return s.MarshalToString(globalAlloc: false, unicode: true); } public static unsafe void CopyToManaged(IntPtr source, Array destination, int startIndex, int length) { if (source == IntPtr.Zero) throw new ArgumentNullException(nameof(source)); if (destination == null) throw new ArgumentNullException(nameof(destination)); if (!destination.IsBlittable()) throw new ArgumentException(nameof(destination), SR.Arg_CopyNonBlittableArray); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.Arg_CopyOutOfRange); if ((uint)startIndex + (uint)length > (uint)destination.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange); nuint bytesToCopy = (nuint)length * destination.ElementSize; nuint startOffset = (nuint)startIndex * destination.ElementSize; fixed (byte* pDestination = &destination.GetRawArrayData()) { byte* destinationData = pDestination + startOffset; Buffer.Memmove(destinationData, (byte*)source, bytesToCopy); } } public static unsafe void CopyToNative(Array source, int startIndex, IntPtr destination, int length) { if (source == null) throw new ArgumentNullException(nameof(source)); if (!source.IsBlittable()) throw new ArgumentException(nameof(source), SR.Arg_CopyNonBlittableArray); if (destination == IntPtr.Zero) throw new ArgumentNullException(nameof(destination)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.Arg_CopyOutOfRange); if ((uint)startIndex + (uint)length > (uint)source.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange); Contract.EndContractBlock(); nuint bytesToCopy = (nuint)length * source.ElementSize; nuint startOffset = (nuint)startIndex * source.ElementSize; fixed (byte* pSource = &source.GetRawArrayData()) { byte* sourceData = pSource + startOffset; Buffer.Memmove((byte*)destination, sourceData, bytesToCopy); } } public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index) { if (arr == null) throw new ArgumentNullException(nameof(arr)); byte* p = (byte*)Unsafe.AsPointer(ref arr.GetRawArrayData()) + (nuint)index * arr.ElementSize; return (IntPtr)p; } #region Delegate marshalling private static object s_thunkPoolHeap; /// <summary> /// Return the stub to the pinvoke marshalling stub /// </summary> /// <param name="del">The delegate</param> public static IntPtr GetStubForPInvokeDelegate(Delegate del) { if (del == null) return IntPtr.Zero; NativeFunctionPointerWrapper fpWrapper = del.Target as NativeFunctionPointerWrapper; if (fpWrapper != null) { // // Marshalling a delegate created from native function pointer back into function pointer // This is easy - just return the 'wrapped' native function pointer // return fpWrapper.NativeFunctionPointer; } else { // // Marshalling a managed delegate created from managed code into a native function pointer // return GetPInvokeDelegates().GetValue(del, s_AllocateThunk ?? (s_AllocateThunk = AllocateThunk)).Thunk; } } /// <summary> /// Used to lookup whether a delegate already has thunk allocated for it /// </summary> private static ConditionalWeakTable<Delegate, PInvokeDelegateThunk> s_pInvokeDelegates; private static ConditionalWeakTable<Delegate, PInvokeDelegateThunk>.CreateValueCallback s_AllocateThunk; private static ConditionalWeakTable<Delegate, PInvokeDelegateThunk> GetPInvokeDelegates() { // // Create the dictionary on-demand to avoid the dependency in the McgModule.ctor // Otherwise NUTC will complain that McgModule being eager ctor depends on a deferred // ctor type // if (s_pInvokeDelegates == null) { Interlocked.CompareExchange( ref s_pInvokeDelegates, new ConditionalWeakTable<Delegate, PInvokeDelegateThunk>(), null ); } return s_pInvokeDelegates; } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal unsafe struct ThunkContextData { public GCHandle Handle; // A weak GCHandle to the delegate public IntPtr FunctionPtr; // Function pointer for open static delegates } internal sealed class PInvokeDelegateThunk { public IntPtr Thunk; // Thunk pointer public IntPtr ContextData; // ThunkContextData pointer which will be stored in the context slot of the thunk public PInvokeDelegateThunk(Delegate del) { Thunk = RuntimeAugments.AllocateThunk(s_thunkPoolHeap); Debug.Assert(Thunk != IntPtr.Zero); if (Thunk == IntPtr.Zero) { // We've either run out of memory, or failed to allocate a new thunk due to some other bug. Now we should fail fast Environment.FailFast("Insufficient number of thunks."); } else { // // Allocate unmanaged memory for GCHandle of delegate and function pointer of open static delegate // We will store this pointer on the context slot of thunk data // ContextData = AllocHGlobal(2 * IntPtr.Size); unsafe { ThunkContextData* thunkData = (ThunkContextData*)ContextData; // allocate a weak GChandle for the delegate thunkData->Handle = GCHandle.Alloc(del, GCHandleType.Weak); // if it is an open static delegate get the function pointer thunkData->FunctionPtr = del.GetRawFunctionPointerForOpenStaticDelegate(); } } } ~PInvokeDelegateThunk() { // Free the thunk RuntimeAugments.FreeThunk(s_thunkPoolHeap, Thunk); unsafe { if (ContextData != IntPtr.Zero) { // free the GCHandle GCHandle handle = ((ThunkContextData*)ContextData)->Handle; if (handle != null) { handle.Free(); } // Free the allocated context data memory FreeHGlobal(ContextData); } } } } private static PInvokeDelegateThunk AllocateThunk(Delegate del) { if (s_thunkPoolHeap == null) { // TODO: Free s_thunkPoolHeap if the thread lose the race Interlocked.CompareExchange( ref s_thunkPoolHeap, RuntimeAugments.CreateThunksHeap(RuntimeImports.GetInteropCommonStubAddress()), null ); Debug.Assert(s_thunkPoolHeap != null); } var delegateThunk = new PInvokeDelegateThunk(del); McgPInvokeDelegateData pinvokeDelegateData; if (!RuntimeAugments.InteropCallbacks.TryGetMarshallerDataForDelegate(del.GetTypeHandle(), out pinvokeDelegateData)) { Environment.FailFast("Couldn't find marshalling stubs for delegate."); } // // For open static delegates set target to ReverseOpenStaticDelegateStub which calls the static function pointer directly // IntPtr pTarget = del.GetRawFunctionPointerForOpenStaticDelegate() == IntPtr.Zero ? pinvokeDelegateData.ReverseStub : pinvokeDelegateData.ReverseOpenStaticDelegateStub; RuntimeAugments.SetThunkData(s_thunkPoolHeap, delegateThunk.Thunk, delegateThunk.ContextData, pTarget); return delegateThunk; } /// <summary> /// Retrieve the corresponding P/invoke instance from the stub /// </summary> public static Delegate GetPInvokeDelegateForStub(IntPtr pStub, RuntimeTypeHandle delegateType) { if (pStub == IntPtr.Zero) return null; // // First try to see if this is one of the thunks we've allocated when we marshal a managed // delegate to native code // s_thunkPoolHeap will be null if there isn't any managed delegate to native // IntPtr pContext; IntPtr pTarget; if (s_thunkPoolHeap != null && RuntimeAugments.TryGetThunkData(s_thunkPoolHeap, pStub, out pContext, out pTarget)) { GCHandle handle; unsafe { // Pull out Handle from context handle = ((ThunkContextData*)pContext)->Handle; } Delegate target = InteropExtensions.UncheckedCast<Delegate>(handle.Target); // // The delegate might already been garbage collected // User should use GC.KeepAlive or whatever ways necessary to keep the delegate alive // until they are done with the native function pointer // if (target == null) { Environment.FailFast(SR.Delegate_GarbageCollected); } return target; } // // Otherwise, the stub must be a pure native function pointer // We need to create the delegate that points to the invoke method of a // NativeFunctionPointerWrapper derived class // McgPInvokeDelegateData pInvokeDelegateData; if (!RuntimeAugments.InteropCallbacks.TryGetMarshallerDataForDelegate(delegateType, out pInvokeDelegateData)) { return null; } return CalliIntrinsics.Call<Delegate>( pInvokeDelegateData.ForwardDelegateCreationStub, pStub ); } /// <summary> /// Retrieves the function pointer for the current open static delegate that is being called /// </summary> public static IntPtr GetCurrentCalleeOpenStaticDelegateFunctionPointer() { // // RH keeps track of the current thunk that is being called through a secret argument / thread // statics. No matter how that's implemented, we get the current thunk which we can use for // look up later // IntPtr pContext = RuntimeImports.GetCurrentInteropThunkContext(); Debug.Assert(pContext != null); IntPtr fnPtr; unsafe { // Pull out function pointer for open static delegate fnPtr = ((ThunkContextData*)pContext)->FunctionPtr; } Debug.Assert(fnPtr != null); return fnPtr; } /// <summary> /// Retrieves the current delegate that is being called /// </summary> public static T GetCurrentCalleeDelegate<T>() where T : class // constraint can't be System.Delegate { // // RH keeps track of the current thunk that is being called through a secret argument / thread // statics. No matter how that's implemented, we get the current thunk which we can use for // look up later // IntPtr pContext = RuntimeImports.GetCurrentInteropThunkContext(); Debug.Assert(pContext != null); GCHandle handle; unsafe { // Pull out Handle from context handle = ((ThunkContextData*)pContext)->Handle; } T target = InteropExtensions.UncheckedCast<T>(handle.Target); // // The delegate might already been garbage collected // User should use GC.KeepAlive or whatever ways necessary to keep the delegate alive // until they are done with the native function pointer // if (target == null) { Environment.FailFast(SR.Delegate_GarbageCollected); } return target; } [McgIntrinsics] private static unsafe class CalliIntrinsics { internal static T Call<T>(IntPtr pfn, IntPtr arg0) { throw new NotSupportedException(); } } #endregion #region String marshalling public static unsafe String PtrToStringUni(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); if (len < 0) throw new ArgumentException(nameof(len)); return new String((char*)ptr, 0, len); } public static unsafe String PtrToStringUni(IntPtr ptr) { if (IntPtr.Zero == ptr) { return null; } else if (IsWin32Atom(ptr)) { return null; } else { return new String((char*)ptr); } } public static unsafe void StringBuilderToUnicodeString(System.Text.StringBuilder stringBuilder, ushort* destination) { stringBuilder.UnsafeCopyTo((char*)destination); } public static unsafe void UnicodeStringToStringBuilder(ushort* newBuffer, System.Text.StringBuilder stringBuilder) { stringBuilder.ReplaceBuffer((char*)newBuffer); } public static unsafe void StringBuilderToAnsiString(System.Text.StringBuilder stringBuilder, byte* pNative, bool bestFit, bool throwOnUnmappableChar) { int len; // Convert StringBuilder to UNICODE string // Optimize for the most common case. If there is only a single char[] in the StringBuilder, // get it and convert it to ANSI char[] buffer = stringBuilder.GetBuffer(out len); if (buffer != null) { fixed (char* pManaged = buffer) { StringToAnsiString(pManaged, len, pNative, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar); } } else // Otherwise, convert StringBuilder to string and then convert to ANSI { string str = stringBuilder.ToString(); // Convert UNICODE string to ANSI string fixed (char* pManaged = str) { StringToAnsiString(pManaged, str.Length, pNative, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar); } } } public static unsafe void AnsiStringToStringBuilder(byte* newBuffer, System.Text.StringBuilder stringBuilder) { if (newBuffer == null) throw new ArgumentNullException(nameof(newBuffer)); int lenAnsi; int lenUnicode; CalculateStringLength(newBuffer, out lenAnsi, out lenUnicode); if (lenUnicode > 0) { char[] buffer = new char[lenUnicode]; fixed (char* pTemp = &buffer[0]) { ConvertMultiByteToWideChar(newBuffer, lenAnsi, pTemp, lenUnicode); } stringBuilder.ReplaceBuffer(buffer); } else { stringBuilder.Clear(); } } /// <summary> /// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG /// </summary> /// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string. /// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling /// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks> public static unsafe string AnsiStringToString(byte* pchBuffer) { if (pchBuffer == null) { return null; } int lenAnsi; int lenUnicode; CalculateStringLength(pchBuffer, out lenAnsi, out lenUnicode); string result = String.Empty; if (lenUnicode > 0) { result = string.FastAllocateString(lenUnicode); fixed (char* pTemp = result) { ConvertMultiByteToWideChar(pchBuffer, lenAnsi, pTemp, lenUnicode); } } return result; } /// <summary> /// Convert UNICODE string to ANSI string. /// </summary> /// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that /// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks> public static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar) { if (str != null) { int lenUnicode = str.Length; fixed (char* pManaged = str) { return StringToAnsiString(pManaged, lenUnicode, null, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar); } } return null; } /// <summary> /// Convert UNICODE wide char array to ANSI ByVal byte array. /// </summary> /// <remarks> /// * This version works with array instead string, it means that there will be NO NULL to terminate the array. /// * The buffer to store the byte array must be allocated by the caller and must fit managedArray.Length. /// </remarks> /// <param name="managedArray">UNICODE wide char array</param> /// <param name="pNative">Allocated buffer where the ansi characters must be placed. Could NOT be null. Buffer size must fit char[].Length.</param> public static unsafe void ByValWideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, int expectedCharCount, bool bestFit, bool throwOnUnmappableChar) { // Zero-init pNative if it is NULL if (managedArray == null) { Buffer.ZeroMemory((byte*)pNative, expectedCharCount); return; } int lenUnicode = managedArray.Length; if (lenUnicode < expectedCharCount) throw new ArgumentException(SR.WrongSizeArrayInNStruct); fixed (char* pManaged = managedArray) { StringToAnsiString(pManaged, lenUnicode, pNative, /*terminateWithNull=*/false, bestFit, throwOnUnmappableChar); } } public static unsafe void ByValAnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray) { // This should never happen because it is a embedded array Debug.Assert(pNative != null); // This should never happen because the array is always allocated by the marshaller Debug.Assert(managedArray != null); // COMPAT: Use the managed array length as the maximum length of native buffer // This obviously doesn't make sense but desktop CLR does that int lenInBytes = managedArray.Length; fixed (char* pManaged = managedArray) { ConvertMultiByteToWideChar(pNative, lenInBytes, pManaged, lenInBytes); } } public static unsafe void WideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, bool bestFit, bool throwOnUnmappableChar) { // Do nothing if array is NULL. This matches desktop CLR behavior if (managedArray == null) return; // Desktop CLR crash (AV at runtime) - we can do better in .NET Native if (pNative == null) throw new ArgumentNullException(nameof(pNative)); int lenUnicode = managedArray.Length; fixed (char* pManaged = managedArray) { StringToAnsiString(pManaged, lenUnicode, pNative, /*terminateWithNull=*/false, bestFit, throwOnUnmappableChar); } } /// <summary> /// Convert ANSI ByVal byte array to UNICODE wide char array, best fit /// </summary> /// <remarks> /// * This version works with array instead to string, it means that the len must be provided and there will be NO NULL to /// terminate the array. /// * The buffer to the UNICODE wide char array must be allocated by the caller. /// </remarks> /// <param name="pNative">Pointer to the ANSI byte array. Could NOT be null.</param> /// <param name="lenInBytes">Maximum buffer size.</param> /// <param name="managedArray">Wide char array that has already been allocated.</param> public static unsafe void AnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray) { // Do nothing if native is NULL. This matches desktop CLR behavior if (pNative == null) return; // Desktop CLR crash (AV at runtime) - we can do better in .NET Native if (managedArray == null) throw new ArgumentNullException(nameof(managedArray)); // COMPAT: Use the managed array length as the maximum length of native buffer // This obviously doesn't make sense but desktop CLR does that int lenInBytes = managedArray.Length; fixed (char* pManaged = managedArray) { ConvertMultiByteToWideChar(pNative, lenInBytes, pManaged, lenInBytes); } } /// <summary> /// Convert a single UNICODE wide char to a single ANSI byte. /// </summary> /// <param name="managedArray">single UNICODE wide char value</param> public static unsafe byte WideCharToAnsiChar(char managedValue, bool bestFit, bool throwOnUnmappableChar) { // @TODO - we really shouldn't allocate one-byte arrays and then destroy it byte* nativeArray = StringToAnsiString(&managedValue, 1, null, /*terminateWithNull=*/false, bestFit, throwOnUnmappableChar); byte native = (*nativeArray); CoTaskMemFree(new IntPtr(nativeArray)); return native; } /// <summary> /// Convert a single ANSI byte value to a single UNICODE wide char value, best fit. /// </summary> /// <param name="nativeValue">Single ANSI byte value.</param> public static unsafe char AnsiCharToWideChar(byte nativeValue) { char ch; ConvertMultiByteToWideChar(&nativeValue, 1, &ch, 1); return ch; } /// <summary> /// Convert UNICODE string to ANSI ByVal string. /// </summary> /// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that /// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks> /// <param name="str">Unicode string.</param> /// <param name="pNative"> Allocated buffer where the ansi string must be placed. Could NOT be null. Buffer size must fit str.Length.</param> public static unsafe void StringToByValAnsiString(string str, byte* pNative, int charCount, bool bestFit, bool throwOnUnmappableChar, bool truncate = true) { if (pNative == null) throw new ArgumentNullException(nameof(pNative)); if (str != null) { // Truncate the string if it is larger than specified by SizeConst int lenUnicode; if (truncate) { lenUnicode = str.Length; if (lenUnicode >= charCount) lenUnicode = charCount - 1; } else { lenUnicode = charCount; } fixed (char* pManaged = str) { StringToAnsiString(pManaged, lenUnicode, pNative, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar); } } else { (*pNative) = (byte)'\0'; } } /// <summary> /// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG /// </summary> /// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string. /// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling /// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks> public static unsafe string ByValAnsiStringToString(byte* pchBuffer, int charCount) { // Match desktop CLR behavior if (charCount == 0) throw new MarshalDirectiveException(); int lenAnsi = GetAnsiStringLen(pchBuffer); int lenUnicode = charCount; string result = String.Empty; if (lenUnicode > 0) { char* unicodeBuf = stackalloc char[lenUnicode]; int unicodeCharWritten = ConvertMultiByteToWideChar(pchBuffer, lenAnsi, unicodeBuf, lenUnicode); // If conversion failure, return empty string to match desktop CLR behavior if (unicodeCharWritten > 0) result = new string(unicodeBuf, 0, unicodeCharWritten); } return result; } private static unsafe int GetAnsiStringLen(byte* pchBuffer) { byte* pchBufferOriginal = pchBuffer; while (*pchBuffer != 0) { pchBuffer++; } return (int)(pchBuffer - pchBufferOriginal); } // c# string (UTF-16) to UTF-8 encoded byte array private static unsafe byte* StringToAnsiString(char* pManaged, int lenUnicode, byte* pNative, bool terminateWithNull, bool bestFit, bool throwOnUnmappableChar) { bool allAscii = true; for (int i = 0; i < lenUnicode; i++) { if (pManaged[i] >= 128) { allAscii = false; break; } } int length; if (allAscii) // If all ASCII, map one UNICODE character to one ANSI char { length = lenUnicode; } else // otherwise, let OS count number of ANSI chars { length = GetByteCount(pManaged, lenUnicode); } if (pNative == null) { pNative = (byte*)CoTaskMemAlloc((System.UIntPtr)(length + 1)); } if (allAscii) // ASCII conversion { byte* pDst = pNative; char* pSrc = pManaged; while (lenUnicode > 0) { unchecked { *pDst++ = (byte)(*pSrc++); lenUnicode--; } } } else // Let OS convert { ConvertWideCharToMultiByte(pManaged, lenUnicode, pNative, length, bestFit, throwOnUnmappableChar); } // Zero terminate if (terminateWithNull) *(pNative + length) = 0; return pNative; } /// <summary> /// This is a auxiliary function that counts the length of the ansi buffer and /// estimate the length of the buffer in Unicode. It returns true if all bytes /// in the buffer are ANSII. /// </summary> private static unsafe bool CalculateStringLength(byte* pchBuffer, out int ansiBufferLen, out int unicodeBufferLen) { ansiBufferLen = 0; bool allAscii = true; { byte* p = pchBuffer; byte b = *p++; while (b != 0) { if (b >= 128) { allAscii = false; } ansiBufferLen++; b = *p++; } } if (allAscii) { unicodeBufferLen = ansiBufferLen; } else // If non ASCII, let OS calculate number of characters { unicodeBufferLen = GetCharCount(pchBuffer, ansiBufferLen); } return allAscii; } #endregion } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using Windows.UI.ApplicationSettings; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using SDKTemplate; using Windows.Security.Credentials; using Windows.Security.Authentication.Web.Core; using System; using Windows.Storage; using System.Threading.Tasks; using System.Collections.Generic; using Windows.UI.Popups; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace Accounts { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class SingleAccountScenario : Page { private MainPage rootPage; const string AppSpecificProviderId = "myproviderid"; const string AppSpecificProviderName = "App specific provider"; const string MicrosoftProviderId = "https://login.microsoft.com"; const string MicrosoftAccountAuthority = "consumers"; const string AzureActiveDirectoryAuthority = "organizations"; const string StoredAccountIdKey = "accountid"; const string StoredProviderIdKey = "providerid"; const string StoredAuthorityKey = "authority"; const string MicrosoftAccountClientId = "none"; const string MicrosoftAccountScopeRequested = "service::wl.basic::DELEGATION"; // To obtain azureAD tokens, you must register this app on the AzureAD portal, and obtain the client ID const string AzureActiveDirectoryClientId = ""; const string AzureActiveDirectoryScopeRequested = ""; public SingleAccountScenario() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += OnAccountCommandsRequested; } protected override void OnNavigatedFrom(NavigationEventArgs e) { AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested; } private void Button_ShowAccountSettings(object sender, RoutedEventArgs e) { ((Button)sender).IsEnabled = false; rootPage.NotifyUser("Launching AccountSettingsPane", NotifyType.StatusMessage); AccountsSettingsPane.Show(); ((Button)sender).IsEnabled = true; } private async void Button_Reset(object sender, RoutedEventArgs e) { ((Button)sender).IsEnabled = false; rootPage.NotifyUser("Resetting...", NotifyType.StatusMessage); await LogoffAndRemoveAccount(); ((Button)sender).IsEnabled = true; } private async void OnAccountCommandsRequested( AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs e) { // In order to make async calls within this callback, the deferral object is needed AccountsSettingsPaneEventDeferral deferral = e.GetDeferral(); // This scenario only lets the user have one account at a time. // If there already is an account, we do not include a provider in the list // This will prevent the add account button from showing up. if (HasAccountStored()) { await AddWebAccountToPane(e); } else { await AddWebAccountProvidersToPane(e); } AddLinksAndDescription(e); deferral.Complete(); } private void AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs e) { e.HeaderText = "Describe what adding an account to your application will do for the user"; // You can add links such as privacy policy, help, general account settings e.Commands.Add(new SettingsCommand("privacypolicy", "Privacy Policy", PrivacyPolicyInvoked)); e.Commands.Add(new SettingsCommand("otherlink", "Other Link", OtherLinkInvoked)); } private async Task AddWebAccountProvidersToPane(AccountsSettingsPaneCommandsRequestedEventArgs e) { List<WebAccountProvider> providers = new List<WebAccountProvider>(); // Microsoft account and Azure AD providers will always return. Non-installed plugins or incorrect identities will return null providers.Add(await GetProvider(MicrosoftProviderId, MicrosoftAccountAuthority)); providers.Add(await GetProvider(MicrosoftProviderId, AzureActiveDirectoryAuthority)); providers.Add(await GetProvider(AppSpecificProviderId)); foreach (WebAccountProvider provider in providers) { WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked); e.WebAccountProviderCommands.Add(providerCommand); } } private async Task<WebAccount> GetWebAccount() { String accountID = ApplicationData.Current.LocalSettings.Values[StoredAccountIdKey] as String; String providerID = ApplicationData.Current.LocalSettings.Values[StoredProviderIdKey] as String; String authority = ApplicationData.Current.LocalSettings.Values[StoredAuthorityKey] as String; WebAccount account; WebAccountProvider provider = await GetProvider(providerID); if (providerID == AppSpecificProviderId) { account = new WebAccount(provider, accountID, WebAccountState.None); } else { account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID); // The account has been deleted if FindAccountAsync returns null if (account == null) { RemoveAccountData(); } } return account; } private async Task AddWebAccountToPane(AccountsSettingsPaneCommandsRequestedEventArgs e) { WebAccount account = await GetWebAccount(); WebAccountCommand command = new WebAccountCommand(account, WebAccountInvoked, SupportedWebAccountActions.Remove | SupportedWebAccountActions.Manage); e.WebAccountCommands.Add(command); } private async Task<WebAccountProvider> GetProvider(string ProviderID, string AuthorityId = "") { if (ProviderID == AppSpecificProviderId) { return new WebAccountProvider(AppSpecificProviderId, AppSpecificProviderName, new Uri(this.BaseUri, "Assets/smallTile-sdk.png")); } else { return await WebAuthenticationCoreManager.FindAccountProviderAsync(ProviderID, AuthorityId); } } private void OtherLinkInvoked(IUICommand command) { rootPage.NotifyUser("Other link pressed by user", NotifyType.StatusMessage); } private void PrivacyPolicyInvoked(IUICommand command) { rootPage.NotifyUser("Privacy policy clicked by user", NotifyType.StatusMessage); } private void WebAccountProviderCommandInvoked(WebAccountProviderCommand command) { if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == MicrosoftAccountAuthority)) { // ClientID is ignored by MSA AuthenticateWithRequestToken(command.WebAccountProvider, MicrosoftAccountScopeRequested, MicrosoftAccountClientId); } else if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == AzureActiveDirectoryAuthority)) { AuthenticateWithRequestToken(command.WebAccountProvider, AzureActiveDirectoryAuthority, AzureActiveDirectoryClientId); } else if (command.WebAccountProvider.Id == AppSpecificProviderId) { // Show user registration/login for your app specific account type. // Store the user if registration/login successful StoreNewAccountDataLocally(new WebAccount(command.WebAccountProvider, "App Specific User", WebAccountState.None)); } } public async void AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID) { try { WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID); // Azure Active Directory requires a resource to return a token if(Provider.Id == "https://login.microsoft.com" && Provider.Authority == "organizations") { webTokenRequest.Properties.Add("resource", "https://graph.windows.net"); } // If the user selected a specific account, RequestTokenAsync will return a token for that account. // The user may be prompted for credentials or to authorize using that account with your app // If the user selected a provider, the user will be prompted for credentials to login to a new account WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { StoreNewAccountDataLocally(webTokenRequestResult.ResponseData[0].WebAccount); } OutputTokenResult(webTokenRequestResult); } catch (Exception ex) { rootPage.NotifyUser("Web Token request failed: " + ex, NotifyType.ErrorMessage); } } public void StoreNewAccountDataLocally(WebAccount account) { if (account.Id != "") { ApplicationData.Current.LocalSettings.Values["AccountID"] = account.Id; } else { // It's a custom account ApplicationData.Current.LocalSettings.Values["AccountID"] = account.UserName; } ApplicationData.Current.LocalSettings.Values["ProviderID"] = account.WebAccountProvider.Id; if (account.WebAccountProvider.Authority != null) { ApplicationData.Current.LocalSettings.Values["Authority"] = account.WebAccountProvider.Authority; } else { ApplicationData.Current.LocalSettings.Values["Authority"] = ""; } } public void OutputTokenResult(WebTokenRequestResult result) { if (result.ResponseStatus == WebTokenRequestStatus.Success) { rootPage.NotifyUser("Web Token request successful for user:" + result.ResponseData[0].WebAccount.UserName, NotifyType.StatusMessage); } else { rootPage.NotifyUser("Web Token request error: " + result.ResponseStatus + " Code: " + result.ResponseError.ErrorMessage, NotifyType.StatusMessage); } } private async void WebAccountInvoked(WebAccountCommand command, WebAccountInvokedArgs args) { if (args.Action == WebAccountAction.Remove) { rootPage.NotifyUser("Removing account", NotifyType.StatusMessage); await LogoffAndRemoveAccount(); } else if (args.Action == WebAccountAction.Manage) { // Display user management UI for this account rootPage.NotifyUser("Managing account", NotifyType.StatusMessage); } } private bool HasAccountStored() { return (ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountIdKey) && ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredProviderIdKey) && ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAuthorityKey)); } private async Task LogoffAndRemoveAccount() { if (HasAccountStored()) { WebAccount account = await GetWebAccount(); // Check if the account has been deleted already by Token Broker if (account != null) { if (account.WebAccountProvider.Id == AppSpecificProviderId) { // perform actions to sign out of the app specific provider } else { await account.SignOutAsync(); } } account = null; RemoveAccountData(); } } private void RemoveAccountData() { ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountIdKey); ApplicationData.Current.LocalSettings.Values.Remove(StoredProviderIdKey); ApplicationData.Current.LocalSettings.Values.Remove(StoredAuthorityKey); } } }
/* * Copyright 2011 Matthew Beardmore * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Nini.Config; using OpenMetaverse; using Aurora.DataManager; using Aurora.Framework; namespace Aurora.Modules.Ban { public class LocalPresenceInfoConnector : IPresenceInfo { private IGenericData GD = null; private string DatabaseToAuthTable = "auth"; public void Initialize(IGenericData GenericData, IConfigSource source, IRegistryCore registry, string DefaultConnectionString) { if (source.Configs["AuroraConnectors"].GetString("PresenceInfoConnector", "LocalConnector") == "LocalConnector") { GD = GenericData; if (source.Configs[Name] != null) { DefaultConnectionString = source.Configs[Name].GetString("ConnectionString", DefaultConnectionString); DatabaseToAuthTable = source.Configs[Name].GetString("DatabasePathToAuthTable", DatabaseToAuthTable); } GD.ConnectToDatabase(DefaultConnectionString, "PresenceInfo", true); DataManager.DataManager.RegisterPlugin(this); } } public string Name { get { return "IPresenceInfo"; } } public void Dispose() { } public PresenceInfo GetPresenceInfo(UUID agentID) { PresenceInfo agent = new PresenceInfo(); Dictionary<string, object> where = new Dictionary<string, object>(1); where["AgentID"] = agentID; List<string> query = GD.Query(new[] { "*" }, "baninfo", new QueryFilter { andFilters = where }, null, null, null); if (query.Count == 0) //Couldn't find it, return null then. { return null; } agent.AgentID = agentID; if (query[1] != "") { agent.Flags = (PresenceInfo.PresenceInfoFlags)Enum.Parse(typeof(PresenceInfo.PresenceInfoFlags), query[1]); } agent.KnownAlts = Util.ConvertToList(query[2]); agent.KnownID0s = Util.ConvertToList(query[3]); agent.KnownIPs = Util.ConvertToList(query[4]); agent.KnownMacs = Util.ConvertToList(query[5]); agent.KnownViewers = Util.ConvertToList(query[6]); agent.LastKnownID0 = query[7]; agent.LastKnownIP = query[8]; agent.LastKnownMac = query[9]; agent.LastKnownViewer = query[10]; agent.Platform = query[11]; return agent; } public void UpdatePresenceInfo(PresenceInfo agent) { Dictionary<string, object> row = new Dictionary<string, object>(12); row["AgentID"] = agent.AgentID; row["Flags"] = agent.Flags; row["KnownAlts"] = Util.ConvertToString(agent.KnownAlts); row["KnownID0s"] = Util.ConvertToString(agent.KnownID0s); row["KnownIPs"] = Util.ConvertToString(agent.KnownIPs); row["KnownMacs"] = Util.ConvertToString(agent.KnownMacs); row["KnownViewers"] = Util.ConvertToString(agent.KnownViewers); row["LastKnownID0"] = agent.LastKnownID0; row["LastKnownIP"] = agent.LastKnownIP; row["LastKnownMac"] = agent.LastKnownMac; row["LastKnownViewer"] = agent.LastKnownViewer; row["Platform"] = agent.Platform; GD.Replace("baninfo", row); } public void Check(List<string> viewers, bool includeList) { List<string> query = GD.Query(new[] { "AgentID" }, "baninfo", new QueryFilter(), null, null, null); foreach (string ID in query) { //Check all Check(GetPresenceInfo(UUID.Parse(ID)), viewers, includeList); } } public void Check (PresenceInfo info, List<string> viewers, bool includeList) { // //Check passwords //Check IPs, Mac's, etc // bool needsUpdated = false; #region Check Password QueryFilter filter = new QueryFilter(); filter.andFilters["UUID"] = info.AgentID; List<string> query = GD.Query(new[] { "passwordHash" }, DatabaseToAuthTable, filter, null, null, null); if (query.Count != 0) { filter = new QueryFilter(); filter.andFilters["passwordHash"] = query[0]; query = GD.Query(new[] { "UUID" }, DatabaseToAuthTable, filter, null, null, null); foreach (string ID in query) { PresenceInfo suspectedInfo = GetPresenceInfo(UUID.Parse(ID)); if (suspectedInfo.AgentID == info.AgentID) { continue; } CoralateLists (info, suspectedInfo); needsUpdated = true; } } #endregion #region Check ID0, IP, Mac, etc //Only check suspected and known offenders in this scan // 2 == Flags filter = new QueryFilter(); query = GD.Query(new[] { "AgentID" }, "baninfo", filter, null, null, null); foreach (string ID in query) { PresenceInfo suspectedInfo = GetPresenceInfo(UUID.Parse(ID)); if (suspectedInfo == null || suspectedInfo.AgentID == info.AgentID) continue; foreach (string ID0 in suspectedInfo.KnownID0s) { if (info.KnownID0s.Contains(ID0)) { CoralateLists (info, suspectedInfo); needsUpdated = true; } } foreach (string IP in suspectedInfo.KnownIPs) { if (info.KnownIPs.Contains(IP.Split(':')[0])) { CoralateLists (info, suspectedInfo); needsUpdated = true; } } foreach (string Mac in suspectedInfo.KnownMacs) { if (info.KnownMacs.Contains(Mac)) { CoralateLists (info, suspectedInfo); needsUpdated = true; } } } foreach (string viewer in info.KnownViewers) { if (IsViewerBanned(viewer, includeList, viewers)) { if ((info.Flags & PresenceInfo.PresenceInfoFlags.Clean) == PresenceInfo.PresenceInfoFlags.Clean) { //Update them to suspected for their viewer AddFlag (ref info, PresenceInfo.PresenceInfoFlags.Suspected); //And update them later needsUpdated = true; } else if ((info.Flags & PresenceInfo.PresenceInfoFlags.Suspected) == PresenceInfo.PresenceInfoFlags.Suspected) { //Suspected, we don't really want to move them higher than this... } else if ((info.Flags & PresenceInfo.PresenceInfoFlags.Known) == PresenceInfo.PresenceInfoFlags.Known) { //Known, can't update anymore } } } if (DoGC(info) & !needsUpdated)//Clean up all info needsUpdated = true; #endregion //Now update ours if (needsUpdated) UpdatePresenceInfo(info); } public bool IsViewerBanned(string name, bool include, List<string> list) { if (include) { if (!list.Contains(name)) return true; } else { if (list.Contains(name)) return true; } return false; } private bool DoGC(PresenceInfo info) { bool update = false; List<string> newIPs = new List<string>(); foreach (string ip in info.KnownIPs) { string[] split; string newIP = ip; if ((split = ip.Split(':')).Length > 1) { //Remove the port if it exists and force an update newIP = split[0]; update = true; } if (!newIPs.Contains(newIP)) newIPs.Add(newIP); } if (info.KnownIPs.Count != newIPs.Count) update = true; info.KnownIPs = newIPs; return update; } private void CoralateLists (PresenceInfo info, PresenceInfo suspectedInfo) { bool addedFlag = false; const PresenceInfo.PresenceInfoFlags Flag = 0; if ((suspectedInfo.Flags & PresenceInfo.PresenceInfoFlags.Clean) == PresenceInfo.PresenceInfoFlags.Clean && (info.Flags & PresenceInfo.PresenceInfoFlags.Clean) == PresenceInfo.PresenceInfoFlags.Clean) { //They are both clean, do nothing } else if ((suspectedInfo.Flags & PresenceInfo.PresenceInfoFlags.Suspected) == PresenceInfo.PresenceInfoFlags.Suspected || (info.Flags & PresenceInfo.PresenceInfoFlags.Suspected) == PresenceInfo.PresenceInfoFlags.Suspected) { //Suspected, update them both addedFlag = true; AddFlag (ref info, PresenceInfo.PresenceInfoFlags.Suspected); AddFlag (ref suspectedInfo, PresenceInfo.PresenceInfoFlags.Suspected); } else if ((suspectedInfo.Flags & PresenceInfo.PresenceInfoFlags.Known) == PresenceInfo.PresenceInfoFlags.Known || (info.Flags & PresenceInfo.PresenceInfoFlags.Known) == PresenceInfo.PresenceInfoFlags.Known) { //Known, update them both addedFlag = true; AddFlag (ref info, PresenceInfo.PresenceInfoFlags.Known); AddFlag (ref suspectedInfo, PresenceInfo.PresenceInfoFlags.Known); } //Add the alt account flag AddFlag (ref info, PresenceInfo.PresenceInfoFlags.SuspectedAltAccount); AddFlag (ref suspectedInfo, PresenceInfo.PresenceInfoFlags.SuspectedAltAccount); if (suspectedInfo.Flags == PresenceInfo.PresenceInfoFlags.Suspected || suspectedInfo.Flags == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfSuspected || info.Flags == PresenceInfo.PresenceInfoFlags.Suspected || info.Flags == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfSuspected) { //They might be an alt, but the other is clean, so don't bother them too much AddFlag (ref info, PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfSuspected); AddFlag (ref suspectedInfo, PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfSuspected); } else if (suspectedInfo.Flags == PresenceInfo.PresenceInfoFlags.Known || suspectedInfo.Flags == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown || info.Flags == PresenceInfo.PresenceInfoFlags.Known || info.Flags == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown) { //Flag 'em AddFlag (ref info, PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown); AddFlag (ref suspectedInfo, PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown); } //Add the lists together List<string> alts = new List<string> (); foreach (string alt in info.KnownAlts) { if (!alts.Contains (alt)) alts.Add (alt); } foreach (string alt in suspectedInfo.KnownAlts) { if (!alts.Contains (alt)) alts.Add (alt); } if(!alts.Contains(suspectedInfo.AgentID.ToString())) alts.Add(suspectedInfo.AgentID.ToString()); if (!alts.Contains(info.AgentID.ToString())) alts.Add(info.AgentID.ToString()); //If we have added a flag, we need to update ALL alts as well if (addedFlag || alts.Count != 0) { foreach (string alt in alts.Where(s => s != suspectedInfo.AgentID.ToString() && s != info.AgentID.ToString())) { PresenceInfo altInfo = GetPresenceInfo (UUID.Parse (alt)); if (altInfo != null) { //Give them the flag as well AddFlag (ref altInfo, Flag); //Add the alt account flag AddFlag (ref altInfo, PresenceInfo.PresenceInfoFlags.SuspectedAltAccount); //Also give them the flags for alts if (suspectedInfo.Flags == PresenceInfo.PresenceInfoFlags.Suspected || suspectedInfo.Flags == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfSuspected || info.Flags == PresenceInfo.PresenceInfoFlags.Suspected || info.Flags == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfSuspected) { //They might be an alt, but the other is clean, so don't bother them too much AddFlag (ref altInfo, PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfSuspected); } else if (suspectedInfo.Flags == PresenceInfo.PresenceInfoFlags.Known || suspectedInfo.Flags == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown || info.Flags == PresenceInfo.PresenceInfoFlags.Known || info.Flags == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown) { //Flag 'em AddFlag (ref altInfo, PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown); } altInfo.KnownAlts = new List<string>(alts.Where(s => s != altInfo.AgentID.ToString())); //And update them in the db UpdatePresenceInfo(altInfo); } } } //Replace both lists now that they are merged info.KnownAlts = new List<string>(alts.Where(s => s != info.AgentID.ToString())); suspectedInfo.KnownAlts = new List<string>(alts.Where(s => s != suspectedInfo.AgentID.ToString())); //Update them, as we changed their info, we get updated below UpdatePresenceInfo (suspectedInfo); } private void AddFlag (ref PresenceInfo info, PresenceInfo.PresenceInfoFlags presenceInfoFlags) { if (presenceInfoFlags == 0) return; info.Flags &= PresenceInfo.PresenceInfoFlags.Clean; //Remove clean if (presenceInfoFlags == PresenceInfo.PresenceInfoFlags.Known) info.Flags &= PresenceInfo.PresenceInfoFlags.Clean; //Remove suspected as well info.Flags |= presenceInfoFlags; //Add the flag } } }
/// Draws a circular reticle in front of any object that the user gazes at. /// The circle dilates if the object is clickable. // Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; [AddComponentMenu("Input/Gaze/CircularReticle")] [RequireComponent(typeof(Renderer))] public class CircularReticle : MonoBehaviour, IGazePointer { /// Number of segments making the reticle circle. public int reticleSegments = 20; /// Growth speed multiplier for the reticle public float reticleGrowthSpeed = 8.0f; // Minimum distance of the reticle (in meters). public float kReticleDistanceMin = 0.45f; // Maximum distance of the reticle (in meters). public float kReticleDistanceMax = 10.0f; // Minimum inner angle of the reticle (in degrees). public float kReticleMinInnerAngle = 0.0f; // Minimum outer angle of the reticle (in degrees). public float kReticleMinOuterAngle = 0.5f; // Angle at which to expand the reticle when intersecting with an object // (in degrees). public float kReticleGrowthAngle = 1.5f; void Start () { CreateReticleVertices(); materialComp = gameObject.GetComponent<Renderer>().material; } void OnEnable() { //GazeInputModule.gazePointer = this; } void OnDisable() { //if (GazeInputModule.gazePointer == (IGazePointer) this) { // GazeInputModule.gazePointer = null; } } void Update() { UpdateDiameters(); } /// This is called when the 'BaseInputModule' system should be enabled. public void OnGazeEnabled() { // nothing to do here (yet) } /// This is called when the 'BaseInputModule' system should be disabled. public void OnGazeDisabled() { // nothing to do here (yet) } /// Called when the user is looking on a valid GameObject. This can be a 3D /// or UI element. /// /// The camera is the event camera, the target is the object /// the user is looking at, and the intersectionPosition is the intersection /// point of the ray sent from the camera on the object. public void OnGazeStart(Camera camera, GameObject targetObject, Vector3 intersectionPosition, bool isInteractive) { SetGazeTarget(intersectionPosition, isInteractive); } /// Called every frame the user is still looking at a valid GameObject. This /// can be a 3D or UI element. /// /// The camera is the event camera, the target is the object the user is /// looking at, and the intersectionPosition is the intersection point of the /// ray sent from the camera on the object. public void OnGazeStay(Camera camera, GameObject targetObject, Vector3 intersectionPosition, float fuseProgress, bool isInteractive) { SetGazeTarget(intersectionPosition, isInteractive); } /// Called when the user's look no longer intersects an object previously /// intersected with a ray projected from the camera. /// This is also called just before **OnGazeDisabled** and may have have any of /// the values set as **null**. /// /// The camera is the event camera and the target is the object the user /// previously looked at. public void OnGazeExit(Camera camera, GameObject targetObject) { reticleDistanceInMeters = kReticleDistanceMax; reticleInnerAngle = kReticleMinInnerAngle; reticleOuterAngle = kReticleMinOuterAngle; } /// Called when a trigger event is initiated. This is practically when /// the user begins pressing the trigger. public void OnGazeTriggerStart(Camera camera) { // Put your reticle trigger start logic here :) } /// Called when a trigger event is finished. This is practically when /// the user releases the trigger. public void OnGazeTriggerEnd(Camera camera) { // Put your reticle trigger end logic here :) } public void GetPointerRadius(out float innerRadius, out float outerRadius) { float min_inner_angle_radians = Mathf.Deg2Rad * kReticleMinInnerAngle; float max_inner_angle_radians = Mathf.Deg2Rad * (kReticleMinInnerAngle + kReticleGrowthAngle); innerRadius = 2.0f * Mathf.Tan(min_inner_angle_radians); outerRadius = 2.0f * Mathf.Tan(max_inner_angle_radians); } public void GetDistanceLimits(out float minimumDistance, out float maximumDistance) { minimumDistance = kReticleDistanceMin; maximumDistance = kReticleDistanceMax; } private void CreateReticleVertices() { Mesh mesh = new Mesh(); gameObject.AddComponent<MeshFilter>(); GetComponent<MeshFilter>().mesh = mesh; int segments_count = reticleSegments; int vertex_count = (segments_count + 1)*2; #region Vertices Vector3[] vertices = new Vector3[vertex_count]; const float kTwoPi = Mathf.PI * 2.0f; int vi = 0; for (int si = 0; si <= segments_count; ++si) { // Add two vertices for every circle segment: one at the beginning of the // prism, and one at the end of the prism. float angle = (float)si / (float)(segments_count) * kTwoPi; float x = Mathf.Sin(angle); float y = Mathf.Cos(angle); vertices[vi++] = new Vector3(x, y, 0.0f); // Outer vertex. vertices[vi++] = new Vector3(x, y, 1.0f); // Inner vertex. } #endregion #region Triangles int indices_count = (segments_count+1)*3*2; int[] indices = new int[indices_count]; int vert = 0; int idx = 0; for (int si = 0; si < segments_count; ++si) { indices[idx++] = vert+1; indices[idx++] = vert; indices[idx++] = vert+2; indices[idx++] = vert+1; indices[idx++] = vert+2; indices[idx++] = vert+3; vert += 2; } #endregion mesh.vertices = vertices; mesh.triangles = indices; mesh.RecalculateBounds(); } private void UpdateDiameters() { reticleDistanceInMeters = Mathf.Clamp(reticleDistanceInMeters, kReticleDistanceMin, kReticleDistanceMax); reticleInnerAngle = Mathf.Max(reticleInnerAngle, kReticleMinInnerAngle); reticleOuterAngle = Mathf.Min(reticleOuterAngle, kReticleMinOuterAngle); float inner_half_angle_radians = Mathf.Deg2Rad * reticleInnerAngle * 0.5f; float outer_half_angle_radians = Mathf.Deg2Rad * reticleOuterAngle * 0.5f; float inner_diameter = 2.0f * Mathf.Tan(inner_half_angle_radians); float outer_diameter = 2.0f * Mathf.Tan(outer_half_angle_radians); reticleInnerDiameter = Mathf.Lerp(reticleInnerDiameter, inner_diameter, Time.deltaTime * reticleGrowthSpeed); reticleOuterDiameter = Mathf.Lerp(reticleOuterDiameter, outer_diameter, Time.deltaTime * reticleGrowthSpeed); materialComp.SetFloat("_InnerDiameter", reticleInnerDiameter * reticleDistanceInMeters); materialComp.SetFloat("_OuterDiameter", reticleOuterDiameter * reticleDistanceInMeters); materialComp.SetFloat("_DistanceInMeters", reticleDistanceInMeters); } private void SetGazeTarget(Vector3 target, bool interactive) { Vector3 targetLocalPosition = transform.InverseTransformPoint(target); reticleDistanceInMeters = Mathf.Clamp(targetLocalPosition.z, kReticleDistanceMin, kReticleDistanceMax); if (interactive) { reticleInnerAngle = kReticleMinInnerAngle + kReticleGrowthAngle; reticleOuterAngle = kReticleMinOuterAngle + kReticleGrowthAngle; } else { reticleInnerAngle = kReticleMinInnerAngle; reticleOuterAngle = kReticleMinOuterAngle; } } private Material materialComp; // Current inner angle of the reticle (in degrees). private float reticleInnerAngle = 0.0f; // Current outer angle of the reticle (in degrees). private float reticleOuterAngle = 0.5f; // Current distance of the reticle (in meters). private float reticleDistanceInMeters = 10.0f; // Current inner and outer diameters of the reticle, // before distance multiplication. private float reticleInnerDiameter = 0.0f; private float reticleOuterDiameter = 0.0f; }
// 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 sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>FeedItem</c> resource.</summary> public sealed partial class FeedItemName : gax::IResourceName, sys::IEquatable<FeedItemName> { /// <summary>The possible contents of <see cref="FeedItemName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </summary> CustomerFeedFeedItem = 1, } private static gax::PathTemplate s_customerFeedFeedItem = new gax::PathTemplate("customers/{customer_id}/feedItems/{feed_id_feed_item_id}"); /// <summary>Creates a <see cref="FeedItemName"/> 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="FeedItemName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static FeedItemName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new FeedItemName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="FeedItemName"/> with the pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="FeedItemName"/> constructed from the provided ids.</returns> public static FeedItemName FromCustomerFeedFeedItem(string customerId, string feedId, string feedItemId) => new FeedItemName(ResourceNameType.CustomerFeedFeedItem, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedItemName"/> with pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedItemName"/> with pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </returns> public static string Format(string customerId, string feedId, string feedItemId) => FormatCustomerFeedFeedItem(customerId, feedId, feedItemId); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedItemName"/> with pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedItemName"/> with pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </returns> public static string FormatCustomerFeedFeedItem(string customerId, string feedId, string feedItemId) => s_customerFeedFeedItem.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)))}"); /// <summary>Parses the given resource name string into a new <see cref="FeedItemName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c></description></item> /// </list> /// </remarks> /// <param name="feedItemName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="FeedItemName"/> if successful.</returns> public static FeedItemName Parse(string feedItemName) => Parse(feedItemName, false); /// <summary> /// Parses the given resource name string into a new <see cref="FeedItemName"/> 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>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedItemName">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="FeedItemName"/> if successful.</returns> public static FeedItemName Parse(string feedItemName, bool allowUnparsed) => TryParse(feedItemName, allowUnparsed, out FeedItemName 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="FeedItemName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c></description></item> /// </list> /// </remarks> /// <param name="feedItemName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeedItemName"/>, 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 feedItemName, out FeedItemName result) => TryParse(feedItemName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeedItemName"/> 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>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedItemName">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="FeedItemName"/>, 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 feedItemName, bool allowUnparsed, out FeedItemName result) { gax::GaxPreconditions.CheckNotNull(feedItemName, nameof(feedItemName)); gax::TemplatedResourceName resourceName; if (s_customerFeedFeedItem.TryParseName(feedItemName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerFeedFeedItem(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(feedItemName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private FeedItemName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedId = null, string feedItemId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; FeedId = feedId; FeedItemId = feedItemId; } /// <summary> /// Constructs a new instance of a <see cref="FeedItemName"/> class from the component parts of pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> public FeedItemName(string customerId, string feedId, string feedItemId) : this(ResourceNameType.CustomerFeedFeedItem, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId))) { } /// <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>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedId { get; } /// <summary> /// The <c>FeedItem</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedItemId { 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.CustomerFeedFeedItem: return s_customerFeedFeedItem.Expand(CustomerId, $"{FeedId}~{FeedItemId}"); 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 FeedItemName); /// <inheritdoc/> public bool Equals(FeedItemName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(FeedItemName a, FeedItemName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(FeedItemName a, FeedItemName b) => !(a == b); } public partial class FeedItem { /// <summary> /// <see cref="FeedItemName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal FeedItemName ResourceNameAsFeedItemName { get => string.IsNullOrEmpty(ResourceName) ? null : FeedItemName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary> internal FeedName FeedAsFeedName { get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true); set => Feed = value?.ToString() ?? ""; } } }
namespace BizLogic.Test { using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Data; using System.Linq; using OpenRiaServices.DomainServices.EntityFramework; using OpenRiaServices.DomainServices.Hosting; using OpenRiaServices.DomainServices.Server; using NorthwindModel; // Implements application logic using the NorthwindEntities context. // TODO: Add your application logic to these methods or in additional methods. // TODO: Wire up authentication (Windows/ASP.NET Forms) and uncomment the following to disable anonymous access // Also consider adding roles to restrict access as appropriate. // [RequiresAuthentication] [EnableClientAccess()] public class EF_Northwind : LinqToEntitiesDomainService<NorthwindEntities> { // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'Categories' query. public IQueryable<Category> GetCategories() { return this.ObjectContext.Categories; } public void InsertCategory(Category category) { if ((category.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(category, EntityState.Added); } else { this.ObjectContext.Categories.AddObject(category); } } public void UpdateCategory(Category currentCategory) { this.ObjectContext.Categories.AttachAsModified(currentCategory, this.ChangeSet.GetOriginal(currentCategory)); } public void DeleteCategory(Category category) { if ((category.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(category, EntityState.Deleted); } else { this.ObjectContext.Categories.Attach(category); this.ObjectContext.Categories.DeleteObject(category); } } // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'Customers' query. public IQueryable<Customer> GetCustomers() { return this.ObjectContext.Customers; } public void InsertCustomer(Customer customer) { if ((customer.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(customer, EntityState.Added); } else { this.ObjectContext.Customers.AddObject(customer); } } public void UpdateCustomer(Customer currentCustomer) { this.ObjectContext.Customers.AttachAsModified(currentCustomer, this.ChangeSet.GetOriginal(currentCustomer)); } public void DeleteCustomer(Customer customer) { if ((customer.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(customer, EntityState.Deleted); } else { this.ObjectContext.Customers.Attach(customer); this.ObjectContext.Customers.DeleteObject(customer); } } // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'CustomerDemographics' query. public IQueryable<CustomerDemographic> GetCustomerDemographics() { return this.ObjectContext.CustomerDemographics; } public void InsertCustomerDemographic(CustomerDemographic customerDemographic) { if ((customerDemographic.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(customerDemographic, EntityState.Added); } else { this.ObjectContext.CustomerDemographics.AddObject(customerDemographic); } } public void UpdateCustomerDemographic(CustomerDemographic currentCustomerDemographic) { this.ObjectContext.CustomerDemographics.AttachAsModified(currentCustomerDemographic, this.ChangeSet.GetOriginal(currentCustomerDemographic)); } public void DeleteCustomerDemographic(CustomerDemographic customerDemographic) { if ((customerDemographic.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(customerDemographic, EntityState.Deleted); } else { this.ObjectContext.CustomerDemographics.Attach(customerDemographic); this.ObjectContext.CustomerDemographics.DeleteObject(customerDemographic); } } // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'Employees' query. public IQueryable<Employee> GetEmployees() { return this.ObjectContext.Employees; } public void InsertEmployee(Employee employee) { if ((employee.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(employee, EntityState.Added); } else { this.ObjectContext.Employees.AddObject(employee); } } public void UpdateEmployee(Employee currentEmployee) { this.ObjectContext.Employees.AttachAsModified(currentEmployee, this.ChangeSet.GetOriginal(currentEmployee)); } public void DeleteEmployee(Employee employee) { if ((employee.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(employee, EntityState.Deleted); } else { this.ObjectContext.Employees.Attach(employee); this.ObjectContext.Employees.DeleteObject(employee); } } // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'Orders' query. public IQueryable<Order> GetOrders() { return this.ObjectContext.Orders; } public void InsertOrder(Order order) { if ((order.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(order, EntityState.Added); } else { this.ObjectContext.Orders.AddObject(order); } } public void UpdateOrder(Order currentOrder) { this.ObjectContext.Orders.AttachAsModified(currentOrder, this.ChangeSet.GetOriginal(currentOrder)); } public void DeleteOrder(Order order) { if ((order.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(order, EntityState.Deleted); } else { this.ObjectContext.Orders.Attach(order); this.ObjectContext.Orders.DeleteObject(order); } } // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'Order_Details' query. public IQueryable<Order_Detail> GetOrder_Details() { return this.ObjectContext.Order_Details; } public void InsertOrder_Detail(Order_Detail order_Detail) { if ((order_Detail.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(order_Detail, EntityState.Added); } else { this.ObjectContext.Order_Details.AddObject(order_Detail); } } public void UpdateOrder_Detail(Order_Detail currentOrder_Detail) { this.ObjectContext.Order_Details.AttachAsModified(currentOrder_Detail, this.ChangeSet.GetOriginal(currentOrder_Detail)); } public void DeleteOrder_Detail(Order_Detail order_Detail) { if ((order_Detail.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(order_Detail, EntityState.Deleted); } else { this.ObjectContext.Order_Details.Attach(order_Detail); this.ObjectContext.Order_Details.DeleteObject(order_Detail); } } // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'Products' query. public IQueryable<Product> GetProducts() { return this.ObjectContext.Products; } public void InsertProduct(Product product) { if ((product.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(product, EntityState.Added); } else { this.ObjectContext.Products.AddObject(product); } } public void UpdateProduct(Product currentProduct) { this.ObjectContext.Products.AttachAsModified(currentProduct, this.ChangeSet.GetOriginal(currentProduct)); } public void DeleteProduct(Product product) { if ((product.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(product, EntityState.Deleted); } else { this.ObjectContext.Products.Attach(product); this.ObjectContext.Products.DeleteObject(product); } } // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'Regions' query. public IQueryable<Region> GetRegions() { return this.ObjectContext.Regions; } public void InsertRegion(Region region) { if ((region.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(region, EntityState.Added); } else { this.ObjectContext.Regions.AddObject(region); } } public void UpdateRegion(Region currentRegion) { this.ObjectContext.Regions.AttachAsModified(currentRegion, this.ChangeSet.GetOriginal(currentRegion)); } public void DeleteRegion(Region region) { if ((region.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(region, EntityState.Deleted); } else { this.ObjectContext.Regions.Attach(region); this.ObjectContext.Regions.DeleteObject(region); } } // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'Shippers' query. public IQueryable<Shipper> GetShippers() { return this.ObjectContext.Shippers; } public void InsertShipper(Shipper shipper) { if ((shipper.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(shipper, EntityState.Added); } else { this.ObjectContext.Shippers.AddObject(shipper); } } public void UpdateShipper(Shipper currentShipper) { this.ObjectContext.Shippers.AttachAsModified(currentShipper, this.ChangeSet.GetOriginal(currentShipper)); } public void DeleteShipper(Shipper shipper) { if ((shipper.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(shipper, EntityState.Deleted); } else { this.ObjectContext.Shippers.Attach(shipper); this.ObjectContext.Shippers.DeleteObject(shipper); } } // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'Suppliers' query. public IQueryable<Supplier> GetSuppliers() { return this.ObjectContext.Suppliers; } public void InsertSupplier(Supplier supplier) { if ((supplier.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(supplier, EntityState.Added); } else { this.ObjectContext.Suppliers.AddObject(supplier); } } public void UpdateSupplier(Supplier currentSupplier) { this.ObjectContext.Suppliers.AttachAsModified(currentSupplier, this.ChangeSet.GetOriginal(currentSupplier)); } public void DeleteSupplier(Supplier supplier) { if ((supplier.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(supplier, EntityState.Deleted); } else { this.ObjectContext.Suppliers.Attach(supplier); this.ObjectContext.Suppliers.DeleteObject(supplier); } } // TODO: // Consider constraining the results of your query method. If you need additional input you can // add parameters to this method or create additional query methods with different names. // To support paging you will need to add ordering to the 'Territories' query. public IQueryable<Territory> GetTerritories() { return this.ObjectContext.Territories; } public void InsertTerritory(Territory territory) { if ((territory.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(territory, EntityState.Added); } else { this.ObjectContext.Territories.AddObject(territory); } } public void UpdateTerritory(Territory currentTerritory) { this.ObjectContext.Territories.AttachAsModified(currentTerritory, this.ChangeSet.GetOriginal(currentTerritory)); } public void DeleteTerritory(Territory territory) { if ((territory.EntityState != EntityState.Detached)) { this.ObjectContext.ObjectStateManager.ChangeObjectState(territory, EntityState.Deleted); } else { this.ObjectContext.Territories.Attach(territory); this.ObjectContext.Territories.DeleteObject(territory); } } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace PnPExtensions { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AutoDiff; //using CarpeNoctem.Containers; //using System.Diagnostics.Contracts; namespace AutoDiff { /// <summary> /// A column vector made of terms. /// </summary> [Serializable] public class TVec { private readonly Term[] terms; /// <summary> /// Constructs a new instance of the <see cref="TVec"/> class given vector components. /// </summary> /// <param name="terms">The vector component terms</param> public TVec(IEnumerable<Term> terms) { /*Contract.Requires(terms != null); Contract.Requires(Contract.ForAll(terms, term => term != null)); Contract.Requires(terms.Any()); */ this.terms = terms.ToArray(); } /// <summary> /// Constructs a new instance of the <see cref="TVec"/> class given vector components. /// </summary> /// <param name="terms">The vector component terms</param> public TVec(params Term[] terms) : this(terms as IEnumerable<Term>) { /* Contract.Requires(terms != null); Contract.Requires(Contract.ForAll(terms, term => term != null)); Contract.Requires(terms.Length > 0); */ } /// <summary> /// Constructs a new instance of the <see cref="TVec"/> class using another vector's components. /// </summary> /// <param name="first">A vector containing the first vector components to use.</param> /// <param name="rest">More vector components to add in addition to the components in <paramref name="first"/></param> public TVec(TVec first, params Term[] rest) : this(first.terms.Concat(rest ?? System.Linq.Enumerable.Empty<Term>())) { /*Contract.Requires(first != null); Contract.Requires(Contract.ForAll(rest, term => term != null)); */ } private TVec(Term[] left, Term[] right, Func<Term, Term, Term> elemOp) { //Contract.Assume(left.Length == right.Length); terms = new Term[left.Length]; for (int i = 0; i < terms.Length; ++i) terms[i] = elemOp(left[i], right[i]); } private TVec(Term[] input, Func<Term, Term> elemOp) { terms = new Term[input.Length]; for (int i = 0; i < input.Length; ++i) terms[i] = elemOp(input[i]); } /// <summary> /// Gets a vector component given its zero-based index. /// </summary> /// <param name="index">The vector's component index.</param> /// <returns>The vector component.</returns> public Term this[int index] { get { /* Contract.Requires(index >= 0 && index < Dimension); Contract.Ensures(Contract.Result<Term>() != null); */ return terms[index]; } } /// <summary> /// Gets a term representing the squared norm of this vector. /// </summary> public Term NormSquared { get { //Contract.Ensures(Contract.Result<Term>() != null); var powers = terms.Select(x => TermBuilder.Power(x, 2)); return TermBuilder.Sum(powers); } } /// <summary> /// Gets a term representing the a new vector with length = 1 and the direction of this vector. /// </summary> public TVec Normalize { get { Term a = NormSquared; a = TermBuilder.Power(a, 0.5); var b = terms.Select(x => (x/a)); return new TVec (b); } } /// <summary> /// Gets the dimensions of this vector /// </summary> public int Dimension { get { //Contract.Ensures(Contract.Result<int>() > 0); return terms.Length; } } /// <summary> /// Gets the first vector component /// </summary> public Term X { get { //Contract.Ensures(Contract.Result<Term>() != null); return this[0]; } } /// <summary> /// Gets the second vector component. /// </summary> public Term Y { get { //Contract.Requires(Dimension >= 2); //Contract.Ensures(Contract.Result<Term>() != null); return this[1]; } } /// <summary> /// Gets the third vector component /// </summary> public Term Z { get { //Contract.Requires(Dimension >= 3); //Contract.Ensures(Contract.Result<Term>() != null); return this[2]; } } /// <summary> /// Gets an array of all vector components. /// </summary> /// <returns>An array of all vector components. Users are free to modify this array. It doesn't point to any /// internal structures.</returns> public Term[] GetTerms() { /*Contract.Ensures(Contract.Result<Term[]>() != null); Contract.Ensures(Contract.Result<Term[]>().Length > 0); Contract.Ensures(Contract.ForAll(Contract.Result<Term[]>(), term => term != null)); */ return (Term[])terms.Clone(); } /* public static implicit operator TVec(Point2D value) { return new TVec(value.X,value.Y); } */ /// <summary> /// Constructs a sum of two term vectors. /// </summary> /// <param name="left">The first vector in the sum</param> /// <param name="right">The second vector in the sum</param> /// <returns>A vector representing the sum of <paramref name="left"/> and <paramref name="right"/></returns> public static TVec operator+(TVec left, TVec right) { /*Contract.Requires(left != null); Contract.Requires(right != null); Contract.Requires(left.Dimension == right.Dimension); Contract.Ensures(Contract.Result<TVec>().Dimension == left.Dimension); */ return new TVec(left.terms, right.terms, (x, y) => x + y); } /// <summary> /// Constructs a difference of two term vectors, /// </summary> /// <param name="left">The first vector in the difference</param> /// <param name="right">The second vector in the difference.</param> /// <returns>A vector representing the difference of <paramref name="left"/> and <paramref name="right"/></returns> public static TVec operator-(TVec left, TVec right) { /*Contract.Requires(left != null); Contract.Requires(right != null); Contract.Requires(left.Dimension == right.Dimension); Contract.Ensures(Contract.Result<TVec>().Dimension == left.Dimension); */ return new TVec(left.terms, right.terms, (x, y) => x - y); } /// <summary> /// Inverts a vector /// </summary> /// <param name="vector">The vector to invert</param> /// <returns>A vector repsesenting the inverse of <paramref name="vector"/></returns> public static TVec operator-(TVec vector) { /*Contract.Requires(vector != null); Contract.Ensures(Contract.Result<TVec>().Dimension == vector.Dimension); */ return vector * -1; } /// <summary> /// Multiplies a vector by a scalar /// </summary> /// <param name="vector">The vector</param> /// <param name="scalar">The scalar</param> /// <returns>A product of the vector <paramref name="vector"/> and the scalar <paramref name="scalar"/>.</returns> public static TVec operator*(TVec vector, Term scalar) { /*Contract.Requires(vector != null); Contract.Requires(scalar != null); Contract.Ensures(Contract.Result<TVec>().Dimension == vector.Dimension); */ return new TVec(vector.terms, x => scalar * x); } /// <summary> /// Multiplies a vector by a scalar /// </summary> /// <param name="vector">The vector</param> /// <param name="scalar">The scalar</param> /// <returns>A product of the vector <paramref name="vector"/> and the scalar <paramref name="scalar"/>.</returns> public static TVec operator *(Term scalar, TVec vector) { /*Contract.Requires(vector != null); Contract.Requires(scalar != null); Contract.Ensures(Contract.Result<TVec>().Dimension == vector.Dimension); */ return vector * scalar; } /// <summary> /// Constructs a term representing the inner product of two vectors. /// </summary> /// <param name="left">The first vector of the inner product</param> /// <param name="right">The second vector of the inner product</param> /// <returns>A term representing the inner product of <paramref name="left"/> and <paramref name="right"/>.</returns> public static Term operator*(TVec left, TVec right) { /*Contract.Requires(left != null); Contract.Requires(right != null); Contract.Requires(left.Dimension == right.Dimension); Contract.Ensures(Contract.Result<Term>() != null); */ return InnerProduct(left, right); } /// <summary> /// Constructs a term representing the inner product of two vectors. /// </summary> /// <param name="left">The first vector of the inner product</param> /// <param name="right">The second vector of the inner product</param> /// <returns>A term representing the inner product of <paramref name="left"/> and <paramref name="right"/>.</returns> public static Term InnerProduct(TVec left, TVec right) { /*Contract.Requires(left != null); Contract.Requires(right != null); Contract.Requires(left.Dimension == right.Dimension); Contract.Ensures(Contract.Result<Term>() != null); */ var products = from i in System.Linq.Enumerable.Range(0, left.Dimension) select left.terms[i] * right.terms[i]; return TermBuilder.Sum(products); } /// <summary> /// Constructs a 3D cross-product vector given two 3D vectors. /// </summary> /// <param name="left">The left cross-product term</param> /// <param name="right">The right cross product term</param> /// <returns>A vector representing the cross product of <paramref name="left"/> and <paramref name="right"/></returns> public static TVec CrossProduct(TVec left, TVec right) { /* Contract.Requires(left != null); Contract.Requires(right != null); Contract.Requires(left.Dimension == 3); Contract.Requires(right.Dimension == 3); Contract.Ensures(Contract.Result<TVec>().Dimension == 3); */ return new TVec( left.Y * right.Z - left.Z * right.Y, left.Z * right.X - left.X * right.Z, left.X * right.Y - left.Y * right.X ); } public override string ToString () { Term[] terms = GetTerms(); string termString = string.Empty; if (terms != null && terms.Length > 0){ termString = terms[0].ToString(); for (int i = 1; i < terms.Length; i++) { termString += string.Format(", {0}", terms[i].ToString()); } } return string.Format ("TVec: Dimension={0}, [{1}]", Dimension, termString); } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; using System; namespace UIWidgets { [Serializable] public class ListViewItemResize : UnityEvent<int,Vector2> { } [Serializable] public class ListViewItemSelect : UnityEvent<ListViewItem> { } [Serializable] public class ListViewItemMove : UnityEvent<AxisEventData, ListViewItem> { } /// <summary> /// ListViewItem. /// Item for ListViewBase. /// </summary> [RequireComponent(typeof(Image))] public abstract class ListViewItem : UIBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler, ISubmitHandler, ICancelHandler, ISelectHandler, IDeselectHandler, IMoveHandler, IComparable<ListViewItem> { /// <summary> /// The index of item in ListView. /// </summary> [HideInInspector] public int Index = -1; /// <summary> /// What to do when the event system send a pointer click event. /// </summary> public UnityEvent onClick = new UnityEvent(); /// <summary> /// What to do when the event system send a submit event. /// </summary> public ListViewItemSelect onSubmit = new ListViewItemSelect(); /// <summary> /// What to do when the event system send a cancel event. /// </summary> public ListViewItemSelect onCancel = new ListViewItemSelect(); /// <summary> /// What to do when the event system send a select event. /// </summary> public ListViewItemSelect onSelect = new ListViewItemSelect(); /// <summary> /// What to do when the event system send a deselect event. /// </summary> public ListViewItemSelect onDeselect = new ListViewItemSelect(); /// <summary> /// What to do when the event system send a move event. /// </summary> public ListViewItemMove onMove = new ListViewItemMove(); /// <summary> /// What to do when the event system send a pointer click event. /// </summary> public PointerUnityEvent onPointerClick = new PointerUnityEvent(); /// <summary> /// What to do when the event system send a pointer enter Event. /// </summary> public PointerUnityEvent onPointerEnter = new PointerUnityEvent(); /// <summary> /// What to do when the event system send a pointer exit Event. /// </summary> public PointerUnityEvent onPointerExit = new PointerUnityEvent(); /// <summary> /// OnResize event. /// </summary> public ListViewItemResize onResize = new ListViewItemResize(); Image background; /// <summary> /// The background. /// </summary> public Image Background { get { if (background==null) { background = GetComponent<Image>(); } return background; } } RectTransform rectTransform; /// <summary> /// Gets the RectTransform. /// </summary> /// <value>The RectTransform.</value> protected RectTransform RectTransform { get { if (rectTransform==null) { rectTransform = transform as RectTransform; } return rectTransform; } } [SerializeField] protected bool LocalPositionZReset; /// <summary> /// Awake this instance. /// </summary> protected override void Awake() { if ((LocalPositionZReset) && (transform.localPosition.z!=0f)) { var pos = transform.localPosition; pos.z = 0f; transform.localPosition = pos; } } /// <summary> /// Raises the move event. /// </summary> /// <param name="eventData">Event data.</param> public virtual void OnMove(AxisEventData eventData) { onMove.Invoke(eventData, this); } /// <summary> /// Raises the submit event. /// </summary> /// <param name="eventData">Event data.</param> public virtual void OnSubmit(BaseEventData eventData) { onSubmit.Invoke(this); } /// <summary> /// Raises the cancel event. /// </summary> /// <param name="eventData">Event data.</param> public virtual void OnCancel(BaseEventData eventData) { onCancel.Invoke(this); } /// <summary> /// Raises the select event. /// </summary> /// <param name="eventData">Event data.</param> public virtual void OnSelect(BaseEventData eventData) { Select(); onSelect.Invoke(this); } /// <summary> /// Raises the deselect event. /// </summary> /// <param name="eventData">Event data.</param> public virtual void OnDeselect(BaseEventData eventData) { onDeselect.Invoke(this); } /// <summary> /// Raises the pointer click event. /// </summary> /// <param name="eventData">Current event data.</param> public virtual void OnPointerClick(PointerEventData eventData) { onPointerClick.Invoke(eventData); if (eventData.button!=PointerEventData.InputButton.Left) { return; } onClick.Invoke(); Select(); } /// <summary> /// Raises the pointer enter event. /// </summary> /// <param name="eventData">Event data.</param> public virtual void OnPointerEnter(PointerEventData eventData) { onPointerEnter.Invoke(eventData); } /// <summary> /// Raises the pointer exit event. /// </summary> /// <param name="eventData">Event data.</param> public virtual void OnPointerExit(PointerEventData eventData) { onPointerExit.Invoke(eventData); } /// <summary> /// Select this instance. /// </summary> public virtual void Select() { if (EventSystem.current.alreadySelecting) { return; } var ev = new ListViewItemEventData(EventSystem.current) { NewSelectedObject = gameObject }; EventSystem.current.SetSelectedGameObject(ev.NewSelectedObject, ev); } Rect oldRect; protected override void OnRectTransformDimensionsChange() { if (oldRect.Equals(RectTransform.rect)) { return ; } oldRect = RectTransform.rect; onResize.Invoke(Index, oldRect.size); } /// <summary> /// Compares the current object with another object of the same type by Index. /// </summary> /// <returns>Another object.</returns> /// <param name="compareItem">Compare item.</param> public int CompareTo(ListViewItem compareItem) { return (compareItem == null) ? 1 : Index.CompareTo(compareItem.Index); } /// <summary> /// Called when item moved to cache, you can use it free used resources. /// </summary> public virtual void MovedToCache() { } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Provisioning.PublishingFeaturesWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using Xunit; namespace Jint.Tests.Ecma { public class Test_7_8_5 : EcmaTest { [Fact] [Trait("Category", "7.8.5")] public void LiteralRegexpObjectsSyntaxerrorExceptionIsThrownIfTheRegularexpressionnonterminatorPositionOfARegularexpressionbackslashsequenceIsALineterminator() { RunTest(@"TestCases/ch07/7.8/7.8.5/7.8.5-1.js", false); } [Fact] [Trait("Category", "7.8.5")] public void EmptyLiteralRegexpShouldResultInASyntaxerror() { RunTest(@"TestCases/ch07/7.8/7.8.5/7.8.5-1gs.js", true); } [Fact] [Trait("Category", "7.8.5")] public void EmptyDynamicRegexpShouldNotResultInASyntaxerror() { RunTest(@"TestCases/ch07/7.8/7.8.5/7.8.5-2gs.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharNonterminatorButNotOrOrRegularexpressioncharsEmptyRegularexpressionflagsEmpty() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.1_T1.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharNonterminatorButNotOrOrRegularexpressioncharsEmptyRegularexpressionflagsEmpty2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.1_T2.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharOrOrOrEmptyIsIncorrect() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.2_T1.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharOrOrOrEmptyIsIncorrect2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.2_T2.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharOrOrOrEmptyIsIncorrect3() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.2_T3.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharOrOrOrEmptyIsIncorrect4() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.2_T4.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharLineterminatorIsIncorrect() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.3_T1.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharLineterminatorIsIncorrect2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.3_T2.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharLineterminatorIsIncorrect3() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.3_T3.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharLineterminatorIsIncorrect4() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.3_T4.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharLineterminatorIsIncorrect5() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.3_T5.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharLineterminatorIsIncorrect6() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.3_T6.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharBackslashsequenceNonterminatorRegularexpressioncharsEmptyRegularexpressionflagsEmpty() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.4_T1.js", false); } [Fact(Skip = @"The pattern a\P is evaluatead as a syntax error in .NET")] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharBackslashsequenceNonterminatorRegularexpressioncharsEmptyRegularexpressionflagsEmpty2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.4_T2.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharBackslashsequenceLineterminatorIsIncorrect() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.5_T1.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharBackslashsequenceLineterminatorIsIncorrect2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.5_T2.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharBackslashsequenceLineterminatorIsIncorrect3() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.5_T3.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharBackslashsequenceLineterminatorIsIncorrect4() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.5_T4.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharBackslashsequenceLineterminatorIsIncorrect5() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.5_T5.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionfirstcharBackslashsequenceLineterminatorIsIncorrect6() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A1.5_T6.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharNonterminatorButNotOrRegularexpressionflagsEmpty() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.1_T1.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharNonterminatorButNotOrRegularexpressionflagsEmpty2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.1_T2.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharOrIsIncorrect() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.2_T1.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharOrIsIncorrect2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.2_T2.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharLineterminatorIsIncorrect() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.3_T1.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharLineterminatorIsIncorrect2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.3_T2.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharLineterminatorIsIncorrect3() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.3_T3.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharLineterminatorIsIncorrect4() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.3_T4.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharLineterminatorIsIncorrect5() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.3_T5.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharLineterminatorIsIncorrect6() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.3_T6.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharBackslashsequenceNonterminatorRegularexpressionflagsEmpty() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.4_T1.js", false); } [Fact(Skip = @"The pattern a\P is evaluatead as a syntax error in .NET")] [Trait("Category", "7.8.5")] public void RegularexpressioncharBackslashsequenceNonterminatorRegularexpressionflagsEmpty2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.4_T2.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharBackslashsequenceLineterminatorIsIncorrect() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.5_T1.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharBackslashsequenceLineterminatorIsIncorrect2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.5_T2.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharBackslashsequenceLineterminatorIsIncorrect3() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.5_T3.js", true); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharBackslashsequenceLineterminatorIsIncorrect4() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.5_T4.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharBackslashsequenceLineterminatorIsIncorrect5() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.5_T5.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressioncharBackslashsequenceLineterminatorIsIncorrect6() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A2.5_T6.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionflagsIdentifierpart() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A3.1_T1.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionflagsIdentifierpart2() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A3.1_T2.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionflagsIdentifierpart3() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A3.1_T3.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionflagsIdentifierpart4() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A3.1_T4.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionflagsIdentifierpart5() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A3.1_T5.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionflagsIdentifierpart6() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A3.1_T6.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionflagsIdentifierpart7() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A3.1_T7.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionflagsIdentifierpart8() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A3.1_T8.js", false); } [Fact] [Trait("Category", "7.8.5")] public void RegularexpressionflagsIdentifierpart9() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A3.1_T9.js", false); } [Fact] [Trait("Category", "7.8.5")] public void ARegularExpressionLiteralIsAnInputElementThatIsConvertedToARegexpObjectWhenItIsScanned() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A4.1.js", false); } [Fact] [Trait("Category", "7.8.5")] public void TwoRegularExpressionLiteralsInAProgramEvaluateToRegularExpressionObjectsThatNeverCompareAsToEachOtherEvenIfTheTwoLiteralsContentsAreIdentical() { RunTest(@"TestCases/ch07/7.8/7.8.5/S7.8.5_A4.2.js", false); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using IxMilia.Dxf.Blocks; using IxMilia.Dxf.Entities; using IxMilia.Dxf.Sections; namespace IxMilia.Dxf { internal class DxbReader { public const string BinarySentinel = "AutoCAD DXB 1.0"; private bool _isIntegerMode = true; private string _layerName = "0"; private double _scaleFactor = 1.0; private DxfColor _color = DxfColor.ByLayer; private DxfPoint _lastLinePoint = DxfPoint.Origin; private DxfPoint _lastTraceP3 = DxfPoint.Origin; private DxfPoint _lastTraceP4 = DxfPoint.Origin; public DxfFile ReadFile(BinaryReader reader) { // swallow next two characters var sub = reader.ReadChar(); Debug.Assert(sub == 0x1A); var nul = reader.ReadChar(); Debug.Assert(nul == 0x00); DxfPoint? blockBase = null; var entities = new List<DxfEntity>(); var stillReading = true; Action<Func<BinaryReader, DxfEntity>> addEntity = (entityReader) => { var entity = entityReader(reader); AssignCommonValues(entity); entities.Add(entity); }; Func<DxfVertex> getLastVertex = () => entities.LastOrDefault() as DxfVertex; while (stillReading) { var itemType = (DxbItemType)reader.ReadByte(); switch (itemType) { case DxbItemType.Line: addEntity(ReadLine); break; case DxbItemType.Point: addEntity(ReadPoint); break; case DxbItemType.Circle: addEntity(ReadCircle); break; case DxbItemType.Arc: addEntity(ReadArc); break; case DxbItemType.Trace: addEntity(ReadTrace); break; case DxbItemType.Solid: addEntity(ReadSolid); break; case DxbItemType.Seqend: addEntity(ReadSeqend); break; case DxbItemType.Polyline: addEntity(ReadPolyline); break; case DxbItemType.Vertex: addEntity(ReadVertex); break; case DxbItemType.Face: addEntity(ReadFace); break; case DxbItemType.ScaleFactor: _scaleFactor = ReadF(reader); break; case DxbItemType.NewLayer: var sb = new StringBuilder(); for (int b = reader.ReadByte(); b != 0; b = reader.ReadByte()) sb.Append((char)b); _layerName = sb.ToString(); break; case DxbItemType.LineExtension: addEntity(ReadLineExtension); break; case DxbItemType.TraceExtension: addEntity(ReadTraceExtension); break; case DxbItemType.BlockBase: var x = ReadN(reader); var y = ReadN(reader); if (blockBase == null && entities.Count == 0) { // only if this is the first item encountered blockBase = new DxfPoint(x, y, 0.0); } break; case DxbItemType.Bulge: { var bulge = ReadU(reader); var lastVertex = getLastVertex(); if (lastVertex != null) { lastVertex.Bulge = bulge; } } break; case DxbItemType.Width: { var startWidth = ReadN(reader); var endWidth = ReadN(reader); var lastVertex = getLastVertex(); if (lastVertex != null) { lastVertex.StartingWidth = startWidth; lastVertex.EndingWidth = endWidth; } } break; case DxbItemType.NumberMode: _isIntegerMode = ReadW(reader) == 0; break; case DxbItemType.NewColor: _color = DxfColor.FromRawValue((short)ReadW(reader)); break; case DxbItemType.LineExtension3D: addEntity(ReadLineExtension3D); break; case 0: stillReading = false; break; } } var file = new DxfFile(); foreach (var section in file.Sections) { section.Clear(); } // collect the entities (e.g., polylines, etc.) entities = DxfEntitiesSection.GatherEntities(entities); if (blockBase != null) { // entities are all contained in a block var block = new DxfBlock(); block.BasePoint = blockBase.GetValueOrDefault(); foreach (var entity in entities) { block.Entities.Add(entity); } file.Blocks.Add(block); } else { // just a normal collection of entities foreach (var entity in entities) { file.Entities.Add(entity); } } return file; } private static IEnumerable<DxfEntity> CollectEntities(IEnumerable<DxfEntity> entities) { return entities; } private double ReadA(BinaryReader reader) { if (_isIntegerMode) { return reader.ReadInt32() * _scaleFactor / 1000000.0; } else { return reader.ReadSingle(); } } private double ReadF(BinaryReader reader) { return reader.ReadDouble(); } private int ReadL(BinaryReader reader) { return (int)(reader.ReadInt32() * _scaleFactor); } private double ReadN(BinaryReader reader) { if (_isIntegerMode) { return reader.ReadInt16() * _scaleFactor; } else { return reader.ReadSingle(); } } private double ReadU(BinaryReader reader) { if (_isIntegerMode) { return reader.ReadInt32() * 65536 * _scaleFactor; } else { return reader.ReadSingle(); } } private int ReadW(BinaryReader reader) { return (int)(reader.ReadInt16() * _scaleFactor); } private void AssignCommonValues(DxfEntity entity) { entity.Color = _color; entity.Layer = _layerName; } private DxfLine ReadLine(BinaryReader reader) { var fromX = ReadN(reader); var fromY = ReadN(reader); var fromZ = ReadN(reader); var toX = ReadN(reader); var toY = ReadN(reader); var toZ = ReadN(reader); var from = new DxfPoint(fromX, fromY, fromZ); var to = new DxfPoint(toX, toY, toZ); _lastLinePoint = to; return new DxfLine(from, to); } private DxfModelPoint ReadPoint(BinaryReader reader) { return new DxfModelPoint(new DxfPoint(ReadN(reader), ReadN(reader), 0.0)); } private DxfCircle ReadCircle(BinaryReader reader) { var centerX = ReadN(reader); var centerY = ReadN(reader); var radius = ReadN(reader); return new DxfCircle(new DxfPoint(centerX, centerY, 0.0), radius); } private DxfArc ReadArc(BinaryReader reader) { var centerX = ReadN(reader); var centerY = ReadN(reader); var radius = ReadN(reader); var start = ReadA(reader); var end = ReadA(reader); return new DxfArc(new DxfPoint(centerX, centerY, 0.0), radius, start, end); } private DxfTrace ReadTrace(BinaryReader reader) { var x1 = ReadN(reader); var y1 = ReadN(reader); var x2 = ReadN(reader); var y2 = ReadN(reader); var x3 = ReadN(reader); var y3 = ReadN(reader); var x4 = ReadN(reader); var y4 = ReadN(reader); var trace = new DxfTrace() { FirstCorner = new DxfPoint(x1, y1, 0.0), SecondCorner = new DxfPoint(x2, y2, 0.0), ThirdCorner = new DxfPoint(x3, y3, 0.0), FourthCorner = new DxfPoint(x4, y4, 0.0) }; _lastTraceP3 = trace.ThirdCorner; _lastTraceP4 = trace.FourthCorner; return trace; } private DxfSolid ReadSolid(BinaryReader reader) { var x1 = ReadN(reader); var y1 = ReadN(reader); var x2 = ReadN(reader); var y2 = ReadN(reader); var x3 = ReadN(reader); var y3 = ReadN(reader); var x4 = ReadN(reader); var y4 = ReadN(reader); return new DxfSolid() { FirstCorner = new DxfPoint(x1, y1, 0.0), SecondCorner = new DxfPoint(x2, y2, 0.0), ThirdCorner = new DxfPoint(x3, y3, 0.0), FourthCorner = new DxfPoint(x4, y4, 0.0) }; } private DxfSeqend ReadSeqend(BinaryReader reader) { return new DxfSeqend(); } private DxfPolyline ReadPolyline(BinaryReader reader) { return new DxfPolyline() { IsClosed = ReadW(reader) != 0 }; } private DxfVertex ReadVertex(BinaryReader reader) { var x = ReadN(reader); var y = ReadN(reader); return new DxfVertex(new DxfPoint(x, y, 0.0)); } private Dxf3DFace ReadFace(BinaryReader reader) { var x1 = ReadN(reader); var y1 = ReadN(reader); var z1 = ReadN(reader); var x2 = ReadN(reader); var y2 = ReadN(reader); var z2 = ReadN(reader); var x3 = ReadN(reader); var y3 = ReadN(reader); var z3 = ReadN(reader); var x4 = ReadN(reader); var y4 = ReadN(reader); var z4 = ReadN(reader); return new Dxf3DFace() { FirstCorner = new DxfPoint(x1, y1, z1), SecondCorner = new DxfPoint(x2, y2, z2), ThirdCorner = new DxfPoint(x3, y3, z3), FourthCorner = new DxfPoint(x4, y4, z4) }; } private DxfLine ReadLineExtension(BinaryReader reader) { var x = ReadN(reader); var y = ReadN(reader); var to = new DxfPoint(x, y, 0.0); var line = new DxfLine(_lastLinePoint, to); _lastLinePoint = to; return line; } private DxfTrace ReadTraceExtension(BinaryReader reader) { var x3 = ReadN(reader); var y3 = ReadN(reader); var x4 = ReadN(reader); var y4 = ReadN(reader); var trace = new DxfTrace() { FirstCorner = _lastTraceP3, SecondCorner = _lastTraceP4, ThirdCorner = new DxfPoint(x3, y3, 0.0), FourthCorner = new DxfPoint(x4, y4, 0.0) }; _lastTraceP3 = trace.ThirdCorner; _lastTraceP4 = trace.FourthCorner; return trace; } private DxfLine ReadLineExtension3D(BinaryReader reader) { var x = ReadN(reader); var y = ReadN(reader); var z = ReadN(reader); var line = new DxfLine(_lastLinePoint, new DxfPoint(x, y, z)); _lastLinePoint = line.P2; return line; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using OpenMetaverse; using log4net; namespace OpenSim.Framework { public abstract class TerrainData { // Terrain always is a square public int SizeX { get; protected set; } public int SizeY { get; protected set; } public int SizeZ { get; protected set; } // A height used when the user doesn't specify anything public const float DefaultTerrainHeight = 21f; public abstract float this[int x, int y] { get; set; } // Someday terrain will have caves // at most holes :p public abstract float this[int x, int y, int z] { get; set; } public abstract bool IsTaintedAt(int xx, int yy); public abstract bool IsTaintedAt(int xx, int yy, bool clearOnTest); public abstract void TaintAllTerrain(); public abstract void ClearTaint(); public abstract void ClearLand(); public abstract void ClearLand(float height); // Return a representation of this terrain for storing as a blob in the database. // Returns 'true' to say blob was stored in the 'out' locations. public abstract bool GetDatabaseBlob(out int DBFormatRevisionCode, out Array blob); // Given a revision code and a blob from the database, create and return the right type of TerrainData. // The sizes passed are the expected size of the region. The database info will be used to // initialize the heightmap of that sized region with as much data is in the blob. // Return created TerrainData or 'null' if unsuccessful. public static TerrainData CreateFromDatabaseBlobFactory(int pSizeX, int pSizeY, int pSizeZ, int pFormatCode, byte[] pBlob) { // For the moment, there is only one implementation class return new HeightmapTerrainData(pSizeX, pSizeY, pSizeZ, pFormatCode, pBlob); } // return a special compressed representation of the heightmap in ushort public abstract float[] GetCompressedMap(); public abstract float CompressionFactor { get; } public abstract float[] GetFloatsSerialized(); public abstract double[,] GetDoubles(); public abstract TerrainData Clone(); } // The terrain is stored in the database as a blob with a 'revision' field. // Some implementations of terrain storage would fill the revision field with // the time the terrain was stored. When real revisions were added and this // feature removed, that left some old entries with the time in the revision // field. // Thus, if revision is greater than 'RevisionHigh' then terrain db entry is // left over and it is presumed to be 'Legacy256'. // Numbers are arbitrary and are chosen to to reduce possible mis-interpretation. // If a revision does not match any of these, it is assumed to be Legacy256. public enum DBTerrainRevision { // Terrain is 'double[256,256]' Legacy256 = 11, // Terrain is 'int32, int32, float[,]' where the ints are X and Y dimensions // The dimensions are presumed to be multiples of 16 and, more likely, multiples of 256. Variable2D = 22, Variable2DGzip = 23, // Terrain is 'int32, int32, int32, int16[]' where the ints are X and Y dimensions // and third int is the 'compression factor'. The heights are compressed as // "ushort compressedHeight = (ushort)(height * compressionFactor);" // The dimensions are presumed to be multiples of 16 and, more likely, multiples of 256. Compressed2D = 27, // A revision that is not listed above or any revision greater than this value is 'Legacy256'. RevisionHigh = 1234 } // Version of terrain that is a heightmap. // This should really be 'LLOptimizedHeightmapTerrainData' as it includes knowledge // of 'patches' which are 16x16 terrain areas which can be sent separately to the viewer. // The heighmap is kept as an array of ushorts. The ushort values are converted to // and from floats by TerrainCompressionFactor. public class HeightmapTerrainData : TerrainData { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[HEIGHTMAP TERRAIN DATA]"; // TerrainData.this[x, y] public override float this[int x, int y] { get { return m_heightmap[x, y]; } set { if (m_heightmap[x, y] != value) { m_heightmap[x, y] = value; m_taint[x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize] = true; } } } // TerrainData.this[x, y, z] public override float this[int x, int y, int z] { get { return this[x, y]; } set { this[x, y] = value; } } // TerrainData.ClearTaint public override void ClearTaint() { SetAllTaint(false); } // TerrainData.TaintAllTerrain public override void TaintAllTerrain() { SetAllTaint(true); } private void SetAllTaint(bool setting) { for (int ii = 0; ii < m_taint.GetLength(0); ii++) for (int jj = 0; jj < m_taint.GetLength(1); jj++) m_taint[ii, jj] = setting; } // TerrainData.ClearLand public override void ClearLand() { ClearLand(DefaultTerrainHeight); } // TerrainData.ClearLand(float) public override void ClearLand(float pHeight) { for (int xx = 0; xx < SizeX; xx++) for (int yy = 0; yy < SizeY; yy++) m_heightmap[xx, yy] = pHeight; } // Return 'true' of the patch that contains these region coordinates has been modified. // Note that checking the taint clears it. // There is existing code that relies on this feature. public override bool IsTaintedAt(int xx, int yy, bool clearOnTest) { int tx = xx / Constants.TerrainPatchSize; int ty = yy / Constants.TerrainPatchSize; bool ret = m_taint[tx, ty]; if (ret && clearOnTest) m_taint[tx, ty] = false; return ret; } // Old form that clears the taint flag when we check it. // ubit: this dangerus naming should be only check without clear // keeping for old modules outthere public override bool IsTaintedAt(int xx, int yy) { return IsTaintedAt(xx, yy, true /* clearOnTest */); } // TerrainData.GetDatabaseBlob // The user wants something to store in the database. public override bool GetDatabaseBlob(out int DBRevisionCode, out Array blob) { bool ret = false; if (SizeX == Constants.RegionSize && SizeY == Constants.RegionSize) { DBRevisionCode = (int)DBTerrainRevision.Legacy256; blob = ToLegacyTerrainSerialization(); ret = true; } else { DBRevisionCode = (int)DBTerrainRevision.Variable2DGzip; // DBRevisionCode = (int)DBTerrainRevision.Variable2D; blob = ToCompressedTerrainSerializationV2DGzip(); // blob = ToCompressedTerrainSerializationV2D(); ret = true; } return ret; } // TerrainData.CompressionFactor private float m_compressionFactor = 100.0f; public override float CompressionFactor { get { return m_compressionFactor; } } // TerrainData.GetCompressedMap public override float[] GetCompressedMap() { float[] newMap = new float[SizeX * SizeY]; int ind = 0; for (int xx = 0; xx < SizeX; xx++) for (int yy = 0; yy < SizeY; yy++) newMap[ind++] = m_heightmap[xx, yy]; return newMap; } // TerrainData.Clone public override TerrainData Clone() { HeightmapTerrainData ret = new HeightmapTerrainData(SizeX, SizeY, SizeZ); ret.m_heightmap = (float[,])this.m_heightmap.Clone(); return ret; } // TerrainData.GetFloatsSerialized // This one dimensional version is ordered so height = map[y*sizeX+x]; // DEPRECATED: don't use this function as it does not retain the dimensions of the terrain // and the caller will probably do the wrong thing if the terrain is not the legacy 256x256. public override float[] GetFloatsSerialized() { int points = SizeX * SizeY; float[] heights = new float[points]; int idx = 0; for (int jj = 0; jj < SizeY; jj++) for (int ii = 0; ii < SizeX; ii++) { heights[idx++] = m_heightmap[ii, jj]; } return heights; } // TerrainData.GetDoubles public override double[,] GetDoubles() { double[,] ret = new double[SizeX, SizeY]; for (int xx = 0; xx < SizeX; xx++) for (int yy = 0; yy < SizeY; yy++) ret[xx, yy] = (double)m_heightmap[xx, yy]; return ret; } // ============================================================= private float[,] m_heightmap; // Remember subregions of the heightmap that has changed. private bool[,] m_taint; // that is coded as the float height times the compression factor (usually '100' // to make for two decimal points). public short ToCompressedHeightshort(float pHeight) { // clamp into valid range pHeight *= CompressionFactor; if (pHeight < short.MinValue) return short.MinValue; else if (pHeight > short.MaxValue) return short.MaxValue; return (short)pHeight; } public ushort ToCompressedHeightushort(float pHeight) { // clamp into valid range pHeight *= CompressionFactor; if (pHeight < ushort.MinValue) return ushort.MinValue; else if (pHeight > ushort.MaxValue) return ushort.MaxValue; return (ushort)pHeight; } public float FromCompressedHeight(short pHeight) { return ((float)pHeight) / CompressionFactor; } public float FromCompressedHeight(ushort pHeight) { return ((float)pHeight) / CompressionFactor; } // To keep with the legacy theme, create an instance of this class based on the // way terrain used to be passed around. public HeightmapTerrainData(double[,] pTerrain) { SizeX = pTerrain.GetLength(0); SizeY = pTerrain.GetLength(1); SizeZ = (int)Constants.RegionHeight; m_compressionFactor = 100.0f; m_heightmap = new float[SizeX, SizeY]; for (int ii = 0; ii < SizeX; ii++) { for (int jj = 0; jj < SizeY; jj++) { m_heightmap[ii, jj] = (float)pTerrain[ii, jj]; } } // m_log.DebugFormat("{0} new by doubles. sizeX={1}, sizeY={2}, sizeZ={3}", LogHeader, SizeX, SizeY, SizeZ); m_taint = new bool[SizeX / Constants.TerrainPatchSize, SizeY / Constants.TerrainPatchSize]; ClearTaint(); } // Create underlying structures but don't initialize the heightmap assuming the caller will immediately do that public HeightmapTerrainData(int pX, int pY, int pZ) { SizeX = pX; SizeY = pY; SizeZ = pZ; m_compressionFactor = 100.0f; m_heightmap = new float[SizeX, SizeY]; m_taint = new bool[SizeX / Constants.TerrainPatchSize, SizeY / Constants.TerrainPatchSize]; // m_log.DebugFormat("{0} new by dimensions. sizeX={1}, sizeY={2}, sizeZ={3}", LogHeader, SizeX, SizeY, SizeZ); ClearTaint(); ClearLand(0f); } public HeightmapTerrainData(float[] cmap, float pCompressionFactor, int pX, int pY, int pZ) : this(pX, pY, pZ) { m_compressionFactor = pCompressionFactor; int ind = 0; for (int xx = 0; xx < SizeX; xx++) for (int yy = 0; yy < SizeY; yy++) m_heightmap[xx, yy] = cmap[ind++]; // m_log.DebugFormat("{0} new by compressed map. sizeX={1}, sizeY={2}, sizeZ={3}", LogHeader, SizeX, SizeY, SizeZ); } // Create a heighmap from a database blob public HeightmapTerrainData(int pSizeX, int pSizeY, int pSizeZ, int pFormatCode, byte[] pBlob) : this(pSizeX, pSizeY, pSizeZ) { switch ((DBTerrainRevision)pFormatCode) { case DBTerrainRevision.Variable2DGzip: FromCompressedTerrainSerializationV2DGZip(pBlob); m_log.DebugFormat("{0} HeightmapTerrainData create from Variable2DGzip serialization. Size=<{1},{2}>", LogHeader, SizeX, SizeY); break; case DBTerrainRevision.Variable2D: FromCompressedTerrainSerializationV2D(pBlob); m_log.DebugFormat("{0} HeightmapTerrainData create from Variable2D serialization. Size=<{1},{2}>", LogHeader, SizeX, SizeY); break; case DBTerrainRevision.Compressed2D: FromCompressedTerrainSerialization2D(pBlob); m_log.DebugFormat("{0} HeightmapTerrainData create from Compressed2D serialization. Size=<{1},{2}>", LogHeader, SizeX, SizeY); break; default: FromLegacyTerrainSerialization(pBlob); m_log.DebugFormat("{0} HeightmapTerrainData create from legacy serialization. Size=<{1},{2}>", LogHeader, SizeX, SizeY); break; } } // Just create an array of doubles. Presumes the caller implicitly knows the size. public Array ToLegacyTerrainSerialization() { Array ret = null; using (MemoryStream str = new MemoryStream((int)Constants.RegionSize * (int)Constants.RegionSize * sizeof(double))) { using (BinaryWriter bw = new BinaryWriter(str)) { for (int xx = 0; xx < Constants.RegionSize; xx++) { for (int yy = 0; yy < Constants.RegionSize; yy++) { double height = this[xx, yy]; if (height == 0.0) height = double.Epsilon; bw.Write(height); } } } ret = str.ToArray(); } return ret; } // Presumes the caller implicitly knows the size. public void FromLegacyTerrainSerialization(byte[] pBlob) { // In case database info doesn't match real terrain size, initialize the whole terrain. ClearLand(); try { using (MemoryStream mstr = new MemoryStream(pBlob)) { using (BinaryReader br = new BinaryReader(mstr)) { for (int xx = 0; xx < (int)Constants.RegionSize; xx++) { for (int yy = 0; yy < (int)Constants.RegionSize; yy++) { float val = (float)br.ReadDouble(); if (xx < SizeX && yy < SizeY) m_heightmap[xx, yy] = val; } } } } } catch { ClearLand(); } ClearTaint(); } // stores as variable2D // int32 sizeX // int32 sizeY // float[,] array public Array ToCompressedTerrainSerializationV2D() { Array ret = null; try { using (MemoryStream str = new MemoryStream((2 * sizeof(Int32)) + (SizeX * SizeY * sizeof(float)))) { using (BinaryWriter bw = new BinaryWriter(str)) { bw.Write((Int32)SizeX); bw.Write((Int32)SizeY); for (int yy = 0; yy < SizeY; yy++) for (int xx = 0; xx < SizeX; xx++) { // reduce to 1cm resolution float val = (float)Math.Round(m_heightmap[xx, yy],2,MidpointRounding.ToEven); bw.Write(val); } } ret = str.ToArray(); } } catch { } m_log.DebugFormat("{0} V2D {1} bytes", LogHeader, ret.Length); return ret; } // as above with Gzip compression public Array ToCompressedTerrainSerializationV2DGzip() { Array ret = null; try { using (MemoryStream inp = new MemoryStream((2 * sizeof(Int32)) + (SizeX * SizeY * sizeof(float)))) { using (BinaryWriter bw = new BinaryWriter(inp)) { bw.Write((Int32)SizeX); bw.Write((Int32)SizeY); for (int yy = 0; yy < SizeY; yy++) for (int xx = 0; xx < SizeX; xx++) { bw.Write((float)m_heightmap[xx, yy]); } bw.Flush(); inp.Seek(0, SeekOrigin.Begin); using (MemoryStream outputStream = new MemoryStream()) { using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress)) { inp.CopyStream(compressionStream, int.MaxValue); compressionStream.Close(); ret = outputStream.ToArray(); } } } } } catch { } m_log.DebugFormat("{0} V2DGzip {1} bytes", LogHeader, ret.Length); return ret; } // Initialize heightmap from blob consisting of: // int32, int32, int32, int32, int16[] // where the first int32 is format code, next two int32s are the X and y of heightmap data and // the forth int is the compression factor for the following int16s // This is just sets heightmap info. The actual size of the region was set on this instance's // creation and any heights not initialized by theis blob are set to the default height. public void FromCompressedTerrainSerialization2D(byte[] pBlob) { Int32 hmFormatCode, hmSizeX, hmSizeY, hmCompressionFactor; using (MemoryStream mstr = new MemoryStream(pBlob)) { using (BinaryReader br = new BinaryReader(mstr)) { hmFormatCode = br.ReadInt32(); hmSizeX = br.ReadInt32(); hmSizeY = br.ReadInt32(); hmCompressionFactor = br.ReadInt32(); m_compressionFactor = hmCompressionFactor; // In case database info doesn't match real terrain size, initialize the whole terrain. ClearLand(); for (int yy = 0; yy < hmSizeY; yy++) { for (int xx = 0; xx < hmSizeX; xx++) { float val = FromCompressedHeight(br.ReadInt16()); if (xx < SizeX && yy < SizeY) m_heightmap[xx, yy] = val; } } } ClearTaint(); m_log.DebugFormat("{0} Read (compressed2D) heightmap. Heightmap size=<{1},{2}>. Region size=<{3},{4}>. CompFact={5}", LogHeader, hmSizeX, hmSizeY, SizeX, SizeY, hmCompressionFactor); } } // Initialize heightmap from blob consisting of: // int32, int32, int32, float[] // where the first int32 is format code, next two int32s are the X and y of heightmap data // This is just sets heightmap info. The actual size of the region was set on this instance's // creation and any heights not initialized by theis blob are set to the default height. public void FromCompressedTerrainSerializationV2D(byte[] pBlob) { Int32 hmSizeX, hmSizeY; try { using (MemoryStream mstr = new MemoryStream(pBlob)) { using (BinaryReader br = new BinaryReader(mstr)) { hmSizeX = br.ReadInt32(); hmSizeY = br.ReadInt32(); // In case database info doesn't match real terrain size, initialize the whole terrain. ClearLand(); for (int yy = 0; yy < hmSizeY; yy++) { for (int xx = 0; xx < hmSizeX; xx++) { float val = br.ReadSingle(); if (xx < SizeX && yy < SizeY) m_heightmap[xx, yy] = val; } } } } } catch (Exception e) { ClearTaint(); m_log.ErrorFormat("{0} 2D error: {1} - terrain may be damaged", LogHeader, e.Message); return; } ClearTaint(); m_log.DebugFormat("{0} V2D Heightmap size=<{1},{2}>. Region size=<{3},{4}>", LogHeader, hmSizeX, hmSizeY, SizeX, SizeY); } // as above but Gzip compressed public void FromCompressedTerrainSerializationV2DGZip(byte[] pBlob) { m_log.InfoFormat("{0} VD2Gzip {1} bytes input", LogHeader, pBlob.Length); Int32 hmSizeX, hmSizeY; try { using (MemoryStream outputStream = new MemoryStream()) { using (MemoryStream inputStream = new MemoryStream(pBlob)) { using (GZipStream decompressionStream = new GZipStream(inputStream, CompressionMode.Decompress)) { decompressionStream.Flush(); decompressionStream.CopyTo(outputStream); } } outputStream.Seek(0, SeekOrigin.Begin); using (BinaryReader br = new BinaryReader(outputStream)) { hmSizeX = br.ReadInt32(); hmSizeY = br.ReadInt32(); // In case database info doesn't match real terrain size, initialize the whole terrain. ClearLand(); for (int yy = 0; yy < hmSizeY; yy++) { for (int xx = 0; xx < hmSizeX; xx++) { float val = br.ReadSingle(); if (xx < SizeX && yy < SizeY) m_heightmap[xx, yy] = val; } } } } } catch( Exception e) { ClearTaint(); m_log.ErrorFormat("{0} V2DGzip error: {1} - terrain may be damaged", LogHeader, e.Message); return; } ClearTaint(); m_log.DebugFormat("{0} V2DGzip. Heightmap size=<{1},{2}>. Region size=<{3},{4}>", LogHeader, hmSizeX, hmSizeY, SizeX, SizeY); } } }
using Discord.Logging; using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; namespace Discord.Audio.Streams { ///<summary> Wraps another stream with a timed buffer and packet loss detection. </summary> public class JitterBuffer : AudioOutStream { private struct Frame { public Frame(byte[] buffer, int bytes, ushort sequence, uint timestamp) { Buffer = buffer; Bytes = bytes; Sequence = sequence; Timestamp = timestamp; } public readonly byte[] Buffer; public readonly int Bytes; public readonly ushort Sequence; public readonly uint Timestamp; } private static readonly byte[] _silenceFrame = new byte[0]; private readonly AudioStream _next; private readonly CancellationTokenSource _cancelTokenSource; private readonly CancellationToken _cancelToken; private readonly Task _task; private readonly ConcurrentQueue<Frame> _queuedFrames; private readonly ConcurrentQueue<byte[]> _bufferPool; private readonly SemaphoreSlim _queueLock; private readonly Logger _logger; private readonly int _ticksPerFrame, _queueLength; private bool _isPreloaded, _hasHeader; private ushort _seq, _nextSeq; private uint _timestamp, _nextTimestamp; private bool _isFirst; public JitterBuffer(AudioStream next, int bufferMillis = 60, int maxFrameSize = 1500) : this(next, null, bufferMillis, maxFrameSize) { } internal JitterBuffer(AudioStream next, Logger logger, int bufferMillis = 60, int maxFrameSize = 1500) { //maxFrameSize = 1275 was too limiting at 128kbps,2ch,60ms _next = next; _ticksPerFrame = OpusEncoder.FrameMillis; _logger = logger; _queueLength = (bufferMillis + (_ticksPerFrame - 1)) / _ticksPerFrame; //Round up _cancelTokenSource = new CancellationTokenSource(); _cancelToken = _cancelTokenSource.Token; _queuedFrames = new ConcurrentQueue<Frame>(); _bufferPool = new ConcurrentQueue<byte[]>(); for (int i = 0; i < _queueLength; i++) _bufferPool.Enqueue(new byte[maxFrameSize]); _queueLock = new SemaphoreSlim(_queueLength, _queueLength); _isFirst = true; _task = Run(); } protected override void Dispose(bool disposing) { if (disposing) _cancelTokenSource.Cancel(); base.Dispose(disposing); } private Task Run() { return Task.Run(async () => { try { long nextTick = Environment.TickCount; int silenceFrames = 0; while (!_cancelToken.IsCancellationRequested) { long tick = Environment.TickCount; long dist = nextTick - tick; if (dist > 0) { await Task.Delay((int)dist).ConfigureAwait(false); continue; } nextTick += _ticksPerFrame; if (!_isPreloaded) { await Task.Delay(_ticksPerFrame).ConfigureAwait(false); continue; } Frame frame; if (_queuedFrames.TryPeek(out frame)) { silenceFrames = 0; uint distance = (uint)(frame.Timestamp - _timestamp); bool restartSeq = _isFirst; if (!_isFirst) { if (distance > uint.MaxValue - (OpusEncoder.FrameSamplesPerChannel * 50 * 5)) //Negative distances wraps { _queuedFrames.TryDequeue(out frame); _bufferPool.Enqueue(frame.Buffer); _queueLock.Release(); #if DEBUG var _ = _logger?.DebugAsync($"Dropped frame {_timestamp} ({_queuedFrames.Count} frames buffered)"); #endif continue; //This is a missed packet less than five seconds old, ignore it } } if (distance == 0 || restartSeq) { //This is the frame we expected _seq = frame.Sequence; _timestamp = frame.Timestamp; _isFirst = false; silenceFrames = 0; _next.WriteHeader(_seq++, _timestamp, false); await _next.WriteAsync(frame.Buffer, 0, frame.Bytes).ConfigureAwait(false); _queuedFrames.TryDequeue(out frame); _bufferPool.Enqueue(frame.Buffer); _queueLock.Release(); #if DEBUG var _ = _logger?.DebugAsync($"Read frame {_timestamp} ({_queuedFrames.Count} frames buffered)"); #endif } else if (distance == OpusEncoder.FrameSamplesPerChannel) { //Missed this frame, but the next queued one might have FEC info _next.WriteHeader(_seq++, _timestamp, true); await _next.WriteAsync(frame.Buffer, 0, frame.Bytes).ConfigureAwait(false); #if DEBUG var _ = _logger?.DebugAsync($"Recreated Frame {_timestamp} (Next is {frame.Timestamp}) ({_queuedFrames.Count} frames buffered)"); #endif } else { //Missed this frame and we have no FEC data to work with _next.WriteHeader(_seq++, _timestamp, true); await _next.WriteAsync(null, 0, 0).ConfigureAwait(false); #if DEBUG var _ = _logger?.DebugAsync($"Missed Frame {_timestamp} (Next is {frame.Timestamp}) ({_queuedFrames.Count} frames buffered)"); #endif } } else if (!_isFirst) { //Missed this frame and we have no FEC data to work with _next.WriteHeader(_seq++, _timestamp, true); await _next.WriteAsync(null, 0, 0).ConfigureAwait(false); if (silenceFrames < 5) silenceFrames++; else { _isFirst = true; _isPreloaded = false; } #if DEBUG var _ = _logger?.DebugAsync($"Missed Frame {_timestamp} ({_queuedFrames.Count} frames buffered)"); #endif } _timestamp += OpusEncoder.FrameSamplesPerChannel; } } catch (OperationCanceledException) { } }); } public override void WriteHeader(ushort seq, uint timestamp, bool missed) { if (_hasHeader) throw new InvalidOperationException("Header received with no payload"); _nextSeq = seq; _nextTimestamp = timestamp; _hasHeader = true; } public override async Task WriteAsync(byte[] data, int offset, int count, CancellationToken cancelToken) { if (cancelToken.CanBeCanceled) cancelToken = CancellationTokenSource.CreateLinkedTokenSource(cancelToken, _cancelToken).Token; else cancelToken = _cancelToken; if (!_hasHeader) throw new InvalidOperationException("Received payload without an RTP header"); _hasHeader = false; uint distance = (uint)(_nextTimestamp - _timestamp); if (!_isFirst && (distance == 0 || distance > OpusEncoder.FrameSamplesPerChannel * 50 * 5)) //Negative distances wraps { #if DEBUG var _ = _logger?.DebugAsync($"Frame {_nextTimestamp} was {distance} samples off. Ignoring."); #endif return; //This is an old frame, ignore } byte[] buffer; if (!await _queueLock.WaitAsync(0).ConfigureAwait(false)) { #if DEBUG var _ = _logger?.DebugAsync($"Buffer overflow"); #endif return; } _bufferPool.TryDequeue(out buffer); Buffer.BlockCopy(data, offset, buffer, 0, count); #if DEBUG { var _ = _logger?.DebugAsync($"Queued Frame {_nextTimestamp}."); } #endif _queuedFrames.Enqueue(new Frame(buffer, count, _nextSeq, _nextTimestamp)); if (!_isPreloaded && _queuedFrames.Count >= _queueLength) { #if DEBUG var _ = _logger?.DebugAsync($"Preloaded"); #endif _isPreloaded = true; } } public override async Task FlushAsync(CancellationToken cancelToken) { while (true) { cancelToken.ThrowIfCancellationRequested(); if (_queuedFrames.Count == 0) return; await Task.Delay(250, cancelToken).ConfigureAwait(false); } } public override Task ClearAsync(CancellationToken cancelToken) { Frame ignored; do cancelToken.ThrowIfCancellationRequested(); while (_queuedFrames.TryDequeue(out ignored)); return Task.Delay(0); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cache.Affinity; using Apache.Ignite.Core.Impl.Client; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Log; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Impl.Unmanaged.Jni; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Resource; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// This class defines a factory for the main Ignite API. /// <p/> /// Use <see cref="Start()"/> method to start Ignite with default configuration. /// <para/> /// All members are thread-safe and may be used concurrently from multiple threads. /// </summary> public static class Ignition { /// <summary> /// Default configuration section name. /// </summary> public const string ConfigurationSectionName = "igniteConfiguration"; /// <summary> /// Default configuration section name. /// </summary> public const string ClientConfigurationSectionName = "igniteClientConfiguration"; /// <summary> /// Environment variable name to enable alternate stack checks on .NET Core 3+ and .NET 5+. /// This is required to fix "Stack smashing detected" errors that occur instead of NullReferenceException /// on Linux and macOS when Java overwrites SIGSEGV handler installed by .NET in thick client or server mode. /// </summary> private const string EnvEnableAlternateStackCheck = "COMPlus_EnableAlternateStackCheck"; /** */ private static readonly object SyncRoot = new object(); /** GC warning flag. */ private static int _diagPrinted; /** */ private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>(); /** Current DLL name. */ private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); /** Startup info. */ [ThreadStatic] private static Startup _startup; /** Client mode flag. */ [ThreadStatic] private static bool _clientMode; /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static Ignition() { AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; } /// <summary> /// Gets or sets a value indicating whether Ignite should be started in client mode. /// Client nodes cannot hold data in caches. /// </summary> public static bool ClientMode { get { return _clientMode; } set { _clientMode = value; } } /// <summary> /// Starts Ignite with default configuration. By default this method will /// use Ignite configuration defined in <c>{IGNITE_HOME}/config/default-config.xml</c> /// configuration file. If such file is not found, then all system defaults will be used. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite Start() { return Start(new IgniteConfiguration()); } /// <summary> /// Starts all grids specified within given Spring XML configuration file. If Ignite with given name /// is already started, then exception is thrown. In this case all instances that may /// have been started so far will be stopped too. /// </summary> /// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be /// absolute or relative to IGNITE_HOME.</param> /// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st /// found instance is returned.</returns> public static IIgnite Start(string springCfgPath) { return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath}); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with <see cref="ConfigurationSectionName"/> /// name and starts Ignite. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration() { // ReSharper disable once IntroduceOptionalParameters.Global return StartFromApplicationConfiguration(ConfigurationSectionName); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection; if (section == null) throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'", typeof(IgniteConfigurationSection).Name, sectionName)); if (section.IgniteConfiguration == null) throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteConfigurationSection).Name, sectionName)); return Start(section.IgniteConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration" /> from application configuration /// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <param name="configPath">Path to the configuration file.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName, string configPath) { var section = GetConfigurationSection<IgniteConfigurationSection>(sectionName, configPath); if (section.IgniteConfiguration == null) { throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteConfigurationSection).Name, sectionName, configPath)); } return Start(section.IgniteConfiguration); } /// <summary> /// Gets the configuration section. /// </summary> private static T GetConfigurationSection<T>(string sectionName, string configPath) where T : class { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); IgniteArgumentCheck.NotNullOrEmpty(configPath, "configPath"); var fileMap = GetConfigMap(configPath); var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); var section = config.GetSection(sectionName) as T; if (section == null) { throw new ConfigurationErrorsException( string.Format("Could not find {0} with name '{1}' in file '{2}'", typeof(T).Name, sectionName, configPath)); } return section; } /// <summary> /// Gets the configuration file map. /// </summary> private static ExeConfigurationFileMap GetConfigMap(string fileName) { var fullFileName = Path.GetFullPath(fileName); if (!File.Exists(fullFileName)) throw new ConfigurationErrorsException("Specified config file does not exist: " + fileName); return new ExeConfigurationFileMap { ExeConfigFilename = fullFileName }; } /// <summary> /// Starts Ignite with given configuration. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite Start(IgniteConfiguration cfg) { IgniteArgumentCheck.NotNull(cfg, "cfg"); cfg = new IgniteConfiguration(cfg); // Create a copy so that config can be modified and reused. lock (SyncRoot) { // 0. Init logger var log = cfg.Logger ?? new JavaLogger(); log.Debug("Starting Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version); // 1. Log diagnostics. LogDiagnosticMessages(cfg, log); // 2. Create context. JvmDll.Load(cfg.JvmDllPath, log); var cbs = IgniteManager.CreateJvmContext(cfg, log); var env = cbs.Jvm.AttachCurrentThread(); log.Debug("JVM started."); var gridName = cfg.IgniteInstanceName; if (cfg.AutoGenerateIgniteInstanceName) { gridName = (gridName ?? "ignite-instance-") + Guid.NewGuid(); } // 3. Create startup object which will guide us through the rest of the process. _startup = new Startup(cfg, cbs); PlatformJniTarget interopProc = null; try { // 4. Initiate Ignite start. UU.IgnitionStart(env, cfg.SpringConfigUrl, gridName, ClientMode, cfg.Logger != null, cbs.IgniteId, cfg.RedirectJavaConsoleOutput); // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data. var node = _startup.Ignite; interopProc = (PlatformJniTarget)node.InteropProcessor; var javaLogger = log as JavaLogger; if (javaLogger != null) { javaLogger.SetIgnite(node); } // 6. On-start callback (notify lifecycle components). node.OnStart(); Nodes[new NodeKey(_startup.Name)] = node; return node; } catch (Exception ex) { // 1. Perform keys cleanup. string name = _startup.Name; if (name != null) { NodeKey key = new NodeKey(name); if (Nodes.ContainsKey(key)) Nodes.Remove(key); } // 2. Stop Ignite node if it was started. if (interopProc != null) UU.IgnitionStop(gridName, true); // 3. Throw error further (use startup error if exists because it is more precise). if (_startup.Error != null) { // Wrap in a new exception to preserve original stack trace. throw new IgniteException("Failed to start Ignite.NET, check inner exception for details", _startup.Error); } var jex = ex as JavaException; if (jex == null) { throw; } throw ExceptionUtils.GetException(null, jex); } finally { var ignite = _startup.Ignite; _startup = null; if (ignite != null) { ignite.ProcessorReleaseStart(); } } } } /// <summary> /// Performs system checks and logs diagnostic messages. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="log">Log.</param> private static void LogDiagnosticMessages(IgniteConfiguration cfg, ILogger log) { if (!cfg.SuppressWarnings && Interlocked.CompareExchange(ref _diagPrinted, 1, 0) == 0) { if (!GCSettings.IsServerGC) { log.Warn("GC server mode is not enabled, this could lead to less " + "than optimal performance on multi-core machines (to enable see " + "https://docs.microsoft.com/en-us/dotnet/core/run-time-config/garbage-collector)."); } if ((Os.IsLinux || Os.IsMacOs) && Environment.GetEnvironmentVariable(EnvEnableAlternateStackCheck) != "1") { log.Warn("Alternate stack check is not enabled, this will cause 'Stack smashing detected' " + "error when NullReferenceException occurs on .NET Core on Linux and macOS. " + "To enable alternate stack check on .NET Core 3+ and .NET 5+, " + "set {0} environment variable to 1.", EnvEnableAlternateStackCheck); } } } /// <summary> /// Prepare callback invoked from Java. /// </summary> /// <param name="inStream">Input stream with data.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> /// <param name="log">Log.</param> internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream, HandleRegistry handleRegistry, ILogger log) { try { BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(inStream); PrepareConfiguration(reader, outStream, log); PrepareLifecycleHandlers(reader, outStream, handleRegistry); PrepareAffinityFunctions(reader, outStream); outStream.SynchronizeOutput(); } catch (Exception e) { _startup.Error = e; throw; } } /// <summary> /// Prepare configuration. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Response stream.</param> /// <param name="log">Log.</param> private static void PrepareConfiguration(BinaryReader reader, PlatformMemoryStream outStream, ILogger log) { // 1. Load assemblies. IgniteConfiguration cfg = _startup.Configuration; LoadAllAssemblies(cfg.Assemblies); ICollection<string> cfgAssembllies; BinaryConfiguration binaryCfg; BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg); LoadAllAssemblies(cfgAssembllies); // 2. Create marshaller only after assemblies are loaded. if (cfg.BinaryConfiguration == null) cfg.BinaryConfiguration = binaryCfg; _startup.Marshaller = new Marshaller(cfg.BinaryConfiguration, log); // 3. Send configuration details to Java cfg.Validate(log); // Use system marshaller. cfg.Write(BinaryUtils.Marshaller.StartMarshal(outStream)); } /// <summary> /// Prepare lifecycle handlers. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> private static void PrepareLifecycleHandlers(IBinaryRawReader reader, IBinaryStream outStream, HandleRegistry handleRegistry) { IList<LifecycleHandlerHolder> beans = new List<LifecycleHandlerHolder> { new LifecycleHandlerHolder(new InternalLifecycleHandler()) // add internal bean for events }; // 1. Read beans defined in Java. int cnt = reader.ReadInt(); for (int i = 0; i < cnt; i++) beans.Add(new LifecycleHandlerHolder(CreateObject<ILifecycleHandler>(reader))); // 2. Append beans defined in local configuration. ICollection<ILifecycleHandler> nativeBeans = _startup.Configuration.LifecycleHandlers; if (nativeBeans != null) { foreach (ILifecycleHandler nativeBean in nativeBeans) beans.Add(new LifecycleHandlerHolder(nativeBean)); } // 3. Write bean pointers to Java stream. outStream.WriteInt(beans.Count); foreach (LifecycleHandlerHolder bean in beans) outStream.WriteLong(handleRegistry.AllocateCritical(bean)); // 4. Set beans to STARTUP object. _startup.LifecycleHandlers = beans; } /// <summary> /// Prepares the affinity functions. /// </summary> private static void PrepareAffinityFunctions(BinaryReader reader, PlatformMemoryStream outStream) { var cnt = reader.ReadInt(); var writer = reader.Marshaller.StartMarshal(outStream); for (var i = 0; i < cnt; i++) { var objHolder = new ObjectInfoHolder(reader); AffinityFunctionSerializer.Write(writer, objHolder.CreateInstance<IAffinityFunction>(), objHolder); } } /// <summary> /// Creates an object and sets the properties. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Resulting object.</returns> private static T CreateObject<T>(IBinaryRawReader reader) { return IgniteUtils.CreateInstance<T>(reader.ReadString(), reader.ReadDictionaryAsGeneric<string, object>()); } /// <summary> /// Kernal start callback. /// </summary> /// <param name="interopProc">Interop processor.</param> /// <param name="stream">Stream.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "PlatformJniTarget is passed further")] internal static void OnStart(GlobalRef interopProc, IBinaryStream stream) { try { // 1. Read data and leave critical state ASAP. BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(stream); // ReSharper disable once PossibleInvalidOperationException var name = reader.ReadString(); // 2. Set ID and name so that Start() method can use them later. _startup.Name = name; if (Nodes.ContainsKey(new NodeKey(name))) throw new IgniteException("Ignite with the same name already started: " + name); _startup.Ignite = new Ignite(_startup.Configuration, _startup.Name, new PlatformJniTarget(interopProc, _startup.Marshaller), _startup.Marshaller, _startup.LifecycleHandlers, _startup.Callbacks); } catch (Exception e) { // 5. Preserve exception to throw it later in the "Start" method and throw it further // to abort startup in Java. _startup.Error = e; throw; } } /// <summary> /// Load assemblies. /// </summary> /// <param name="assemblies">Assemblies.</param> private static void LoadAllAssemblies(IEnumerable<string> assemblies) { if (assemblies != null) { foreach (var s in assemblies) { LoadAssembly(s); } } } /// <summary> /// Load assembly from file, directory, or full name. /// </summary> /// <param name="asm">Assembly file, directory, or full name.</param> internal static void LoadAssembly(string asm) { // 1. Try loading as directory. if (Directory.Exists(asm)) { string[] files = Directory.GetFiles(asm, "*.dll"); foreach (string dllPath in files) { if (!SelfAssembly(dllPath)) { try { Assembly.LoadFile(dllPath); } catch (BadImageFormatException) { // No-op. } } } return; } // 2. Try loading using full-name. try { Assembly assembly = Assembly.Load(asm); if (assembly != null) return; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + asm, e); } // 3. Try loading using file path. try { Assembly assembly = Assembly.LoadFrom(asm); // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (assembly != null) return; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + asm, e); } // 4. Not found, exception. throw new IgniteException("Failed to load assembly: " + asm); } /// <summary> /// Whether assembly points to Ignite binary. /// </summary> /// <param name="assembly">Assembly to check..</param> /// <returns><c>True</c> if this is one of GG assemblies.</returns> private static bool SelfAssembly(string assembly) { return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Gets a named Ignite instance. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p /> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned.</param> /// <returns> /// An instance of named grid. /// </returns> /// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception> public static IIgnite GetIgnite(string name) { var ignite = TryGetIgnite(name); if (ignite == null) throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name); return ignite; } /// <summary> /// Gets the default Ignite instance with null name, or an instance with any name when there is only one. /// <para /> /// Note that caller of this method should not assume that it will return the same instance every time. /// </summary> /// <returns>Default Ignite instance.</returns> /// <exception cref="IgniteException">When there is no matching Ignite instance.</exception> public static IIgnite GetIgnite() { lock (SyncRoot) { if (Nodes.Count == 0) { throw new IgniteException("Failed to get default Ignite instance: " + "there are no instances started."); } if (Nodes.Count == 1) { return Nodes.Single().Value; } Ignite result; if (Nodes.TryGetValue(new NodeKey(null), out result)) { return result; } throw new IgniteException(string.Format("Failed to get default Ignite instance: " + "there are {0} instances started, and none of them has null name.", Nodes.Count)); } } /// <summary> /// Gets all started Ignite instances. /// </summary> /// <returns>All Ignite instances.</returns> public static ICollection<IIgnite> GetAll() { lock (SyncRoot) { return Nodes.Values.ToArray(); } } /// <summary> /// Gets a named Ignite instance, or <c>null</c> if none found. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p/> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned. /// </param> /// <returns>An instance of named grid, or null.</returns> public static IIgnite TryGetIgnite(string name) { lock (SyncRoot) { Ignite result; return !Nodes.TryGetValue(new NodeKey(name), out result) ? null : result; } } /// <summary> /// Gets the default Ignite instance with null name, or an instance with any name when there is only one. /// Returns null when there are no Ignite instances started, or when there are more than one, /// and none of them has null name. /// </summary> /// <returns>An instance of default no-name grid, or null.</returns> public static IIgnite TryGetIgnite() { lock (SyncRoot) { if (Nodes.Count == 1) { return Nodes.Single().Value; } return TryGetIgnite(null); } } /// <summary> /// Stops named grid. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. If /// grid name is <c>null</c>, then default no-name Ignite will be stopped. /// </summary> /// <param name="name">Grid name. If <c>null</c>, then default no-name Ignite will be stopped.</param> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.cancel</c>method.</param> /// <returns><c>true</c> if named Ignite instance was indeed found and stopped, <c>false</c> /// othwerwise (the instance with given <c>name</c> was not found).</returns> public static bool Stop(string name, bool cancel) { lock (SyncRoot) { NodeKey key = new NodeKey(name); Ignite node; if (!Nodes.TryGetValue(key, out node)) return false; node.Stop(cancel); Nodes.Remove(key); GC.Collect(); return true; } } /// <summary> /// Stops <b>all</b> started grids. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. /// </summary> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.Cancel()</c> method.</param> public static void StopAll(bool cancel) { lock (SyncRoot) { while (Nodes.Count > 0) { var entry = Nodes.First(); entry.Value.Stop(cancel); Nodes.Remove(entry.Key); } } GC.Collect(); } /// <summary> /// Connects Ignite lightweight (thin) client to an Ignite node. /// <para /> /// Thin client connects to an existing Ignite node with a socket and does not start JVM in process. /// </summary> /// <param name="clientConfiguration">The client configuration.</param> /// <returns>Ignite client instance.</returns> public static IIgniteClient StartClient(IgniteClientConfiguration clientConfiguration) { IgniteArgumentCheck.NotNull(clientConfiguration, "clientConfiguration"); return new IgniteClient(clientConfiguration); } /// <summary> /// Reads <see cref="IgniteClientConfiguration"/> from application configuration /// <see cref="IgniteClientConfigurationSection"/> with <see cref="ClientConfigurationSectionName"/> /// name and connects Ignite lightweight (thin) client to an Ignite node. /// <para /> /// Thin client connects to an existing Ignite node with a socket and does not start JVM in process. /// </summary> /// <returns>Ignite client instance.</returns> public static IIgniteClient StartClient() { // ReSharper disable once IntroduceOptionalParameters.Global return StartClient(ClientConfigurationSectionName); } /// <summary> /// Reads <see cref="IgniteClientConfiguration" /> from application configuration /// <see cref="IgniteClientConfigurationSection" /> with specified name and connects /// Ignite lightweight (thin) client to an Ignite node. /// <para /> /// Thin client connects to an existing Ignite node with a socket and does not start JVM in process. /// </summary> /// <param name="sectionName">Name of the configuration section.</param> /// <returns>Ignite client instance.</returns> public static IIgniteClient StartClient(string sectionName) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); var section = ConfigurationManager.GetSection(sectionName) as IgniteClientConfigurationSection; if (section == null) { throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'.", typeof(IgniteClientConfigurationSection).Name, sectionName)); } if (section.IgniteClientConfiguration == null) { throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteClientConfigurationSection).Name, sectionName)); } return StartClient(section.IgniteClientConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration" /> from application configuration /// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <param name="configPath">Path to the configuration file.</param> /// <returns>Started Ignite.</returns> public static IIgniteClient StartClient(string sectionName, string configPath) { var section = GetConfigurationSection<IgniteClientConfigurationSection>(sectionName, configPath); if (section.IgniteClientConfiguration == null) { throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteClientConfigurationSection).Name, sectionName, configPath)); } return StartClient(section.IgniteClientConfiguration); } /// <summary> /// Handles the DomainUnload event of the CurrentDomain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private static void CurrentDomain_DomainUnload(object sender, EventArgs e) { // If we don't stop Ignite.NET on domain unload, // we end up with broken instances in Java (invalid callbacks, etc). // IIS, in particular, is known to unload and reload domains within the same process. StopAll(true); } /// <summary> /// Grid key. Workaround for non-null key requirement in Dictionary. /// </summary> private class NodeKey { /** */ private readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="NodeKey"/> class. /// </summary> /// <param name="name">The name.</param> internal NodeKey(string name) { _name = name; } /** <inheritdoc /> */ public override bool Equals(object obj) { var other = obj as NodeKey; return other != null && Equals(_name, other._name); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", Justification = "Not available on .NET FW")] public override int GetHashCode() { return _name == null ? 0 : _name.GetHashCode(); } } /// <summary> /// Value object to pass data between .NET methods during startup bypassing Java. /// </summary> private class Startup { /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="cbs"></param> internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { Configuration = cfg; Callbacks = cbs; } /// <summary> /// Configuration. /// </summary> internal IgniteConfiguration Configuration { get; private set; } /// <summary> /// Gets unmanaged callbacks. /// </summary> internal UnmanagedCallbacks Callbacks { get; private set; } /// <summary> /// Lifecycle handlers. /// </summary> internal IList<LifecycleHandlerHolder> LifecycleHandlers { get; set; } /// <summary> /// Node name. /// </summary> internal string Name { get; set; } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get; set; } /// <summary> /// Start error. /// </summary> internal Exception Error { get; set; } /// <summary> /// Gets or sets the ignite. /// </summary> internal Ignite Ignite { get; set; } } /// <summary> /// Internal handler for event notification. /// </summary> private class InternalLifecycleHandler : ILifecycleHandler { /** */ #pragma warning disable 649 // unused field [InstanceResource] private readonly IIgnite _ignite; /** <inheritdoc /> */ public void OnLifecycleEvent(LifecycleEventType evt) { if (evt == LifecycleEventType.BeforeNodeStop && _ignite != null) ((Ignite) _ignite).BeforeNodeStop(); } } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System; using System.IO; using System.Collections; using NUnit.Framework; using NPOI.POIFS.Storage; using NPOI.Util; using NPOI.POIFS.FileSystem; using NPOI.POIFS.Common; using System.Collections.Generic; namespace TestCases.POIFS.Storage { /** * Class to Test SmallDocumentBlock functionality * * @author Marc Johnson */ [TestFixture] public class TestSmallDocumentBlock { private static byte[] testData; private static int testDataSize = 2999; public TestSmallDocumentBlock() { testData = new byte[testDataSize]; for (int i = 0; i < testData.Length; i++) { testData[i] = (byte)i; } } /** * Test conversion from DocumentBlocks * * @exception IOException */ [Test] public void TestConvert1() { MemoryStream stream = new MemoryStream(testData); List<DocumentBlock> documents = new List<DocumentBlock>(); while (true) { DocumentBlock block = new DocumentBlock(stream, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); documents.Add(block); if (block.PartiallyRead) { break; } } SmallDocumentBlock[] results = SmallDocumentBlock.Convert(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, documents.ToArray(), testDataSize); Assert.AreEqual((testDataSize + 63) / 64, results.Length, "checking correct result size: "); MemoryStream output = new MemoryStream(); for (int j = 0; j < results.Length; j++) { results[j].WriteBlocks(output); } byte[] output_array = output.ToArray(); Assert.AreEqual(64 * results.Length, output_array.Length, "checking correct output size: "); int index = 0; for (; index < testDataSize; index++) { Assert.AreEqual(testData[index], output_array[index], "checking output " + index); } for (; index < output_array.Length; index++) { Assert.AreEqual((byte)0xff, output_array[index], "checking output " + index); } } /** * Test conversion from byte array * * @exception IOException; * * @exception IOException */ [Test] public void TestConvert2() { for (int j = 0; j < 320; j++) { byte[] array = new byte[j]; for (int k = 0; k < j; k++) { array[k] = (byte)255; //Tony Qu changed } SmallDocumentBlock[] blocks = SmallDocumentBlock.Convert(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, array, 319); Assert.AreEqual(5, blocks.Length); MemoryStream stream = new MemoryStream(); for (int k = 0; k < blocks.Length; k++) { blocks[k].WriteBlocks(stream); } stream.Close(); byte[] output = stream.ToArray(); for (int k = 0; k < array.Length; k++) { Assert.AreEqual(array[k], output[k], k.ToString()); } for (int k = array.Length; k < 320; k++) { Assert.AreEqual((byte)0xFF, output[k], k.ToString()); } } } /** * Test Read method * * @exception IOException */ [Test] public void TestRead() { MemoryStream stream = new MemoryStream(testData); ArrayList documents = new ArrayList(); while (true) { DocumentBlock block = new DocumentBlock(stream, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); documents.Add(block); if (block.PartiallyRead) { break; } } SmallDocumentBlock[] blocks = SmallDocumentBlock.Convert(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, (BlockWritable[])documents.ToArray(typeof(DocumentBlock)), testDataSize); for (int j = 1; j <= testDataSize; j += 38) { byte[] buffer = new byte[j]; int offset = 0; for (int k = 0; k < (testDataSize / j); k++) { SmallDocumentBlock.Read(blocks, buffer, offset); for (int n = 0; n < buffer.Length; n++) { Assert.AreEqual(testData[(k * j) + n], buffer[n], "checking byte " + (k * j) + n); } offset += j; } } } /** * Test fill * * @exception IOException */ [Test] public void TestFill() { for (int j = 0; j <= 8; j++) { List<SmallDocumentBlock> blocks = new List<SmallDocumentBlock>(); for (int k = 0; k < j; k++) { blocks.Add(null); } int result = SmallDocumentBlock.Fill(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, blocks); Assert.AreEqual((j + 7) / 8, result, "correct big block count: "); Assert.AreEqual(8 * result, blocks.Count, "correct small block count: "); for (int m = j; m < blocks.Count; m++) { BlockWritable block = blocks[m]; MemoryStream stream = new MemoryStream(); block.WriteBlocks(stream); byte[] output = stream.ToArray(); Assert.AreEqual(64, output.Length, "correct output size (block[ " + m + " ]): "); for (int n = 0; n < 64; n++) { Assert.AreEqual((byte)0xff, output[n], "correct value (block[ " + m + " ][ " + n + " ]): "); } } } } /** * Test calcSize */ [Test] public void TestCalcSize() { for (int j = 0; j < 10; j++) { Assert.AreEqual(j * 64, SmallDocumentBlock.CalcSize(j), "testing " + j); } } /** * Test extract method * * @exception IOException */ [Test] public void TestExtract() { byte[] data = new byte[512]; int offset = 0; for (int j = 0; j < 8; j++) { for (int k = 0; k < 64; k++) { data[offset++] = (byte)(k + j); } } RawDataBlock[] blocks = { new RawDataBlock(new MemoryStream(data)) }; IList<SmallDocumentBlock> output = SmallDocumentBlock.Extract(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, (ListManagedBlock[])blocks); offset = 0; foreach (SmallDocumentBlock block in output) { byte[] out_data = block.Data; Assert.AreEqual(64, out_data.Length, "testing block at offset " + offset); for (int j = 0; j < out_data.Length; j++) { Assert.AreEqual(data[offset], out_data[j], "testing byte at offset " + offset); offset++; } } } } }
using System; using System.Collections; using System.ComponentModel; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Rainbow.Framework.Security; using Rainbow.Framework.Site.Configuration; namespace Rainbow.Framework.Web.UI.WebControls { /// <summary> /// Represents a flat navigation bar. /// One dimension. /// Can render horizontally or vertically. /// </summary> public class DesktopNavigation : DataList, INavigation { /// <summary> /// Default constructor /// </summary> public DesktopNavigation() { EnableViewState = false; RepeatDirection = RepeatDirection.Horizontal; Load += new EventHandler(LoadControl); } /// <summary> /// Loads the control. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> private void LoadControl(object sender, EventArgs e) { if (AutoBind) DataBind(); } private RepeatDirection rd = RepeatDirection.Horizontal; /// <summary> /// Gets or sets whether the <see cref="T:System.Web.UI.WebControls.DataList"></see> control displays vertically or horizontally. /// </summary> /// <value></value> /// <returns>One of the <see cref="T:System.Web.UI.WebControls.RepeatDirection"></see> values. The default is Vertical.</returns> /// <exception cref="T:System.ArgumentException">The specified value is not one of the <see cref="T:System.Web.UI.WebControls.RepeatDirection"></see> values. </exception> [ DefaultValue(RepeatDirection.Horizontal) ] public override RepeatDirection RepeatDirection { get { return rd; } set { rd = value; } } /// <summary> /// Gives the me URL. /// </summary> /// <param name="tab">The tab.</param> /// <param name="id">The id.</param> /// <returns></returns> public string giveMeUrl(string tab, int id) { if (!UseTabNameInUrl) return HttpUrlBuilder.BuildUrl(id); string auxtab = string.Empty; foreach (char c in tab) if (char.IsLetterOrDigit(c)) auxtab += c; else auxtab += "_"; return HttpUrlBuilder.BuildUrl("~/" + auxtab + ".aspx", id); } #region INavigation implementation private bool _useTabNameInUrl = false; /// <summary> /// Indicates if control show the tabname in the url /// </summary> /// <value><c>true</c> if [use tab name in URL]; otherwise, <c>false</c>.</value> [Category("Data"), PersistenceMode(PersistenceMode.Attribute)] public bool UseTabNameInUrl { get { return _useTabNameInUrl; } set { _useTabNameInUrl = value; } } private BindOption _bind = BindOption.BindOptionTop; private bool _autoBind = false; //MH: added 29/04/2003 by mario@hartmann.net private int _definedParentTab = -1; //MH: end /// <summary> /// Indicates if control should bind when loads /// </summary> /// <value><c>true</c> if [auto bind]; otherwise, <c>false</c>.</value> [ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] public bool AutoBind { get { return _autoBind; } set { _autoBind = value; } } /// <summary> /// Describes how this control should bind to db data /// </summary> /// <value>The bind.</value> [ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] public BindOption Bind { get { return _bind; } set { if (_bind != value) { _bind = value; } } } //MH: added 23/05/2003 by mario@hartmann.net /// <summary> /// defines the parentPageID when using BindOptionDefinedParent /// </summary> /// <value>The parent page ID.</value> [ Category("Data"), PersistenceMode(PersistenceMode.Attribute) ] public int ParentPageID { get { return _definedParentTab; } set { if (_definedParentTab != value) { _definedParentTab = value; } } } //MH: end #endregion private object innerDataSource = null; /// <summary> /// Populates ArrayList of tabs based on binding option selected. /// </summary> /// <returns></returns> protected object GetInnerDataSource() { ArrayList authorizedTabs = new ArrayList(); if (HttpContext.Current != null) { // Obtain PortalSettings from Current Context PortalSettings portalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"]; switch (Bind) { case BindOption.BindOptionTop: { authorizedTabs = GetTabs(0, portalSettings.ActivePage.PageID, portalSettings.DesktopPages); break; } case BindOption.BindOptionCurrentChilds: { int currentTabRoot = PortalSettings.GetRootPage(portalSettings.ActivePage, portalSettings.DesktopPages). PageID; authorizedTabs = GetTabs(currentTabRoot, portalSettings.ActivePage.PageID, portalSettings.DesktopPages); break; } case BindOption.BindOptionSubtabSibling: { int currentTabRoot; if (portalSettings.ActivePage.ParentPageID == 0) currentTabRoot = portalSettings.ActivePage.PageID; else currentTabRoot = portalSettings.ActivePage.ParentPageID; authorizedTabs = GetTabs(currentTabRoot, portalSettings.ActivePage.PageID, portalSettings.DesktopPages); break; // int tmpPageID = 0; // // if(portalSettings.ActivePage.ParentPageID == 0) // { // tmpPageID = portalSettings.ActivePage.PageID; // } // else // { // tmpPageID = portalSettings.ActivePage.ParentPageID; // } // ArrayList parentTabs = GetTabs(tmpPageID, portalSettings.DesktopPages); // try // { // if (parentTabs.Count > 0) // { // PageStripDetails currentParentTab = (PageStripDetails) parentTabs[this.SelectedIndex]; // this.SelectedIndex = -1; // authorizedTabs = GetTabs(portalSettings.ActivePage.PageID, currentParentTab.Pages); // } // } // catch // {} // break; } case BindOption.BindOptionChildren: { authorizedTabs = GetTabs(portalSettings.ActivePage.PageID, portalSettings.ActivePage.PageID, portalSettings.DesktopPages); break; } case BindOption.BindOptionSiblings: { authorizedTabs = GetTabs(portalSettings.ActivePage.ParentPageID, portalSettings.ActivePage.PageID, portalSettings.DesktopPages); break; } //MH: added 19/09/2003 by mario@hartmann.net case BindOption.BindOptionTabSibling: { authorizedTabs = GetTabs(portalSettings.ActivePage.PageID, portalSettings.ActivePage.PageID, portalSettings.DesktopPages); if (authorizedTabs.Count == 0) authorizedTabs = GetTabs(portalSettings.ActivePage.ParentPageID, portalSettings.ActivePage.PageID, portalSettings.DesktopPages); break; } //MH: added 29/04/2003 by mario@hartmann.net case BindOption.BindOptionDefinedParent: if (ParentPageID != -1) authorizedTabs = GetTabs(ParentPageID, portalSettings.ActivePage.PageID, portalSettings.DesktopPages); break; //MH: end default: { break; } } } return authorizedTabs; } /// <summary> /// Gets the selected tab. /// </summary> /// <param name="parentPageID">The parent page ID.</param> /// <param name="activePageID">The active page ID.</param> /// <param name="allTabs">All tabs.</param> /// <returns></returns> private int GetSelectedTab(int parentPageID, int activePageID, IList allTabs) { for (int i = 0; i < allTabs.Count; i++) { PageStripDetails tmpTab = (PageStripDetails) allTabs[i]; if (tmpTab.PageID == activePageID) { int selectedPageID = activePageID; if (tmpTab.ParentPageID != parentPageID) { selectedPageID = GetSelectedTab(parentPageID, tmpTab.ParentPageID, allTabs); return selectedPageID; } else { return selectedPageID; } } } return 0; } /// <summary> /// Gets the tabs. /// </summary> /// <param name="parentID">The parent ID.</param> /// <param name="tabID">The tab ID.</param> /// <param name="Tabs">The tabs.</param> /// <returns></returns> private ArrayList GetTabs(int parentID, int tabID, IList Tabs) { ArrayList authorizedTabs = new ArrayList(); int index = -1; //MH:get the selected tab for this int selectedPageID = GetSelectedTab(parentID, tabID, Tabs); // Populate Tab List with authorized tabs for (int i = 0; i < Tabs.Count; i++) { PageStripDetails tab = (PageStripDetails) Tabs[i]; if (tab.ParentPageID == parentID) // Get selected row only { if (PortalSecurity.IsInRoles(tab.AuthorizedRoles)) { index = authorizedTabs.Add(tab); //MH:if (tab.PageID == tabID) //MH:added to support the selected menutab in each level if (tab.PageID == selectedPageID) SelectedIndex = index; } } } return authorizedTabs; } /// <summary> /// DataSource /// </summary> public override object DataSource { get { if (innerDataSource == null) { innerDataSource = GetInnerDataSource(); } return innerDataSource; } set { innerDataSource = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.IO; using System.Xml.Schema; using Xunit; using Xunit.Abstractions; namespace System.Xml.Tests { // ===================== ValidateAttribute ===================== public class TCValidateAttribute_String : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; private ExceptionVerifier _exVerifier; public TCValidateAttribute_String(ITestOutputHelper output) : base(output) { _output = output; _exVerifier = new ExceptionVerifier("System.Xml", _output); } [Theory] [InlineData(null, "")] [InlineData("attr", null)] public void PassNull_LocalName_Namespace__Invalid(String localName, String nameSpace) { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); try { val.ValidateAttribute(localName, nameSpace, "foo", info); } catch (ArgumentNullException) { return; } Assert.True(false); } [Fact] public void PassNullValueGetter__Invalid() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); try { val.ValidateAttribute("attr", "", (string)null, info); } catch (ArgumentNullException) { return; } Assert.True(false); } [Fact] public void PassNullXmlSchemaInfo__Valid() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); val.ValidateAttribute("attr", "", "foo", null); return; } [Theory] [InlineData("RequiredAttribute")] [InlineData("OptionalAttribute")] [InlineData("DefaultAttribute")] [InlineData("FixedAttribute")] [InlineData("FixedRequiredAttribute")] public void Validate_Required_Optional_Default_Fixed_FixedRequired_Attribute(String attrType) { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement(attrType + "Element", "", null); val.ValidateAttribute(attrType, "", "foo", info); Assert.Equal(info.SchemaAttribute.QualifiedName, new XmlQualifiedName(attrType)); Assert.Equal(info.Validity, XmlSchemaValidity.Valid); Assert.Equal(info.SchemaType.TypeCode, XmlTypeCode.String); return; } [Fact] public void ValidateAttributeWithNamespace() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("NamespaceAttributeElement", "", null); val.ValidateAttribute("attr1", "uri:tempuri", "123", info); Assert.Equal(info.SchemaAttribute.QualifiedName, new XmlQualifiedName("attr1", "uri:tempuri")); Assert.Equal(info.Validity, XmlSchemaValidity.Valid); Assert.Equal(info.SchemaType.TypeCode, XmlTypeCode.Int); return; } [Fact] public void ValidateAnyAttribute() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("AnyAttributeElement", "", null); val.ValidateAttribute("SomeAttribute", "", "foo", info); Assert.Equal(info.Validity, XmlSchemaValidity.NotKnown); return; } [Fact] public void AskForDefaultAttributesAndValidateThem() { XmlSchemaValidator val = CreateValidator(XSDFILE_200_DEF_ATTRIBUTES); XmlSchemaInfo info = new XmlSchemaInfo(); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("StressElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); foreach (XmlSchemaAttribute a in atts) { val.ValidateAttribute(a.QualifiedName.Name, a.QualifiedName.Namespace, a.DefaultValue, info); Assert.Equal(info.SchemaAttribute, a); } atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); Assert.Equal(atts.Count, 0); return; } [Fact] public void ValidateTopLevelAttribute() { XmlSchemaValidator val; XmlSchemaSet schemas = new XmlSchemaSet(); XmlSchemaInfo info = new XmlSchemaInfo(); schemas.Add("", Path.Combine(TestData, XSDFILE_200_DEF_ATTRIBUTES)); schemas.Compile(); val = CreateValidator(schemas); val.Initialize(); val.ValidateAttribute("BasicAttribute", "", "foo", info); Assert.Equal(info.SchemaAttribute, schemas.GlobalAttributes[new XmlQualifiedName("BasicAttribute")]); return; } [Fact] public void ValidateSameAttributeTwice() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("RequiredAttributeElement", "", null); val.ValidateAttribute("RequiredAttribute", "", "foo", info); try { val.ValidateAttribute("RequiredAttribute", "", "foo", info); } catch (XmlSchemaValidationException e) { _exVerifier.IsExceptionOk(e, "Sch_DuplicateAttribute", new string[] { "RequiredAttribute" }); return; } Assert.True(false); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Threading; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api.Plugins; using Timer=OpenSim.Region.ScriptEngine.Shared.Api.Plugins.Timer; using System.Reflection; using log4net; namespace OpenSim.Region.ScriptEngine.Shared.Api { /// <summary> /// Handles LSL commands that takes long time and returns an event, for example timers, HTTP requests, etc. /// </summary> public class AsyncCommandManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static Thread cmdHandlerThread; private static int cmdHandlerThreadCycleSleepms; private static int numInstances; /// <summary> /// Lock for reading/writing static components of AsyncCommandManager. /// </summary> /// <remarks> /// This lock exists so that multiple threads from different engines and/or different copies of the same engine /// are prevented from running non-thread safe code (e.g. read/write of lists) concurrently. /// </remarks> private static object staticLock = new object(); private static List<IScriptEngine> m_ScriptEngines = new List<IScriptEngine>(); public IScriptEngine m_ScriptEngine; private static Dictionary<IScriptEngine, Dataserver> m_Dataserver = new Dictionary<IScriptEngine, Dataserver>(); private static Dictionary<IScriptEngine, Timer> m_Timer = new Dictionary<IScriptEngine, Timer>(); private static Dictionary<IScriptEngine, Listener> m_Listener = new Dictionary<IScriptEngine, Listener>(); private static Dictionary<IScriptEngine, HttpRequest> m_HttpRequest = new Dictionary<IScriptEngine, HttpRequest>(); private static Dictionary<IScriptEngine, SensorRepeat> m_SensorRepeat = new Dictionary<IScriptEngine, SensorRepeat>(); private static Dictionary<IScriptEngine, XmlRequest> m_XmlRequest = new Dictionary<IScriptEngine, XmlRequest>(); public Dataserver DataserverPlugin { get { lock (staticLock) return m_Dataserver[m_ScriptEngine]; } } public Timer TimerPlugin { get { lock (staticLock) return m_Timer[m_ScriptEngine]; } } public HttpRequest HttpRequestPlugin { get { lock (staticLock) return m_HttpRequest[m_ScriptEngine]; } } public Listener ListenerPlugin { get { lock (staticLock) return m_Listener[m_ScriptEngine]; } } public SensorRepeat SensorRepeatPlugin { get { lock (staticLock) return m_SensorRepeat[m_ScriptEngine]; } } public XmlRequest XmlRequestPlugin { get { lock (staticLock) return m_XmlRequest[m_ScriptEngine]; } } public IScriptEngine[] ScriptEngines { get { lock (staticLock) return m_ScriptEngines.ToArray(); } } public AsyncCommandManager(IScriptEngine _ScriptEngine) { m_ScriptEngine = _ScriptEngine; // If there is more than one scene in the simulator or multiple script engines are used on the same region // then more than one thread could arrive at this block of code simultaneously. However, it cannot be // executed concurrently both because concurrent list operations are not thread-safe and because of other // race conditions such as the later check of cmdHandlerThread == null. lock (staticLock) { if (m_ScriptEngines.Count == 0) ReadConfig(); if (!m_ScriptEngines.Contains(m_ScriptEngine)) m_ScriptEngines.Add(m_ScriptEngine); // Create instances of all plugins if (!m_Dataserver.ContainsKey(m_ScriptEngine)) m_Dataserver[m_ScriptEngine] = new Dataserver(this); if (!m_Timer.ContainsKey(m_ScriptEngine)) m_Timer[m_ScriptEngine] = new Timer(this); if (!m_HttpRequest.ContainsKey(m_ScriptEngine)) m_HttpRequest[m_ScriptEngine] = new HttpRequest(this); if (!m_Listener.ContainsKey(m_ScriptEngine)) m_Listener[m_ScriptEngine] = new Listener(this); if (!m_SensorRepeat.ContainsKey(m_ScriptEngine)) m_SensorRepeat[m_ScriptEngine] = new SensorRepeat(this); if (!m_XmlRequest.ContainsKey(m_ScriptEngine)) m_XmlRequest[m_ScriptEngine] = new XmlRequest(this); numInstances++; if (cmdHandlerThread == null) { cmdHandlerThread = WorkManager.StartThread( CmdHandlerThreadLoop, "AsyncLSLCmdHandlerThread", ThreadPriority.Normal, true, true); } } } private void ReadConfig() { // cmdHandlerThreadCycleSleepms = m_ScriptEngine.Config.GetInt("AsyncLLCommandLoopms", 100); // TODO: Make this sane again cmdHandlerThreadCycleSleepms = 100; } /* ~AsyncCommandManager() { // Shut down thread try { lock (staticLock) { numInstances--; if(numInstances > 0) return; if (cmdHandlerThread != null) { if (cmdHandlerThread.IsAlive == true) { cmdHandlerThread.Abort(); //cmdHandlerThread.Join(); cmdHandlerThread = null; } } } } catch { } } */ /// <summary> /// Main loop for the manager thread /// </summary> private static void CmdHandlerThreadLoop() { while (true) { try { Thread.Sleep(cmdHandlerThreadCycleSleepms); Watchdog.UpdateThread(); DoOneCmdHandlerPass(); Watchdog.UpdateThread(); } catch ( System.Threading.ThreadAbortException) { } catch (Exception e) { m_log.Error("[ASYNC COMMAND MANAGER]: Exception in command handler pass: ", e); } } } private static void DoOneCmdHandlerPass() { lock (staticLock) { // Check HttpRequests try { m_HttpRequest[m_ScriptEngines[0]].CheckHttpRequests(); } catch {} // Check XMLRPCRequests try { m_XmlRequest[m_ScriptEngines[0]].CheckXMLRPCRequests(); } catch {} foreach (IScriptEngine s in m_ScriptEngines) { // Check Listeners try { m_Listener[s].CheckListeners(); } catch {} // Check timers try { m_Timer[s].CheckTimerEvents(); } catch {} // Check Sensors try { m_SensorRepeat[s].CheckSenseRepeaterEvents(); } catch {} // Check dataserver try { m_Dataserver[s].ExpireRequests(); } catch {} } } } /// <summary> /// Remove a specific script (and all its pending commands) /// </summary> /// <param name="localID"></param> /// <param name="itemID"></param> public static void RemoveScript(IScriptEngine engine, uint localID, UUID itemID) { // Remove a specific script // m_log.DebugFormat("[ASYNC COMMAND MANAGER]: Removing facilities for script {0}", itemID); lock (staticLock) { // Remove dataserver events m_Dataserver[engine].RemoveEvents(localID, itemID); // Remove from: Timers m_Timer[engine].UnSetTimerEvents(localID, itemID); // Remove from: HttpRequest IHttpRequestModule iHttpReq = engine.World.RequestModuleInterface<IHttpRequestModule>(); if (iHttpReq != null) iHttpReq.StopHttpRequest(localID, itemID); IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>(); if (comms != null) comms.DeleteListener(itemID); IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>(); if (xmlrpc != null) { xmlrpc.DeleteChannels(itemID); xmlrpc.CancelSRDRequests(itemID); } // Remove Sensors m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID); } } public static void StateChange(IScriptEngine engine, uint localID, UUID itemID) { // Remove a specific script // Remove dataserver events m_Dataserver[engine].RemoveEvents(localID, itemID); IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>(); if (comms != null) comms.DeleteListener(itemID); IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>(); if (xmlrpc != null) { xmlrpc.DeleteChannels(itemID); xmlrpc.CancelSRDRequests(itemID); } // Remove Sensors m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID); } /// <summary> /// Get the sensor repeat plugin for this script engine. /// </summary> /// <param name="engine"></param> /// <returns></returns> public static SensorRepeat GetSensorRepeatPlugin(IScriptEngine engine) { lock (staticLock) { if (m_SensorRepeat.ContainsKey(engine)) return m_SensorRepeat[engine]; else return null; } } /// <summary> /// Get the dataserver plugin for this script engine. /// </summary> /// <param name="engine"></param> /// <returns></returns> public static Dataserver GetDataserverPlugin(IScriptEngine engine) { lock (staticLock) { if (m_Dataserver.ContainsKey(engine)) return m_Dataserver[engine]; else return null; } } /// <summary> /// Get the timer plugin for this script engine. /// </summary> /// <param name="engine"></param> /// <returns></returns> public static Timer GetTimerPlugin(IScriptEngine engine) { lock (staticLock) { if (m_Timer.ContainsKey(engine)) return m_Timer[engine]; else return null; } } /// <summary> /// Get the listener plugin for this script engine. /// </summary> /// <param name="engine"></param> /// <returns></returns> public static Listener GetListenerPlugin(IScriptEngine engine) { lock (staticLock) { if (m_Listener.ContainsKey(engine)) return m_Listener[engine]; else return null; } } public static Object[] GetSerializationData(IScriptEngine engine, UUID itemID) { List<Object> data = new List<Object>(); lock (staticLock) { Object[] listeners = m_Listener[engine].GetSerializationData(itemID); if (listeners.Length > 0) { data.Add("listener"); data.Add(listeners.Length); data.AddRange(listeners); } Object[] timers=m_Timer[engine].GetSerializationData(itemID); if (timers.Length > 0) { data.Add("timer"); data.Add(timers.Length); data.AddRange(timers); } Object[] sensors = m_SensorRepeat[engine].GetSerializationData(itemID); if (sensors.Length > 0) { data.Add("sensor"); data.Add(sensors.Length); data.AddRange(sensors); } } return data.ToArray(); } public static void CreateFromData(IScriptEngine engine, uint localID, UUID itemID, UUID hostID, Object[] data) { int idx = 0; int len; while (idx < data.Length) { string type = data[idx].ToString(); len = (int)data[idx+1]; idx+=2; if (len > 0) { Object[] item = new Object[len]; Array.Copy(data, idx, item, 0, len); idx+=len; lock (staticLock) { switch (type) { case "listener": m_Listener[engine].CreateFromData(localID, itemID, hostID, item); break; case "timer": m_Timer[engine].CreateFromData(localID, itemID, hostID, item); break; case "sensor": m_SensorRepeat[engine].CreateFromData(localID, itemID, hostID, item); break; } } } } } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Threading; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// Options for calls made by client. /// </summary> public struct CallOptions { Metadata headers; DateTime? deadline; CancellationToken cancellationToken; WriteOptions writeOptions; ContextPropagationToken propagationToken; CallCredentials credentials; CallFlags flags; /// <summary> /// Creates a new instance of <c>CallOptions</c> struct. /// </summary> /// <param name="headers">Headers to be sent with the call.</param> /// <param name="deadline">Deadline for the call to finish. null means no deadline.</param> /// <param name="cancellationToken">Can be used to request cancellation of the call.</param> /// <param name="writeOptions">Write options that will be used for this call.</param> /// <param name="propagationToken">Context propagation token obtained from <see cref="ServerCallContext"/>.</param> /// <param name="credentials">Credentials to use for this call.</param> public CallOptions(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken), WriteOptions writeOptions = null, ContextPropagationToken propagationToken = null, CallCredentials credentials = null) { this.headers = headers; this.deadline = deadline; this.cancellationToken = cancellationToken; this.writeOptions = writeOptions; this.propagationToken = propagationToken; this.credentials = credentials; this.flags = default(CallFlags); } /// <summary> /// Headers to send at the beginning of the call. /// </summary> public Metadata Headers { get { return headers; } } /// <summary> /// Call deadline. /// </summary> public DateTime? Deadline { get { return deadline; } } /// <summary> /// Token that can be used for cancelling the call on the client side. /// Cancelling the token will request cancellation /// of the remote call. Best effort will be made to deliver the cancellation /// notification to the server and interaction of the call with the server side /// will be terminated. Unless the call finishes before the cancellation could /// happen (there is an inherent race), /// the call will finish with <c>StatusCode.Cancelled</c> status. /// </summary> public CancellationToken CancellationToken { get { return cancellationToken; } } /// <summary> /// Write options that will be used for this call. /// </summary> public WriteOptions WriteOptions { get { return this.writeOptions; } } /// <summary> /// Token for propagating parent call context. /// </summary> public ContextPropagationToken PropagationToken { get { return this.propagationToken; } } /// <summary> /// Credentials to use for this call. /// </summary> public CallCredentials Credentials { get { return this.credentials; } } /// <summary> /// If <c>true</c> and and channel is in <c>ChannelState.TransientFailure</c>, the call will attempt waiting for the channel to recover /// instead of failing immediately (which is the default "FailFast" semantics). /// Note: experimental API that can change or be removed without any prior notice. /// </summary> public bool IsWaitForReady { get { return (this.flags & CallFlags.WaitForReady) == CallFlags.WaitForReady; } } /// <summary> /// Flags to use for this call. /// </summary> internal CallFlags Flags { get { return this.flags; } } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Headers</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="headers">The headers.</param> public CallOptions WithHeaders(Metadata headers) { var newOptions = this; newOptions.headers = headers; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Deadline</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="deadline">The deadline.</param> public CallOptions WithDeadline(DateTime deadline) { var newOptions = this; newOptions.deadline = deadline; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>CancellationToken</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> public CallOptions WithCancellationToken(CancellationToken cancellationToken) { var newOptions = this; newOptions.cancellationToken = cancellationToken; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>WriteOptions</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="writeOptions">The write options.</param> public CallOptions WithWriteOptions(WriteOptions writeOptions) { var newOptions = this; newOptions.writeOptions = writeOptions; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>PropagationToken</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="propagationToken">The context propagation token.</param> public CallOptions WithPropagationToken(ContextPropagationToken propagationToken) { var newOptions = this; newOptions.propagationToken = propagationToken; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Credentials</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="credentials">The call credentials.</param> public CallOptions WithCredentials(CallCredentials credentials) { var newOptions = this; newOptions.credentials = credentials; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with "WaitForReady" semantics enabled/disabled. /// <see cref="IsWaitForReady"/>. /// Note: experimental API that can change or be removed without any prior notice. /// </summary> public CallOptions WithWaitForReady(bool waitForReady = true) { if (waitForReady) { return WithFlags(this.flags | CallFlags.WaitForReady); } return WithFlags(this.flags & ~CallFlags.WaitForReady); } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Flags</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="flags">The call flags.</param> internal CallOptions WithFlags(CallFlags flags) { var newOptions = this; newOptions.flags = flags; return newOptions; } /// <summary> /// Returns a new instance of <see cref="CallOptions"/> with /// all previously unset values set to their defaults and deadline and cancellation /// token propagated when appropriate. /// </summary> internal CallOptions Normalize() { var newOptions = this; if (propagationToken != null) { if (propagationToken.Options.IsPropagateDeadline) { GrpcPreconditions.CheckArgument(!newOptions.deadline.HasValue, "Cannot propagate deadline from parent call. The deadline has already been set explicitly."); newOptions.deadline = propagationToken.ParentDeadline; } if (propagationToken.Options.IsPropagateCancellation) { GrpcPreconditions.CheckArgument(!newOptions.cancellationToken.CanBeCanceled, "Cannot propagate cancellation token from parent call. The cancellation token has already been set to a non-default value."); newOptions.cancellationToken = propagationToken.ParentCancellationToken; } } newOptions.headers = newOptions.headers ?? Metadata.Empty; newOptions.deadline = newOptions.deadline ?? DateTime.MaxValue; return newOptions; } } }
using System; using System.Linq.Expressions; using Foundation; using Toggl.Phoebe; using Toggl.Phoebe.Analytics; using Toggl.Phoebe.Data; using XPlatUtils; namespace Toggl.Ross.Data { public class SettingsStore : ISettingsStore { private const string PhoebeUserIdKey = "phoebeUserId"; private const string PhoebeApiTokenKey = "phoebeApiToken"; private const string PhoebeSyncLastRunKey = "phoebeSyncLastRun"; private const string PhoebeUseDefaultTagKey = "phoebeUseDefaultTag"; private const string PhoebeLastAppVersionKey = "phoebeLastAppVersion"; private const string PhoebeExperimentIdKey = "phoebeExperimentId"; private const string PhoebeLastReportZoomKey = "lastReportZoomKey"; private const string PhoebeGroupedEntriesKey = "groupedEntriesKey"; private const string RossInstallIdKey = "rossInstallId"; private const string RossPreferredStartViewKey = "rossPreferredStartView"; private const string RossChooseProjectForNewKey = "rossChooseProjectForNew"; private const string RossReadDurOnlyNoticeKey = "rossReadDurOnlyNotice"; private const string RossIgnoreSyncErrorsUntilKey = "rossIgnoreSyncErrorsUntil"; private const string PhoebeProjectSortKey = "projectSortKey"; private const string PhoebeIsStagingKey = "isStagingKey"; private const string PhoebeShowWelcomeKey = "showWelcomeKey"; private const string PhoebeIsOfflineKey = "isOfflineKey"; private static string GetPropertyName<T> (Expression<Func<SettingsStore, T>> expr) { return expr.ToPropertyName (); } protected Guid? GetGuid (string key) { var val = (string) (NSString)NSUserDefaults.StandardUserDefaults [key]; if (String.IsNullOrEmpty (val)) { return null; } return Guid.Parse (val); } protected void SetGuid (string key, Guid? value) { if (value != null) { NSUserDefaults.StandardUserDefaults [key] = (NSString)value.Value.ToString (); } else { NSUserDefaults.StandardUserDefaults.RemoveObject (key); } NSUserDefaults.StandardUserDefaults.Synchronize (); } protected string GetString (string key) { return (string) (NSString)NSUserDefaults.StandardUserDefaults [key]; } protected void SetString (string key, string value) { if (value != null) { NSUserDefaults.StandardUserDefaults [key] = (NSString)value; } else { NSUserDefaults.StandardUserDefaults.RemoveObject (key); } NSUserDefaults.StandardUserDefaults.Synchronize (); } protected int? GetInt (string key) { var raw = NSUserDefaults.StandardUserDefaults [key]; if (raw == null) { return null; } return (int) (NSNumber)raw; } protected void SetInt (string key, int? value) { if (value != null) { NSUserDefaults.StandardUserDefaults [key] = (NSNumber)value.Value; } else { NSUserDefaults.StandardUserDefaults.RemoveObject (key); } NSUserDefaults.StandardUserDefaults.Synchronize (); } protected DateTime? GetDateTime (string key) { var raw = NSUserDefaults.StandardUserDefaults [key]; if (raw == null) { return null; } return DateTime.FromBinary ((long) (NSNumber)raw); } protected void SetDateTime (string key, DateTime? value) { if (value != null) { NSUserDefaults.StandardUserDefaults [key] = (NSNumber)value.Value.ToBinary (); } else { NSUserDefaults.StandardUserDefaults.RemoveObject (key); } NSUserDefaults.StandardUserDefaults.Synchronize (); } protected void OnSettingChanged (string name) { var bus = ServiceContainer.Resolve<MessageBus> (); bus.Send (new SettingChangedMessage (this, name)); } public static readonly string PropertyUserId = GetPropertyName (s => s.UserId); public Guid? UserId { get { return GetGuid (PhoebeUserIdKey); } set { SetGuid (PhoebeUserIdKey, value); OnSettingChanged (PropertyUserId); } } public string InstallId { get { var val = GetString (RossInstallIdKey); if (String.IsNullOrEmpty (val)) { val = Guid.NewGuid ().ToString (); SetString (RossInstallIdKey, val); } return val; } } public static readonly string PropertyApiToken = GetPropertyName (s => s.ApiToken); public string ApiToken { get { return GetString (PhoebeApiTokenKey); } set { SetString (PhoebeApiTokenKey, value); OnSettingChanged (PropertyApiToken); } } public static readonly string PropertySyncLastRun = GetPropertyName (s => s.SyncLastRun); public DateTime? SyncLastRun { get { return GetDateTime (PhoebeSyncLastRunKey); } set { SetDateTime (PhoebeSyncLastRunKey, value); OnSettingChanged (PropertySyncLastRun); } } public static readonly string PropertyUseDefaultTag = GetPropertyName (s => s.UseDefaultTag); public bool UseDefaultTag { get { return (GetInt (PhoebeUseDefaultTagKey) ?? 1) == 1; } set { SetInt (PhoebeUseDefaultTagKey, value ? 1 : 0); OnSettingChanged (PropertyUseDefaultTag); ServiceContainer.Resolve<ITracker> ().SendSettingsChangeEvent (SettingName.DefaultMobileTag); } } public bool GroupedTimeEntries { get { return GetInt (PhoebeGroupedEntriesKey) == 1; } set { SetInt (PhoebeGroupedEntriesKey, value ? 1 : 0); OnSettingChanged (PhoebeGroupedEntriesKey); ServiceContainer.Resolve<ITracker> ().SendSettingsChangeEvent (SettingName.GroupedTimeEntries); } } public static readonly string PropertyLastAppVersion = GetPropertyName (s => s.LastAppVersion); public string LastAppVersion { get { return GetString (PhoebeLastAppVersionKey); } set { SetString (PhoebeLastAppVersionKey, value); } } public static readonly string PropertyExperimentId = GetPropertyName (s => s.ExperimentId); public string ExperimentId { get { return GetString (PhoebeExperimentIdKey); } set { SetString (PhoebeExperimentIdKey, value); OnSettingChanged (PropertyExperimentId); } } public static readonly string PropertyPreferredStartView = GetPropertyName (s => s.PreferredStartView); public string PreferredStartView { get { return GetString (RossPreferredStartViewKey); } set { SetString (RossPreferredStartViewKey, value); OnSettingChanged (PropertyPreferredStartView); } } public static readonly string PropertyChooseProjectForNew = GetPropertyName (s => s.ChooseProjectForNew); public bool ChooseProjectForNew { get { return GetInt (RossChooseProjectForNewKey) == 1; } set { SetInt (RossChooseProjectForNewKey, value ? 1 : 0); OnSettingChanged (PropertyChooseProjectForNew); ServiceContainer.Resolve<ITracker> ().SendSettingsChangeEvent (SettingName.AskForProject); } } public static readonly string PropertyReadDurOnlyNotice = GetPropertyName (s => s.ReadDurOnlyNotice); public bool ReadDurOnlyNotice { get { return GetInt (RossReadDurOnlyNoticeKey) == 1; } set { SetInt (RossReadDurOnlyNoticeKey, value ? 1 : 0); OnSettingChanged (PropertyReadDurOnlyNotice); } } public static readonly string PropertyIgnoreSyncErrorsUntil = GetPropertyName (s => s.IgnoreSyncErrorsUntil); public DateTime? IgnoreSyncErrorsUntil { get { return GetDateTime (RossIgnoreSyncErrorsUntilKey); } set { SetDateTime (RossIgnoreSyncErrorsUntilKey, value); OnSettingChanged (PropertyIgnoreSyncErrorsUntil); } } public static readonly string PropertyLastReportZoomViewed = GetPropertyName (s => s.LastReportZoomViewed); public int? LastReportZoomViewed { get { return GetInt (PhoebeLastReportZoomKey); } set { SetInt (PhoebeLastReportZoomKey, value); OnSettingChanged (PropertyLastReportZoomViewed); } } public static readonly string PropertyProjectSort = GetPropertyName (s => s.SortProjectsBy); public string SortProjectsBy { get { return (GetString (PhoebeProjectSortKey)); } set { SetString (PhoebeProjectSortKey, value); } } public static readonly string PropertyIsStagingMode = GetPropertyName (s => s.IsStagingMode); public bool IsStagingMode { get { return GetInt (PhoebeIsStagingKey) == 1; } set { SetInt (PhoebeIsStagingKey, value ? 1 : 0); OnSettingChanged (PropertyIsStagingMode); } } public static readonly string PropertyShowWelcome = GetPropertyName (s => s.ShowWelcome); public bool ShowWelcome { get { return (GetInt (PhoebeShowWelcomeKey) ?? 1) == 1; } set { SetInt (PhoebeShowWelcomeKey, value ? 1 : 0); } } public bool OfflineMode { get { return false; } set { SetInt (PhoebeIsOfflineKey, value ? 1 : 0); } } } }
/* Genuine Channels product. * * Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved. * * This source code comes under and must be used and distributed according to the Genuine Channels license agreement. */ using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Net; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading; using Belikov.Common.ThreadProcessing; using Belikov.GenuineChannels.Connection; using Belikov.GenuineChannels.DotNetRemotingLayer; using Belikov.GenuineChannels.Logbook; using Belikov.GenuineChannels.Messaging; using Belikov.GenuineChannels.Parameters; using Belikov.GenuineChannels.Security; using Belikov.GenuineChannels.TransportContext; using Belikov.GenuineChannels.Utilities; using Zyan.SafeDeserializationHelpers; namespace Belikov.GenuineChannels.GenuineHttp { /// <summary> /// Implements HTTP transport manager working via .NET Remoting http web request implementation. /// </summary> internal class HttpClientConnectionManager : ConnectionManager, ITimerConsumer { /// <summary> /// Constructs an instance of the HttpClientConnectionManager class. /// </summary> /// <param name="iTransportContext">The transport context.</param> public HttpClientConnectionManager(ITransportContext iTransportContext) : base(iTransportContext) { this.Local = new HostInformation("_ghttp://" + iTransportContext.HostIdentifier, iTransportContext); // calculate host renewing timespan this._hostRenewingSpan = GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]) + GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]); this._internal_TimerCallback = new WaitCallback(Internal_TimerCallback); this._pool_Sender_OnEndSending_ContinueExchange = new WaitCallback(this.Pool_Sender_OnEndSending_ContinueExchange); this._listener_OnEndReceiving_ContinueExchange = new WaitCallback(this.Pool_Sender_OnEndSending_ContinueExchange); this._webRequestInitiationTimeout = (TimeSpan) iTransportContext.IParameterProvider[GenuineParameter.HttpWebRequestInitiationTimeout]; this._httpAsynchronousRequestTimeout = GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.HttpAsynchronousRequestTimeout]); TimerProvider.Attach(this); } /// <summary> /// Sends the message to the remote host. /// </summary> /// <param name="message">The message to be sent.</param> protected override void InternalSend(Message message) { switch (message.SecuritySessionParameters.GenuineConnectionType) { case GenuineConnectionType.Persistent: this.InternalSend(message, this.Pool_GetConnectionForSending(message)); break; case GenuineConnectionType.Named: throw new NotSupportedException("Genuine HTTP client connection manager doesn't support named connections."); case GenuineConnectionType.Invocation: HttpInvocationConnection httpInvocationConnection = this.FindInvocationConnection(message); httpInvocationConnection.SendMessage(message); break; } } /// <summary> /// Sends the message to the remote host. /// </summary> /// <param name="message">The message to be sent.</param> /// <param name="httpClientConnection">The connection.</param> private void InternalSend(Message message, HttpClientConnection httpClientConnection) { bool sendingLockObtained = false; lock (httpClientConnection.SendingLock) { if (! httpClientConnection.IsSent) { httpClientConnection.IsSent = true; sendingLockObtained = true; } else { httpClientConnection.MessageContainer.AddMessage(message, false); } } if (sendingLockObtained) this.LowLevel_Sender_Send(message, httpClientConnection, httpClientConnection.OnEndSending, false); } #region -- Invocation connections ---------------------------------------------------------- /// <summary> /// Set of invocation connections { remote url => connection }. /// </summary> private Hashtable _invocation = Hashtable.Synchronized(new Hashtable()); /// <summary> /// Gets an invocation connection that is able to deliver a message and receive a result. /// </summary> /// <param name="message">The source message.</param> /// <returns>An invocation connection that is able to deliver a message and receive a result.</returns> private HttpInvocationConnection FindInvocationConnection(Message message) { lock (this._invocation.SyncRoot) { HttpInvocationConnection httpInvocationConnection = this._invocation[message.Recipient.Url] as HttpInvocationConnection; if (httpInvocationConnection == null) this._invocation[message.Recipient.Url] = httpInvocationConnection = new HttpInvocationConnection(this.ITransportContext, message.Recipient); return httpInvocationConnection; } } #endregion #region -- Pool management ----------------------------------------------------------------- /// <summary> /// Set of connections {remote url => connection}. /// </summary> private Hashtable _persistent = Hashtable.Synchronized(new Hashtable()); /// <summary> /// TimeSpan to renew the host resource for. /// </summary> private int _hostRenewingSpan; /// <summary> /// Opens or returns established connection according to message parameters. /// </summary> /// <param name="message">The message.</param> /// <returns>The established connection.</returns> private HttpClientConnection Pool_GetConnectionForSending(Message message) { HttpClientConnection httpClientConnection = null; using (new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) throw OperationException.WrapException(this._disposeReason); } string connectionName = message.ConnectionName; if (connectionName == null || connectionName.Length <= 0) connectionName = "$/__GC/" + message.Recipient.PrimaryUri; if (! Monitor.TryEnter(message.Recipient.PersistentConnectionEstablishingLock, GenuineUtility.GetMillisecondsLeft(message.FinishTime))) throw GenuineExceptions.Get_Send_Timeout(); try { lock (this._persistent.SyncRoot) { httpClientConnection = this._persistent[message.Recipient.Url] as HttpClientConnection; if (httpClientConnection != null && httpClientConnection._disposed) { this._persistent.Remove(message.Recipient.Url); httpClientConnection = null; } if (httpClientConnection != null) return httpClientConnection; } // it's necessary to open the connection to the remote host httpClientConnection = this.LowLevel_OpenConnection(message.Recipient, message.SecuritySessionParameters.GenuineConnectionType, connectionName); using (new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) { httpClientConnection.Dispose(this._disposeReason); throw OperationException.WrapException(this._disposeReason); } this._persistent[message.Recipient.Url] = httpClientConnection; } httpClientConnection.SignalState(GenuineEventType.GeneralConnectionEstablished, null, null); httpClientConnection.MessageContainer = new MessageContainer(this.ITransportContext); } finally { Monitor.Exit(message.Recipient.PersistentConnectionEstablishingLock); } return httpClientConnection; } /// <summary> /// Finishes sending a message through the connection. /// </summary> /// <param name="httpClientConnection">The connection.</param> /// <param name="httpWebResponse">The received response.</param> public void Pool_Sender_OnEndSending(HttpClientConnection httpClientConnection, HttpWebResponse httpWebResponse) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; Stream inputStream = null; try { httpClientConnection.Remote.Renew(this._hostRenewingSpan, false); httpClientConnection.LastMessageWasReceviedAt = GenuineUtility.TickCount; httpClientConnection.SignalState(GenuineEventType.GeneralConnectionEstablished, null, null); httpClientConnection.SentContent.Close(); httpClientConnection.SentContent = null; httpClientConnection.MessagesBeingSent.Clear(); // process the content inputStream = httpWebResponse.GetResponseStream(); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { GenuineChunkedStream content = null; if (binaryLogWriter[LogCategory.Transport] > 1) { content = new GenuineChunkedStream(false); GenuineUtility.CopyStreamToStream(inputStream, content, (int) httpWebResponse.ContentLength); } binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.Pool_Sender_OnEndSending", LogMessageType.AsynchronousSendingFinished, null, null, httpClientConnection.Remote, binaryLogWriter[LogCategory.LowLevelTransport] > 1 ? content : null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.DbgConnectionId, (int) httpWebResponse.ContentLength, null, null, null, "The content of the response received by the sender connection."); if (binaryLogWriter[LogCategory.Transport] > 1) inputStream = content; } BinaryReader binaryReader = new BinaryReader(inputStream); string serverUri; int sequenceNo; HttpPacketType httpPacketType; int remoteHostUniqueIdentifier; HttpMessageCoder.ReadResponseHeader(binaryReader, out serverUri, out sequenceNo, out httpPacketType, out remoteHostUniqueIdentifier); if (sequenceNo != httpClientConnection.SendSequenceNo) throw GenuineExceptions.Get_Receive_IncorrectData(); if (httpClientConnection.GenuineConnectionType == GenuineConnectionType.Persistent) httpClientConnection.Remote.UpdateUri(serverUri, remoteHostUniqueIdentifier); if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.Pool_Sender_OnEndSending", LogMessageType.LowLevelTransport_AsyncSendingCompleted, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Sender_ConnectionLevelSecurity, httpClientConnection.Sender_ConnectionLevelSecurity == null ? null : httpClientConnection.Sender_ConnectionLevelSecurity.Name, httpClientConnection.DbgConnectionId, (int) httpPacketType, sequenceNo, 0, null, null, null, null, "SENDER invocation completed. Type of the packet: {0}. Server Uri: {1}. Seq No: {2}", Enum.Format(typeof(HttpPacketType), httpPacketType, "g"), serverUri, sequenceNo); } if (httpPacketType == HttpPacketType.Desynchronization) { this.ConnectionFailed(httpClientConnection, true, GenuineExceptions.Get_Channel_Desynchronization(), false); return ; } if (httpPacketType == HttpPacketType.SenderError) { Exception deserializedException = null; try { var binaryFormatter = new BinaryFormatter(new RemotingSurrogateSelector(), new StreamingContext(StreamingContextStates.Other)).Safe(); deserializedException = binaryFormatter.Deserialize(inputStream) as Exception; } catch { } if (deserializedException != null) this.ConnectionFailed(httpClientConnection, true, GenuineExceptions.Get_Receive_ConnectionClosed(deserializedException.Message), false); else this.ConnectionFailed(httpClientConnection, true, GenuineExceptions.Get_Receive_ConnectionClosed("Remote host was not able to parse the request. Probably due to the security reasons."), false); return ; } // fetch and process messages this.LowLevel_ParseLabelledStream(inputStream, httpClientConnection.Sender_ReceiveBuffer, httpClientConnection, httpClientConnection.Sender_ConnectionLevelSecurity); } finally { if (inputStream != null) inputStream.Close(); httpWebResponse.Close(); // TODO: remove this if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Debugging] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Debugging, "HttpClientConnectionManager.Pool_Sender_OnEndSending", LogMessageType.DebuggingSuccess, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Sender_ConnectionLevelSecurity, null, httpClientConnection.DbgConnectionId, -1, -1, -1, null, null, null, null, "HttpClientConnectionManager.Pool_Sender_OnEndSending is completed."); } } GenuineThreadPool.QueueUserWorkItem(this._pool_Sender_OnEndSending_ContinueExchange, httpClientConnection, false); } private WaitCallback _pool_Sender_OnEndSending_ContinueExchange; /// <summary> /// This is the second part of the Pool_Sender_OnEndSending implementation being /// executed in the separate thread to prevent .NET Framework internal deadlock. /// </summary> /// <param name="httpClientConnectionAsObject">The connection.</param> private void Pool_Sender_OnEndSending_ContinueExchange(object httpClientConnectionAsObject) { Message message = null; HttpClientConnection httpClientConnection = (HttpClientConnection) httpClientConnectionAsObject; lock (httpClientConnection.SendingLock) { // analyze the queue message = httpClientConnection.MessageContainer.GetMessage(); if (message == null) { // release the lock httpClientConnection.IsSent = false; return ; } } Debug.Assert(httpClientConnection.IsSent == true); this.LowLevel_Sender_Send(message, httpClientConnection, httpClientConnection.OnEndSending, false); } /// <summary> /// Processes failed or closed connections. /// </summary> /// <param name="httpClientConnection">The connection.</param> /// <param name="sender">The type of the failed connection (P/Async).</param> /// <param name="exception">The exception.</param> /// <param name="tryToReestablish">True if it's a good idea to try to reestablish the connection.</param> public void ConnectionFailed(HttpClientConnection httpClientConnection, bool sender, Exception exception, bool tryToReestablish) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; try { if (tryToReestablish) tryToReestablish = ! ConnectionManager.IsExceptionCritical(exception as OperationException); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ConnectionFailed", LogMessageType.ConnectionFailed, exception, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Connection failure. Sender: {0}. Connection type: {1}. Try to reestablish: {2}.", sender.ToString(), Enum.GetName(typeof(GenuineConnectionType), httpClientConnection.GenuineConnectionType), tryToReestablish.ToString()); } using (new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) tryToReestablish = false; } lock (httpClientConnection.Remote.PersistentConnectionEstablishingLock) { if (! tryToReestablish || httpClientConnection._disposed) { using (new ReaderAutoLocker(this._disposeLock)) { this._persistent.Remove(httpClientConnection.Remote.Url); } // close the content if (httpClientConnection.SentContent != null) { httpClientConnection.SentContent.Close(); httpClientConnection.SentContent = null; } // release all resources this.ITransportContext.KnownHosts.ReleaseHostResources(httpClientConnection.Remote, exception); foreach (Message message in httpClientConnection.MessagesBeingSent) this.ITransportContext.IIncomingStreamHandler.DispatchException(message, exception); httpClientConnection.MessagesBeingSent.Clear(); httpClientConnection.Dispose(exception); httpClientConnection.SignalState(GenuineEventType.GeneralConnectionClosed, exception, null); if (exception is OperationException && ((OperationException) exception).OperationErrorMessage.ErrorIdentifier == "GenuineChannels.Exception.Receive.ServerHasBeenRestarted") httpClientConnection.SignalState(GenuineEventType.GeneralServerRestartDetected, exception, null); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ConnectionFailed", LogMessageType.ConnectionFailed, exception, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The connection has been completely terminated and removed from all collection. Sender: {0}. Connection type: {1}. Try to reestablish: {2}.", sender.ToString(), Enum.GetName(typeof(GenuineConnectionType), httpClientConnection.GenuineConnectionType), tryToReestablish.ToString()); } return ; } httpClientConnection.SignalState(GenuineEventType.GeneralConnectionReestablishing, exception, null); HttpClientConnection.ReconnectionContainer reconnectionContainer = sender ? httpClientConnection.SenderReconnectionLock : httpClientConnection.ListenerReconnectionLock; lock (reconnectionContainer.SyncLock) { if (GenuineUtility.IsTimeoutExpired(reconnectionContainer.ReconnectionStartedAt + GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]))) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ConnectionFailed", LogMessageType.ConnectionReestablishing, GenuineExceptions.Get_Debugging_GeneralWarning("Connection was not reestablished within the specified time boundaries."), null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The connection has not been reestablished within the specified time boundaries."); } // just close the connection using (new ReaderAutoLocker(this._disposeLock)) { this._persistent.Remove(httpClientConnection.Remote.Url); } this.ITransportContext.KnownHosts.ReleaseHostResources(httpClientConnection.Remote, exception); httpClientConnection.Dispose(exception); httpClientConnection.MessageContainer.Dispose(exception); // and fire a warning httpClientConnection.SignalState(GenuineEventType.GeneralConnectionClosed, exception, null); return ; } // resend the content or rerequest the previous content if (sender) { if (httpClientConnection.SentContent != null) this.LowLevel_Sender_Send(null, httpClientConnection, httpClientConnection.OnEndSending, true); } else this.LowLevel_InitiateListening(httpClientConnection, false); } } } catch(Exception ex) { if ( binaryLogWriter != null ) binaryLogWriter.WriteImplementationWarningEvent("HttpClientConnectionManager.ConnectionFailed", LogMessageType.Error, ex, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, "Unexpected exception occurred in the HttpClientConnectionManager.ConnectionFailed method. Most likely, something must be fixed."); } } /// <summary> /// Closes expired connections and sends ping via inactive connections. /// </summary> public void TimerCallback() { GenuineThreadPool.QueueUserWorkItem(_internal_TimerCallback, null, false); } private WaitCallback _internal_TimerCallback; /// <summary> /// Closes expired connections and sends ping via inactive connections. /// </summary> /// <param name="ignored">Ignored.</param> private void Internal_TimerCallback(object ignored) { int now = GenuineUtility.TickCount; int sendPingAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.PersistentConnectionSendPingAfterInactivity]); int closePersistentConnectionAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]); int closeInvocationConnectionsAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.CloseInvocationConnectionAfterInactivity]); int closeOneWayConnectionsAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.CloseOneWayConnectionAfterInactivity]); int reconnectionFailedAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]); // go through the pool and close all expired connections // persistent ArrayList connectionsBeingRemoved = new ArrayList(); DictionaryEntry[] entries = null; lock (this._persistent.SyncRoot) { entries = new DictionaryEntry[this._persistent.Count]; this._persistent.CopyTo(entries, 0); } foreach (DictionaryEntry dictionaryEntry in entries) { HttpClientConnection httpClientConnection = (HttpClientConnection) dictionaryEntry.Value; if (httpClientConnection._disposed) { connectionsBeingRemoved.Add(dictionaryEntry.Key); continue; } // retrieve reconnection information in a transaction bool isReconnectionStarted = false; int reconnectionStarted = 0; lock (httpClientConnection.ListenerReconnectionLock.SyncLock) { isReconnectionStarted |= httpClientConnection.ListenerReconnectionLock.IsReconnectionStarted; if (httpClientConnection.ListenerReconnectionLock.IsReconnectionStarted) reconnectionStarted = httpClientConnection.ListenerReconnectionLock.ReconnectionStartedAt; } lock (httpClientConnection.SenderReconnectionLock.SyncLock) { isReconnectionStarted |= httpClientConnection.SenderReconnectionLock.IsReconnectionStarted; if (httpClientConnection.SenderReconnectionLock.IsReconnectionStarted) reconnectionStarted = httpClientConnection.SenderReconnectionLock.ReconnectionStartedAt; } if (GenuineUtility.IsTimeoutExpired(httpClientConnection.LastMessageWasReceviedAt + closePersistentConnectionAfter, now)) { // if connection is not being reestablished, then it's necessary to close it // if it's being reestablished, it comes under reestablishing rules if ( ! isReconnectionStarted ) GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.PerformConnectionFailure), httpClientConnection, false); } if (GenuineUtility.IsTimeoutExpired(httpClientConnection.LastMessageWasSentAt + sendPingAfter, now)) GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.SendPing), httpClientConnection, false); if ( isReconnectionStarted && GenuineUtility.IsTimeoutExpired(reconnectionStarted + reconnectionFailedAfter, now)) GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.PerformConnectionFailure), httpClientConnection, false); } foreach (object key in connectionsBeingRemoved) this._persistent.Remove(key); } /// <summary> /// Closes the expired connection. /// </summary> /// <param name="httpClientConnectionAsObject">The connection to be closed.</param> private void PerformConnectionFailure(object httpClientConnectionAsObject) { this.ConnectionFailed(httpClientConnectionAsObject as HttpClientConnection, true, GenuineExceptions.Get_Channel_ConnectionClosedAfterTimeout(), false); } /// <summary> /// Sends a ping through the specified connection. /// </summary> /// <param name="httpClientConnectionAsObject">The connection.</param> private void SendPing(object httpClientConnectionAsObject) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; HttpClientConnection httpClientConnection = null; try { httpClientConnection = (HttpClientConnection) httpClientConnectionAsObject; // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.SendPing", LogMessageType.ConnectionPingSending, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Sending a ping."); } //Message message = new Message(this.ITransportContext, httpClientConnection.Remote, GenuineReceivingHandler.PING_MESSAGE_REPLYID, new TransportHeaders(), Stream.Null); Message message = new Message(this.ITransportContext, httpClientConnection.Remote, -1, new TransportHeaders(), Stream.Null); message.IsSynchronous = false; this.Send(message); } catch(Exception ex) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.SendPing", LogMessageType.ConnectionPingSending, ex, null, httpClientConnection == null ? null : httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection == null ? -1 : httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Exception occurred while sending a ping."); } } } #endregion #region -- Connection recovering ----------------------------------------------------------- /// <summary> /// Represents a failed HTTP request. /// </summary> private class FailedHttpRequest { /// <summary> /// The connection. /// </summary> public HttpClientConnection HttpClientConnection; /// <summary> /// The reason of failure. /// </summary> public Exception Exception; /// <summary> /// Represents a value indicating the type of the failed connection. /// </summary> public bool Sender; } /// <summary> /// Tries to reestablish the failed connection. /// </summary> /// <param name="failedHttpRequestAsObject">The failed request.</param> private void ReestablishFailedConnection(object failedHttpRequestAsObject) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; using(new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) return ; } FailedHttpRequest failedHttpRequest = (FailedHttpRequest) failedHttpRequestAsObject; HttpClientConnection httpClientConnection = failedHttpRequest.HttpClientConnection; HttpClientConnection.ReconnectionContainer reconnectionContainer = failedHttpRequest.Sender ? httpClientConnection.SenderReconnectionLock : httpClientConnection.ListenerReconnectionLock; // this variable is used to prevent from setting reconnectionContainer.IsReconnectionStarted to false // within a very short period of time bool closureClosed = false; try { Exception exception = failedHttpRequest.Exception; // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReestablishFailedConnection", LogMessageType.ConnectionReestablishing, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Reestablishing the {0} HTTP connection. System.Net.ServicePointManager.DefaultConnectionLimit = {1}.", failedHttpRequest.Sender ? "SENDER" : "LISTENER", System.Net.ServicePointManager.DefaultConnectionLimit); } int reconnectionMustBeFinishedBefore = GenuineUtility.GetTimeout((TimeSpan) httpClientConnection.ITransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]); for ( int i = 0; i < (int) httpClientConnection.ITransportContext.IParameterProvider[GenuineParameter.ReconnectionTries] && ! GenuineUtility.IsTimeoutExpired(reconnectionMustBeFinishedBefore) && ! httpClientConnection._disposed; i++ ) { Thread.Sleep((TimeSpan) httpClientConnection.ITransportContext.IParameterProvider[GenuineParameter.SleepBetweenReconnections]); using(new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) return ; } lock (reconnectionContainer.SyncLock) { reconnectionContainer.RequestFailed = false; } if (httpClientConnection._disposed) return ; try { // TODO: remove this // LOG: if ( binaryLogWriter != null ) { binaryLogWriter.WriteEvent(LogCategory.Debugging, "HttpClientConnectionManager.ReestablishFailedConnection", LogMessageType.DebuggingWarning, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Reestablishing the {0} attempt #{1}", failedHttpRequest.Sender ? "SENDER" : "LISTENER", i); } this.ConnectionFailed(httpClientConnection, failedHttpRequest.Sender, exception, true); lock (reconnectionContainer.SyncLock) { // TODO: remove this // LOG: if ( binaryLogWriter != null ) { binaryLogWriter.WriteEvent(LogCategory.Debugging, "HttpClientConnectionManager.ReestablishFailedConnection", LogMessageType.DebuggingWarning, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Reestablishing the {0} attempt N{1} RESULT: {2}", failedHttpRequest.Sender ? "SENDER" : "LISTENER", i, reconnectionContainer.RequestFailed ? "FAILURE" : "SUCCESS"); } if (reconnectionContainer.RequestFailed) continue; closureClosed = true; reconnectionContainer.IsReconnectionStarted = false; return; } } catch(Exception ex) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReestablishFailedConnection", LogMessageType.ConnectionReestablishing, ex, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Reestablishing attempt failed. Reestablishing the {0} HTTP connection will be continued. Try: {1}. Milliseconds left: {2}", failedHttpRequest.Sender ? "SENDER" : "LISTENER", i, GenuineUtility.CompareTickCounts(reconnectionMustBeFinishedBefore, GenuineUtility.TickCount)); } httpClientConnection.SignalState(GenuineEventType.GeneralConnectionReestablishing, ex, null); } } // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReestablishFailedConnection", LogMessageType.ConnectionReestablished, GenuineExceptions.Get_Debugging_GeneralWarning("Reestablishing failed."), null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Reestablishing the {0} HTTP connection has failed.", failedHttpRequest.Sender ? "SENDER" : "LISTENER"); } // connection can not be restored this.ConnectionFailed(httpClientConnection, failedHttpRequest.Sender, exception, false); } finally { if (! closureClosed) reconnectionContainer.IsReconnectionStarted = false; } } #endregion #region -- Low-level layer ----------------------------------------------------------------- /// <summary> /// Represents a value indicating the maximum time period of WebRequest initialization. /// </summary> private TimeSpan _webRequestInitiationTimeout; private int _httpAsynchronousRequestTimeout; /// <summary> /// Sends the message to the remote host through the sender connection. /// </summary> /// <param name="message">Message to be sent.</param> /// <param name="httpClientConnection">The connection.</param> /// <param name="asyncCallback">The callback to be called after the operation will be completed.</param> /// <param name="repeatSending">Whether to send the previous content again.</param> private void LowLevel_Sender_Send(Message message, HttpClientConnection httpClientConnection, AsyncCallback asyncCallback, bool repeatSending) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; // connection lock obtained, assemble the packet and send it try { if (! repeatSending) { httpClientConnection.SendSequenceNo ++; httpClientConnection.LastMessageWasSentAt = GenuineUtility.TickCount; httpClientConnection.SentContent = new GenuineChunkedStream(false); MessageCoder.FillInLabelledStream(message, httpClientConnection.MessageContainer, httpClientConnection.MessagesBeingSent, httpClientConnection.SentContent, httpClientConnection.Sender_SendBuffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Transport] > 0 ) { for ( int i = 0; i < httpClientConnection.MessagesBeingSent.Count; i++) { Message nextMessage = (Message) httpClientConnection.MessagesBeingSent[i]; binaryLogWriter.WriteEvent(LogCategory.Transport, "HttpClientConnectionManager.LowLevel_Sender_Send", LogMessageType.MessageIsSentAsynchronously, null, nextMessage, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Sender_ConnectionLevelSecurity, null, httpClientConnection.DbgConnectionId, httpClientConnection.SendSequenceNo, 0, 0, null, null, null, null, "The message will be sent in the SENDER stream N: {0}.", httpClientConnection.SendSequenceNo); } } // apply CLSSE if (httpClientConnection.Sender_ConnectionLevelSecurity != null) { GenuineChunkedStream encryptedContent = new GenuineChunkedStream(false); httpClientConnection.Sender_ConnectionLevelSecurity.Encrypt(httpClientConnection.SentContent, encryptedContent); httpClientConnection.SentContent = encryptedContent; } // prepare the final version of the content GenuineChunkedStream resultStream = new GenuineChunkedStream(false); BinaryWriter binaryWriter = new BinaryWriter(resultStream); HttpMessageCoder.WriteRequestHeader(binaryWriter, MessageCoder.PROTOCOL_VERSION, httpClientConnection.GenuineConnectionType, httpClientConnection.HostId, HttpPacketType.Usual, httpClientConnection.SendSequenceNo, httpClientConnection.ConnectionName, httpClientConnection.Remote.LocalHostUniqueIdentifier); if (httpClientConnection.SentContent.CanSeek) resultStream.WriteStream(httpClientConnection.SentContent); else GenuineUtility.CopyStreamToStream(httpClientConnection.SentContent, resultStream); httpClientConnection.SentContent = resultStream; } else { httpClientConnection.SentContent.Position = 0; } // try to send it httpClientConnection.Sender = httpClientConnection.InitializeRequest(true, httpClientConnection._keepalive); httpClientConnection.Sender.ContentLength = httpClientConnection.SentContent.Length; this.LowLevel_InitiateHttpWebRequest(httpClientConnection.Sender, httpClientConnection.SentContent, httpClientConnection.SenderClosed, true, asyncCallback, httpClientConnection); } catch(Exception ex) { // sending failed, rollback the entire operation // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_Sender_Send", LogMessageType.AsynchronousSendingFinished, ex, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Error occurred while sending a message to the remote host."); } this.StartReestablishingIfNecessary(httpClientConnection, ex, true); } } /// <summary> /// Initiates the HTTP request. /// </summary> /// <param name="httpWebRequest">The instance of the HttpWebRequest class.</param> /// <param name="inputStream">The input stream.</param> /// <param name="closed">The state event.</param> /// <param name="sender">Indicates whether the sender request is being sent.</param> /// <param name="asyncCallback">The callback.</param> /// <param name="dbgHttpClientConnection">The connection provided for debugging purposes.</param> private void LowLevel_InitiateHttpWebRequest(HttpWebRequest httpWebRequest, Stream inputStream, ManualResetEvent closed, bool sender, AsyncCallback asyncCallback, HttpClientConnection dbgHttpClientConnection) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; using(new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) throw OperationException.WrapException(this._disposeReason); } Stream requestStream = null; try { if (! closed.WaitOne(this._webRequestInitiationTimeout, false)) throw GenuineExceptions.Get_Processing_LogicError("[0] Deadlock or a heavy load."); closed.Reset(); requestStream = httpWebRequest.GetRequestStream(); if (binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.LowLevel_InitiateHttpWebRequest", LogMessageType.LowLevelTransport_AsyncSendingInitiating, null, null, dbgHttpClientConnection == null ? null : dbgHttpClientConnection.Remote, binaryLogWriter[LogCategory.LowLevelTransport] > 1 ? inputStream : null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, dbgHttpClientConnection == null ? -1 : dbgHttpClientConnection.DbgConnectionId, (int) inputStream.Length, null, null, null, "HTTP {0} Request is being sent. Size: {1}.", sender ? "SENDER" : "LISTENER", (int) inputStream.Length); } GenuineUtility.CopyStreamToStream(inputStream, requestStream, (int) inputStream.Length); this.IncreaseBytesSent((int) inputStream.Length); HttpWebRequestCop webRequestCop = new HttpWebRequestCop(httpWebRequest, asyncCallback, httpWebRequest, this._httpAsynchronousRequestTimeout); //httpWebRequest.BeginGetResponse(asyncCallback, httpWebRequest); } catch(Exception ex) { if (binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.LowLevel_InitiateHttpWebRequest", LogMessageType.LowLevelTransport_AsyncSendingInitiating, ex, null, dbgHttpClientConnection == null ? null : dbgHttpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, dbgHttpClientConnection == null ? -1 : dbgHttpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Exception occurred while initiating HTTP request."); } try { httpWebRequest.Abort(); } catch(Exception) { } throw; } finally { try { if (requestStream != null) requestStream.Close(); } catch(Exception ex) { // ignore & warning if (binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.LowLevel_InitiateHttpWebRequest", LogMessageType.LowLevelTransport_AsyncSendingInitiating, ex, null, dbgHttpClientConnection == null ? null : dbgHttpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, dbgHttpClientConnection == null ? -1 : dbgHttpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Can't close the stream!"); } } closed.Set(); } } /// <summary> /// Opens connection to the remote host. /// </summary> /// <param name="remote">The remote host.</param> /// <param name="genuineConnectionType">The type of the connection.</param> /// <param name="connectionName">The name of the connection.</param> /// <returns>The opened connection.</returns> private HttpClientConnection LowLevel_OpenConnection(HostInformation remote, GenuineConnectionType genuineConnectionType, string connectionName) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; using (new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) throw OperationException.WrapException(this._disposeReason); } // the time we should finish connection establishing before int timeout = GenuineUtility.GetTimeout((TimeSpan) this.ITransportContext.IParameterProvider[GenuineParameter.ConnectTimeout]); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.ConnectionEstablishing, null, null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "The connection is being established to \"{0}\".", remote == null ? "?" : remote.Url == null ? "?" : remote.Url); } // first - send the check request and start CLSSE HttpClientConnection httpClientConnection = new HttpClientConnection(this.ITransportContext, connectionName); httpClientConnection.Remote = remote; httpClientConnection.GenuineConnectionType = genuineConnectionType; httpClientConnection.Sender_ConnectionLevelSecurity = this.CreateConnectionLevelSecuritySession(genuineConnectionType); httpClientConnection.Listener_ConnectionLevelSecurity = this.CreateConnectionLevelSecuritySession(genuineConnectionType); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteConnectionParameterEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.ConnectionParameters, null, remote, this.ITransportContext.IParameterProvider, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.DbgConnectionId, "An HTTP connection is being established."); } // gather the output stream Stream senderInputClsseStream = Stream.Null; Stream listenerInputClsseStream = Stream.Null; Stream clsseStream = null; GenuineChunkedStream outputStream = null; bool resend = false; bool firstFailure = false; // CLSS establishing for ( int i = 0; ; i++ ) { bool noClsseToSend = true; if (! resend) { // build the content outputStream = new GenuineChunkedStream(false); BinaryWriter binaryWriter = new BinaryWriter(outputStream); HttpMessageCoder.WriteRequestHeader(binaryWriter, MessageCoder.PROTOCOL_VERSION, genuineConnectionType, httpClientConnection.HostId, i == 0 ? HttpPacketType.Establishing_ResetConnection : HttpPacketType.Establishing, ++httpClientConnection.SendSequenceNo, httpClientConnection.ConnectionName, remote.LocalHostUniqueIdentifier); // CLSSE info using (new GenuineChunkedStreamSizeLabel(outputStream)) { if (httpClientConnection.Sender_ConnectionLevelSecurity != null && ! httpClientConnection.Sender_ConnectionLevelSecurity.IsEstablished) { clsseStream = httpClientConnection.Sender_ConnectionLevelSecurity.EstablishSession(senderInputClsseStream, true); if (clsseStream != null) { noClsseToSend = false; GenuineUtility.CopyStreamToStream(clsseStream, outputStream); } } } // CLSSE info using (new GenuineChunkedStreamSizeLabel(outputStream)) { if (httpClientConnection.Listener_ConnectionLevelSecurity != null && ! httpClientConnection.Listener_ConnectionLevelSecurity.IsEstablished) { clsseStream = httpClientConnection.Listener_ConnectionLevelSecurity.EstablishSession(listenerInputClsseStream, true); if (clsseStream != null) { noClsseToSend = false; GenuineUtility.CopyStreamToStream(clsseStream, outputStream); } } } } else outputStream.Position = 0; // parse the response HttpWebRequest httpWebRequest = httpClientConnection.InitializeRequest(true, httpClientConnection._keepalive); int millisecondsRemain = GenuineUtility.CompareTickCounts(timeout, GenuineUtility.TickCount); if ( millisecondsRemain <= 0) throw GenuineExceptions.Get_Channel_ConnectionClosedAfterTimeout(); httpWebRequest.Timeout = millisecondsRemain; httpWebRequest.ContentLength = outputStream.Length; Stream requestStream = null; try { requestStream = httpWebRequest.GetRequestStream(); GenuineUtility.CopyStreamToStream(outputStream, requestStream, (int) outputStream.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse()) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { StringBuilder stringBuilderHeaders = new StringBuilder(1024); foreach (string headerName in httpWebResponse.Headers.Keys) stringBuilderHeaders.AppendFormat("{0}=\"{1}\"; ", headerName, httpWebResponse.Headers.Get(headerName)); binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.ConnectionEstablishing, null, null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The trial connection has been successfully completed. Content-Length: {0}; Content encoding: {1}; Content type: {2}; Protocol version: {3}; Respose uri: {4}; Status code: {5}; Status description: {6}; HTTP headers: {7}.", httpWebResponse.ContentLength, httpWebResponse.ContentEncoding, httpWebResponse.ContentType, httpWebResponse.ProtocolVersion, httpWebResponse.ResponseUri, httpWebResponse.StatusCode, httpWebResponse.StatusDescription, stringBuilderHeaders.ToString()); } using (Stream responseStream = httpWebResponse.GetResponseStream()) { BinaryReader binaryReader = new BinaryReader(responseStream); string serverUri; int sequenceNo; HttpPacketType httpPacketType; int remoteHostUniqueIdentifier; HttpMessageCoder.ReadResponseHeader(binaryReader, out serverUri, out sequenceNo, out httpPacketType, out remoteHostUniqueIdentifier); if ( httpPacketType != HttpPacketType.Establishing && httpPacketType != HttpPacketType.Establishing_ResetConnection ) throw GenuineExceptions.Get_Connect_CanNotConnectToRemoteHost(remote.ToString(), "Wrong response received from the remote host."); // check the restartion if either CLSS or the persistent connection is used if (genuineConnectionType == GenuineConnectionType.Persistent || httpClientConnection.Sender_ConnectionLevelSecurity != null) remote.UpdateUri(serverUri, remoteHostUniqueIdentifier); // the first SS int writtenSize = binaryReader.ReadInt32(); senderInputClsseStream = new GenuineChunkedStream(true); GenuineUtility.CopyStreamToStream(responseStream, senderInputClsseStream, writtenSize); writtenSize = binaryReader.ReadInt32(); listenerInputClsseStream = new GenuineChunkedStream(true); GenuineUtility.CopyStreamToStream(responseStream, listenerInputClsseStream, writtenSize); } } outputStream.Close(); } catch(Exception ex) { if (firstFailure) throw; // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.ConnectionEstablishing, ex, null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "Exception occurred while establishing the connection to \"{0}\". The connection establishing will be continued.", remote == null ? "?" : remote.Url == null ? "?" : remote.Url); } // try to recover resend = true; continue; } finally { if (requestStream != null) requestStream.Close(); } firstFailure = false; resend = false; if (httpClientConnection.Sender_ConnectionLevelSecurity != null && ! httpClientConnection.Sender_ConnectionLevelSecurity.IsEstablished) continue; if (httpClientConnection.Listener_ConnectionLevelSecurity != null && ! httpClientConnection.Listener_ConnectionLevelSecurity.IsEstablished) continue; if (! noClsseToSend) continue; break; } // start listener if it's a persistent connection remote.PhysicalAddress = remote.Url; // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.HostInformation] > 0 ) { binaryLogWriter.WriteHostInformationEvent("HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.HostInformationCreated, null, remote, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Sender_ConnectionLevelSecurity, httpClientConnection.Sender_ConnectionLevelSecurity == null ? null : httpClientConnection.Sender_ConnectionLevelSecurity.Name, httpClientConnection.DbgConnectionId, "HostInformation is ready for actions."); } // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.ConnectionEstablished, null, null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Sender_ConnectionLevelSecurity, httpClientConnection.Sender_ConnectionLevelSecurity == null ? null : httpClientConnection.Sender_ConnectionLevelSecurity.Name, httpClientConnection.DbgConnectionId, (int) genuineConnectionType, 0, 0, this.GetType().Name, remote.Url, remote.Url, null, "The connection to the remote host is established."); } if (genuineConnectionType == GenuineConnectionType.Persistent) this.LowLevel_InitiateListening(httpClientConnection, true); return httpClientConnection; } /// <summary> /// Reads messages from the stream and processes them. /// </summary> /// <param name="stream">The source stream.</param> /// <param name="intermediateBuffer">The intermediate buffer.</param> /// <param name="httpClientConnection">The connection.</param> /// <param name="connectionLevelSecuritySession">The Connection Level Security Session that decrypted this message.</param> public void LowLevel_ParseLabelledStream(Stream stream, byte[] intermediateBuffer, HttpClientConnection httpClientConnection, SecuritySession connectionLevelSecuritySession) { bool directExecution = httpClientConnection.GenuineConnectionType == GenuineConnectionType.Invocation; BinaryReader binaryReader = new BinaryReader(stream); while ( binaryReader.ReadByte() == 0 ) { using (LabelledStream labelledStream = new LabelledStream(this.ITransportContext, stream, intermediateBuffer)) { if (directExecution) this.ITransportContext.IIncomingStreamHandler.HandleMessage(labelledStream, httpClientConnection.Remote, httpClientConnection.GenuineConnectionType, httpClientConnection.ConnectionName, httpClientConnection.DbgConnectionId, true, null, connectionLevelSecuritySession, null); else { GenuineChunkedStream receivedContent = new GenuineChunkedStream(true); GenuineUtility.CopyStreamToStream(labelledStream, receivedContent); this.ITransportContext.IIncomingStreamHandler.HandleMessage(receivedContent, httpClientConnection.Remote, httpClientConnection.GenuineConnectionType, httpClientConnection.ConnectionName, httpClientConnection.DbgConnectionId, false, null, connectionLevelSecuritySession, null); } } } } #endregion #region -- P/listener management ----------------------------------------------------------- /// <summary> /// Initiates the listening request. /// </summary> /// <param name="httpClientConnection">The connection.</param> /// <param name="requestNextPacket">Whether to request the next packet.</param> private void LowLevel_InitiateListening(HttpClientConnection httpClientConnection, bool requestNextPacket) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; try { #if DEBUG Debug.Assert(httpClientConnection.GenuineConnectionType == GenuineConnectionType.Persistent); #endif if (requestNextPacket) httpClientConnection.ListenerSequenceNo ++; // write the request header using (GenuineChunkedStream listenerStream = new GenuineChunkedStream(false)) { BinaryWriter binaryWriter = new BinaryWriter(listenerStream); HttpMessageCoder.WriteRequestHeader(binaryWriter, MessageCoder.PROTOCOL_VERSION, httpClientConnection.GenuineConnectionType, httpClientConnection.HostId, HttpPacketType.Listening, httpClientConnection.ListenerSequenceNo, httpClientConnection.ConnectionName, httpClientConnection.Remote.LocalHostUniqueIdentifier); // start the request httpClientConnection.Listener = httpClientConnection.InitializeRequest(false, httpClientConnection._keepalive); httpClientConnection.Listener.ContentLength = listenerStream.Length; this.LowLevel_InitiateHttpWebRequest(httpClientConnection.Listener, listenerStream, httpClientConnection.ListenerClosed, false, httpClientConnection.OnEndReceiving, httpClientConnection); } } catch(Exception ex) { // It's necessary to schedule connection reestablishing // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_InitiateListening", LogMessageType.ConnectionFailed, ex, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The LISTENER request Seq No={0} has failed. The connection will be reestablished, if possible.", httpClientConnection.ListenerSequenceNo); } this.StartReestablishingIfNecessary(httpClientConnection, ex, false); } } /// <summary> /// Finishes sending a message through the connection. /// </summary> /// <param name="httpClientConnection">The connection.</param> /// <param name="httpWebResponse">The received response.</param> public void Listener_OnEndReceiving(HttpClientConnection httpClientConnection, HttpWebResponse httpWebResponse) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; Stream inputStream = null; try { #if DEBUG Debug.Assert(httpClientConnection.GenuineConnectionType == GenuineConnectionType.Persistent); #endif httpClientConnection.Remote.Renew(this._hostRenewingSpan, false); httpClientConnection.LastMessageWasReceviedAt = GenuineUtility.TickCount; httpClientConnection.SignalState(GenuineEventType.GeneralConnectionEstablished, null, null); // process the content inputStream = httpWebResponse.GetResponseStream(); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { bool writeContent = binaryLogWriter[LogCategory.LowLevelTransport] > 1; GenuineChunkedStream content = null; if (writeContent) { content = new GenuineChunkedStream(false); GenuineUtility.CopyStreamToStream(inputStream, content, (int) httpWebResponse.ContentLength); } binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.Listener_OnEndReceiving", LogMessageType.LowLevelTransport_AsyncReceivingCompleted, null, null, httpClientConnection.Remote, writeContent ? content : null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.DbgConnectionId, (int) httpWebResponse.ContentLength, null, null, null, "The content has been received."); if (writeContent) inputStream = content; } if (httpClientConnection.Listener_ConnectionLevelSecurity != null) inputStream = httpClientConnection.Listener_ConnectionLevelSecurity.Decrypt(inputStream); BinaryReader binaryReader = new BinaryReader(inputStream); string serverUri; int sequenceNo; HttpPacketType httpPacketType; int remoteHostUniqueIdentifier; HttpMessageCoder.ReadResponseHeader(binaryReader, out serverUri, out sequenceNo, out httpPacketType, out remoteHostUniqueIdentifier); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.Listener_OnEndReceiving", LogMessageType.ReceivingFinished, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Listener_ConnectionLevelSecurity, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "A response to the listener request has been received. Server uri: {0}. Sequence no: {1}. Packet type: {2}. Content-encoding: {3}. Content-length: {4}. Protocol version: {5}. Response uri: \"{6}\". Server: \"{7}\". Status code: {8}. Status description: \"{9}\".", serverUri, sequenceNo, Enum.Format(typeof(HttpPacketType), httpPacketType, "g"), httpWebResponse.ContentEncoding, httpWebResponse.ContentLength, httpWebResponse.ProtocolVersion, httpWebResponse.ResponseUri, httpWebResponse.Server, httpWebResponse.StatusCode, httpWebResponse.StatusDescription); } if (httpPacketType == HttpPacketType.Desynchronization) throw GenuineExceptions.Get_Channel_Desynchronization(); if (sequenceNo != httpClientConnection.ListenerSequenceNo) throw GenuineExceptions.Get_Processing_LogicError( string.Format("Impossible situation. The request stream number: {0}. The received stream number: {1}.", httpClientConnection.ListenerSequenceNo, sequenceNo) ); if (httpClientConnection.GenuineConnectionType == GenuineConnectionType.Persistent) httpClientConnection.Remote.UpdateUri(serverUri, remoteHostUniqueIdentifier); // if the remote host has asked to terminate a connection if (httpPacketType == HttpPacketType.ClosedManually || httpPacketType == HttpPacketType.Desynchronization) throw GenuineExceptions.Get_Receive_ConnectionClosed(); // fetch and process messages if (httpPacketType != HttpPacketType.ListenerTimedOut) this.LowLevel_ParseLabelledStream(inputStream, httpClientConnection.Listener_ReceiveBuffer, httpClientConnection, httpClientConnection.Listener_ConnectionLevelSecurity); GenuineUtility.CopyStreamToStream(inputStream, Stream.Null); } catch(Exception ex) { this.ConnectionFailed(httpClientConnection, false, ex, true); return ; } finally { if (inputStream != null) inputStream.Close(); httpWebResponse.Close(); } GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.Listener_OnEndReceiving_ContinueExchange), httpClientConnection, false); } private WaitCallback _listener_OnEndReceiving_ContinueExchange; /// <summary> /// The second part of the Listener_OnEndReceiving member implementation which is executed /// in the separate thread to avoid internal .NET Framework deadlock. /// </summary> /// <param name="httpClientConnectionAsObject">The connection represented as a reference to an instance of the Object class.</param> private void Listener_OnEndReceiving_ContinueExchange(object httpClientConnectionAsObject) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; HttpClientConnection httpClientConnection = (HttpClientConnection) httpClientConnectionAsObject; this.LowLevel_InitiateListening(httpClientConnection, true); } #endregion #region -- Listening ----------------------------------------------------------------------- /// <summary> /// Starts listening to the specified end point and accepting incoming connections. /// </summary> /// <param name="endPoint">The end point.</param> public override void StartListening(object endPoint) { throw new NotSupportedException(); } /// <summary> /// Stops listening to the specified end point. Does not close any connections. /// </summary> /// <param name="endPoint">The end point</param> public override void StopListening(object endPoint) { throw new NotSupportedException(); } #endregion #region -- Resource releasing -------------------------------------------------------------- /// <summary> /// Closes the specified connections to the remote host and releases acquired resources. /// </summary> /// <param name="hostInformation">Host information.</param> /// <param name="genuineConnectionType">What kind of connections will be affected by this operation.</param> /// <param name="reason">Reason of resource releasing.</param> public override void ReleaseConnections(HostInformation hostInformation, GenuineConnectionType genuineConnectionType, Exception reason) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; HttpClientConnection httpClientConnection = null; ArrayList connectionsToClose = new ArrayList(); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReleaseConnections", LogMessageType.ReleaseConnections, reason, null, hostInformation, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, Enum.Format(typeof(GenuineConnectionType), genuineConnectionType, "g"), null, null, null, "\"{0}\" connections will be terminated.", Enum.Format(typeof(GenuineConnectionType), genuineConnectionType, "g"), null); } // TODO: 2.5.3. fix (deadlock by design), will be completely fixed in 3.0 // using (new WriterAutoLocker(this._disposeLock)) { // persistent if ( (genuineConnectionType & GenuineConnectionType.Persistent) != 0 ) lock (this._persistent.SyncRoot) { foreach (DictionaryEntry entry in this._persistent) { httpClientConnection = (HttpClientConnection) entry.Value; if (hostInformation != null && httpClientConnection.Remote != hostInformation) continue; connectionsToClose.Add(httpClientConnection); } } // close connections foreach (HttpClientConnection nextHttpClientConnection in connectionsToClose) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReleaseConnections", LogMessageType.ConnectionShuttingDown, reason, null, nextHttpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, nextHttpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The connection is being shut down manually."); } this.ConnectionFailed(nextHttpClientConnection, true, GenuineExceptions.Get_Channel_ConnectionShutDown(reason), false); if (nextHttpClientConnection.GenuineConnectionType == GenuineConnectionType.Persistent) { nextHttpClientConnection.SignalState(GenuineEventType.GeneralConnectionClosed, reason, null); } } } } /// <summary> /// Returns names of connections opened to the specified destination. /// Not all Connection Manager support this member. /// </summary> /// <param name="uri">The URI or URL of the remote host.</param> /// <returns>Names of connections opened to the specified destination.</returns> public override string[] GetConnectionNames(string uri) { lock (this._persistent.SyncRoot) { if (this._persistent.ContainsKey(uri)) { string[] result = new string[1]; result[0] = uri; return result; } } return null; } /// <summary> /// Releases all resources. /// </summary> /// <param name="reason">The reason of disposing.</param> public override void InternalDispose(Exception reason) { this.ReleaseConnections(null, GenuineConnectionType.All, reason); } #endregion #region -- Reestablishing ------------------------------------------------------------------ /// <summary> /// Starts reestablishing if it has not been started. /// </summary> /// <param name="httpClientConnection">The HTTP client connection.</param> /// <param name="exception">The reason of the connection failure.</param> /// <param name="sender">A flag indicating the role of the connection.</param> public void StartReestablishingIfNecessary(HttpClientConnection httpClientConnection, Exception exception, bool sender) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; HttpClientConnection.ReconnectionContainer reconnectionContainer = sender ? httpClientConnection.SenderReconnectionLock : httpClientConnection.ListenerReconnectionLock; lock (reconnectionContainer.SyncLock) { if (! reconnectionContainer.IsReconnectionStarted) { // LOG: if ( binaryLogWriter != null ) { binaryLogWriter.WriteEvent(LogCategory.Debugging, "HttpClientConnectionManager.StartReestablishingIfNecessary", LogMessageType.ConnectionReestablishing, exception, null, null, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "Reconnection is being started."); } reconnectionContainer.IsReconnectionStarted = true; reconnectionContainer.ReconnectionStartedAt = GenuineUtility.TickCount; FailedHttpRequest failedHttpRequest = new FailedHttpRequest(); failedHttpRequest.HttpClientConnection = httpClientConnection; failedHttpRequest.Exception = exception; failedHttpRequest.Sender = sender; GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.ReestablishFailedConnection), failedHttpRequest, true); } else { // LOG: if ( binaryLogWriter != null ) { binaryLogWriter.WriteEvent(LogCategory.Debugging, "HttpClientConnectionManager.StartReestablishingIfNecessary", LogMessageType.ConnectionReestablishing, exception, null, null, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "Reconnection is already in progress."); } reconnectionContainer.RequestFailed = true; } } } /// <summary> /// Resets the reestablishing flag. /// </summary> /// <param name="httpClientConnection">The HTTP client connection.</param> /// <param name="sender">A flag indicating the role of the connection.</param> public void ReestablishingCompleted(HttpClientConnection httpClientConnection, bool sender) { HttpClientConnection.ReconnectionContainer reconnectionContainer = sender ? httpClientConnection.SenderReconnectionLock : httpClientConnection.ListenerReconnectionLock; reconnectionContainer.IsReconnectionStarted = false; } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="SqlInt16.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">junfang</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ //************************************************************************** // @File: SqlInt16.cs // // Create by: JunFang // // Purpose: Implementation of SqlInt16 which is equivalent to // data type "smallint" in SQL Server // // Notes: // // History: // // 11/1/99 JunFang Created. // // @EndHeader@ //************************************************************************** using System; using System.Data.Common; using System.Runtime.InteropServices; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Data.SqlTypes { /// <devdoc> /// <para> /// Represents a 16-bit signed integer to be stored in /// or retrieved from a database. /// </para> /// </devdoc> [Serializable] [StructLayout(LayoutKind.Sequential)] [XmlSchemaProvider("GetXsdType")] public struct SqlInt16 : INullable, IComparable, IXmlSerializable { private bool m_fNotNull; // false if null private short m_value; private static readonly int O_MASKI2 = ~0x00007fff; // constructor // construct a Null private SqlInt16(bool fNull) { m_fNotNull = false; m_value = 0; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SqlInt16(short value) { m_value = value; m_fNotNull = true; } // INullable /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsNull { get { return !m_fNotNull;} } // property: Value /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public short Value { get { if (m_fNotNull) return m_value; else throw new SqlNullValueException(); } } // Implicit conversion from short to SqlInt16 /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static implicit operator SqlInt16(short x) { return new SqlInt16(x); } // Explicit conversion from SqlInt16 to short. Throw exception if x is Null. /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator short(SqlInt16 x) { return x.Value; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override String ToString() { return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 Parse(String s) { if (s == SQLResource.NullString) return SqlInt16.Null; else return new SqlInt16(Int16.Parse(s, (IFormatProvider)null)); } // Unary operators /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 operator -(SqlInt16 x) { return x.IsNull ? Null : new SqlInt16((short)-x.m_value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 operator ~(SqlInt16 x) { return x.IsNull ? Null : new SqlInt16((short)~x.m_value); } // Binary operators // Arithmetic operators /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 operator +(SqlInt16 x, SqlInt16 y) { if (x.IsNull || y.IsNull) return Null; int iResult = (int)x.m_value + (int)y.m_value; if ((((iResult >> 15) ^ (iResult >> 16)) & 1) != 0) // Bit 15 != bit 16 throw new OverflowException(SQLResource.ArithOverflowMessage); else return new SqlInt16((short)iResult); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 operator -(SqlInt16 x, SqlInt16 y) { if (x.IsNull || y.IsNull) return Null; int iResult = (int)x.m_value - (int)y.m_value; if ((((iResult >> 15) ^ (iResult >> 16)) & 1) != 0) // Bit 15 != bit 16 throw new OverflowException(SQLResource.ArithOverflowMessage); else return new SqlInt16((short)iResult); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 operator *(SqlInt16 x, SqlInt16 y) { if (x.IsNull || y.IsNull) return Null; int iResult = (int)x.m_value * (int)y.m_value; int iTemp = iResult & O_MASKI2; if (iTemp != 0 && iTemp != O_MASKI2) throw new OverflowException(SQLResource.ArithOverflowMessage); else return new SqlInt16((short)iResult); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 operator /(SqlInt16 x, SqlInt16 y) { if (x.IsNull || y.IsNull) return Null; if (y.m_value != 0) { if ((x.m_value == Int16.MinValue) && (y.m_value == -1)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlInt16((short)(x.m_value / y.m_value)); } else throw new DivideByZeroException(SQLResource.DivideByZeroMessage); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 operator %(SqlInt16 x, SqlInt16 y) { if (x.IsNull || y.IsNull) return Null; if (y.m_value != 0) { if ((x.m_value == Int16.MinValue) && (y.m_value == -1)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlInt16((short)(x.m_value % y.m_value)); } else throw new DivideByZeroException(SQLResource.DivideByZeroMessage); } // Bitwise operators /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 operator &(SqlInt16 x, SqlInt16 y) { return(x.IsNull || y.IsNull) ? Null : new SqlInt16((short)(x.m_value & y.m_value)); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 operator |(SqlInt16 x, SqlInt16 y) { return(x.IsNull || y.IsNull) ? Null : new SqlInt16((short)((ushort)x.m_value | (ushort)y.m_value)); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlInt16 operator ^(SqlInt16 x, SqlInt16 y) { return(x.IsNull || y.IsNull) ? Null : new SqlInt16((short)(x.m_value ^ y.m_value)); } // Implicit conversions // Implicit conversion from SqlBoolean to SqlInt16 /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlInt16(SqlBoolean x) { return x.IsNull ? Null : new SqlInt16((short)(x.ByteValue)); } // Implicit conversion from SqlByte to SqlInt16 /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static implicit operator SqlInt16(SqlByte x) { return x.IsNull ? Null : new SqlInt16((short)(x.Value)); } // Explicit conversions // Explicit conversion from SqlInt32 to SqlInt16 /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlInt16(SqlInt32 x) { if (x.IsNull) return Null; int value = x.Value; if (value > (int)Int16.MaxValue || value < (int)Int16.MinValue) throw new OverflowException(SQLResource.ArithOverflowMessage); else return new SqlInt16((short)value); } // Explicit conversion from SqlInt64 to SqlInt16 /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlInt16(SqlInt64 x) { if (x.IsNull) return Null; long value = x.Value; if (value > (long)Int16.MaxValue || value < (long)Int16.MinValue) throw new OverflowException(SQLResource.ArithOverflowMessage); else return new SqlInt16((short)value); } // Explicit conversion from SqlSingle to SqlInt16 /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlInt16(SqlSingle x) { if (x.IsNull) return Null; float value = x.Value; if (value < (float)Int16.MinValue || value > (float)Int16.MaxValue) throw new OverflowException(SQLResource.ArithOverflowMessage); else return new SqlInt16((short)value); } // Explicit conversion from SqlDouble to SqlInt16 /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlInt16(SqlDouble x) { if (x.IsNull) return Null; double value = x.Value; if (value < (double)Int16.MinValue || value > (double)Int16.MaxValue) throw new OverflowException(SQLResource.ArithOverflowMessage); else return new SqlInt16((short)value); } // Explicit conversion from SqlMoney to SqlInt16 /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlInt16(SqlMoney x) { return x.IsNull ? Null : new SqlInt16(checked((short)x.ToInt32())); } // Explicit conversion from SqlDecimal to SqlInt16 /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlInt16(SqlDecimal x) { return(SqlInt16)(SqlInt32)x; } // Explicit conversion from SqlString to SqlInt16 /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlInt16(SqlString x) { return x.IsNull ? Null : new SqlInt16(Int16.Parse(x.Value, (IFormatProvider)null)); } // Overloading comparison operators /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator==(SqlInt16 x, SqlInt16 y) { return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value == y.m_value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator!=(SqlInt16 x, SqlInt16 y) { return ! (x == y); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator<(SqlInt16 x, SqlInt16 y) { return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value < y.m_value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator>(SqlInt16 x, SqlInt16 y) { return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value > y.m_value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator<=(SqlInt16 x, SqlInt16 y) { return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value <= y.m_value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator>=(SqlInt16 x, SqlInt16 y) { return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value >= y.m_value); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator ~ public static SqlInt16 OnesComplement(SqlInt16 x) { return ~x; } // Alternative method for operator + public static SqlInt16 Add(SqlInt16 x, SqlInt16 y) { return x + y; } // Alternative method for operator - public static SqlInt16 Subtract(SqlInt16 x, SqlInt16 y) { return x - y; } // Alternative method for operator * public static SqlInt16 Multiply(SqlInt16 x, SqlInt16 y) { return x * y; } // Alternative method for operator / public static SqlInt16 Divide(SqlInt16 x, SqlInt16 y) { return x / y; } // Alternative method for operator % public static SqlInt16 Mod(SqlInt16 x, SqlInt16 y) { return x % y; } public static SqlInt16 Modulus(SqlInt16 x, SqlInt16 y) { return x % y; } // Alternative method for operator & public static SqlInt16 BitwiseAnd(SqlInt16 x, SqlInt16 y) { return x & y; } // Alternative method for operator | public static SqlInt16 BitwiseOr(SqlInt16 x, SqlInt16 y) { return x | y; } // Alternative method for operator ^ public static SqlInt16 Xor(SqlInt16 x, SqlInt16 y) { return x ^ y; } // Alternative method for operator == public static SqlBoolean Equals(SqlInt16 x, SqlInt16 y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlInt16 x, SqlInt16 y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlInt16 x, SqlInt16 y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlInt16 x, SqlInt16 y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlInt16 x, SqlInt16 y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlInt16 x, SqlInt16 y) { return (x >= y); } // Alternative method for conversions. public SqlBoolean ToSqlBoolean() { return (SqlBoolean)this; } public SqlByte ToSqlByte() { return (SqlByte)this; } public SqlDouble ToSqlDouble() { return (SqlDouble)this; } public SqlInt32 ToSqlInt32() { return (SqlInt32)this; } public SqlInt64 ToSqlInt64() { return (SqlInt64)this; } public SqlMoney ToSqlMoney() { return (SqlMoney)this; } public SqlDecimal ToSqlDecimal() { return (SqlDecimal)this; } public SqlSingle ToSqlSingle() { return (SqlSingle)this; } public SqlString ToSqlString() { return (SqlString)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int CompareTo(Object value) { if (value is SqlInt16) { SqlInt16 i = (SqlInt16)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlInt16)); } public int CompareTo(SqlInt16 value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override bool Equals(Object value) { if (!(value is SqlInt16)) { return false; } SqlInt16 i = (SqlInt16)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override int GetHashCode() { return IsNull ? 0 : Value.GetHashCode(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> XmlSchema IXmlSerializable.GetSchema() { return null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> void IXmlSerializable.ReadXml(XmlReader reader) { string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // VSTFDevDiv# 479603 - SqlTypes read null value infinitely and never read the next value. Fix - Read the next value. reader.ReadElementString(); m_fNotNull = false; } else { m_value = XmlConvert.ToInt16(reader.ReadElementString()); m_fNotNull = true; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { writer.WriteString(XmlConvert.ToString(m_value)); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("short", XmlSchema.Namespace); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly SqlInt16 Null = new SqlInt16(true); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly SqlInt16 Zero = new SqlInt16(0); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly SqlInt16 MinValue = new SqlInt16(Int16.MinValue); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly SqlInt16 MaxValue = new SqlInt16(Int16.MaxValue); } // SqlInt16 } // namespace System.Data.SqlTypes
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Kms.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedEkmServiceClientSnippets { /// <summary>Snippet for ListEkmConnections</summary> public void ListEkmConnectionsRequestObject() { // Snippet: ListEkmConnections(ListEkmConnectionsRequest, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) ListEkmConnectionsRequest request = new ListEkmConnectionsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Filter = "", OrderBy = "", }; // Make the request PagedEnumerable<ListEkmConnectionsResponse, EkmConnection> response = ekmServiceClient.ListEkmConnections(request); // Iterate over all response items, lazily performing RPCs as required foreach (EkmConnection item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListEkmConnectionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (EkmConnection item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<EkmConnection> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (EkmConnection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListEkmConnectionsAsync</summary> public async Task ListEkmConnectionsRequestObjectAsync() { // Snippet: ListEkmConnectionsAsync(ListEkmConnectionsRequest, CallSettings) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) ListEkmConnectionsRequest request = new ListEkmConnectionsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Filter = "", OrderBy = "", }; // Make the request PagedAsyncEnumerable<ListEkmConnectionsResponse, EkmConnection> response = ekmServiceClient.ListEkmConnectionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((EkmConnection item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListEkmConnectionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (EkmConnection item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<EkmConnection> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (EkmConnection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListEkmConnections</summary> public void ListEkmConnections() { // Snippet: ListEkmConnections(string, string, int?, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListEkmConnectionsResponse, EkmConnection> response = ekmServiceClient.ListEkmConnections(parent); // Iterate over all response items, lazily performing RPCs as required foreach (EkmConnection item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListEkmConnectionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (EkmConnection item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<EkmConnection> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (EkmConnection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListEkmConnectionsAsync</summary> public async Task ListEkmConnectionsAsync() { // Snippet: ListEkmConnectionsAsync(string, string, int?, CallSettings) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListEkmConnectionsResponse, EkmConnection> response = ekmServiceClient.ListEkmConnectionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((EkmConnection item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListEkmConnectionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (EkmConnection item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<EkmConnection> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (EkmConnection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListEkmConnections</summary> public void ListEkmConnectionsResourceNames() { // Snippet: ListEkmConnections(LocationName, string, int?, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListEkmConnectionsResponse, EkmConnection> response = ekmServiceClient.ListEkmConnections(parent); // Iterate over all response items, lazily performing RPCs as required foreach (EkmConnection item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListEkmConnectionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (EkmConnection item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<EkmConnection> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (EkmConnection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListEkmConnectionsAsync</summary> public async Task ListEkmConnectionsResourceNamesAsync() { // Snippet: ListEkmConnectionsAsync(LocationName, string, int?, CallSettings) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListEkmConnectionsResponse, EkmConnection> response = ekmServiceClient.ListEkmConnectionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((EkmConnection item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListEkmConnectionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (EkmConnection item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<EkmConnection> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (EkmConnection item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetEkmConnection</summary> public void GetEkmConnectionRequestObject() { // Snippet: GetEkmConnection(GetEkmConnectionRequest, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) GetEkmConnectionRequest request = new GetEkmConnectionRequest { EkmConnectionName = EkmConnectionName.FromProjectLocationEkmConnection("[PROJECT]", "[LOCATION]", "[EKM_CONNECTION]"), }; // Make the request EkmConnection response = ekmServiceClient.GetEkmConnection(request); // End snippet } /// <summary>Snippet for GetEkmConnectionAsync</summary> public async Task GetEkmConnectionRequestObjectAsync() { // Snippet: GetEkmConnectionAsync(GetEkmConnectionRequest, CallSettings) // Additional: GetEkmConnectionAsync(GetEkmConnectionRequest, CancellationToken) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) GetEkmConnectionRequest request = new GetEkmConnectionRequest { EkmConnectionName = EkmConnectionName.FromProjectLocationEkmConnection("[PROJECT]", "[LOCATION]", "[EKM_CONNECTION]"), }; // Make the request EkmConnection response = await ekmServiceClient.GetEkmConnectionAsync(request); // End snippet } /// <summary>Snippet for GetEkmConnection</summary> public void GetEkmConnection() { // Snippet: GetEkmConnection(string, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/ekmConnections/[EKM_CONNECTION]"; // Make the request EkmConnection response = ekmServiceClient.GetEkmConnection(name); // End snippet } /// <summary>Snippet for GetEkmConnectionAsync</summary> public async Task GetEkmConnectionAsync() { // Snippet: GetEkmConnectionAsync(string, CallSettings) // Additional: GetEkmConnectionAsync(string, CancellationToken) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/ekmConnections/[EKM_CONNECTION]"; // Make the request EkmConnection response = await ekmServiceClient.GetEkmConnectionAsync(name); // End snippet } /// <summary>Snippet for GetEkmConnection</summary> public void GetEkmConnectionResourceNames() { // Snippet: GetEkmConnection(EkmConnectionName, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) EkmConnectionName name = EkmConnectionName.FromProjectLocationEkmConnection("[PROJECT]", "[LOCATION]", "[EKM_CONNECTION]"); // Make the request EkmConnection response = ekmServiceClient.GetEkmConnection(name); // End snippet } /// <summary>Snippet for GetEkmConnectionAsync</summary> public async Task GetEkmConnectionResourceNamesAsync() { // Snippet: GetEkmConnectionAsync(EkmConnectionName, CallSettings) // Additional: GetEkmConnectionAsync(EkmConnectionName, CancellationToken) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) EkmConnectionName name = EkmConnectionName.FromProjectLocationEkmConnection("[PROJECT]", "[LOCATION]", "[EKM_CONNECTION]"); // Make the request EkmConnection response = await ekmServiceClient.GetEkmConnectionAsync(name); // End snippet } /// <summary>Snippet for CreateEkmConnection</summary> public void CreateEkmConnectionRequestObject() { // Snippet: CreateEkmConnection(CreateEkmConnectionRequest, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) CreateEkmConnectionRequest request = new CreateEkmConnectionRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), EkmConnectionId = "", EkmConnection = new EkmConnection(), }; // Make the request EkmConnection response = ekmServiceClient.CreateEkmConnection(request); // End snippet } /// <summary>Snippet for CreateEkmConnectionAsync</summary> public async Task CreateEkmConnectionRequestObjectAsync() { // Snippet: CreateEkmConnectionAsync(CreateEkmConnectionRequest, CallSettings) // Additional: CreateEkmConnectionAsync(CreateEkmConnectionRequest, CancellationToken) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) CreateEkmConnectionRequest request = new CreateEkmConnectionRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), EkmConnectionId = "", EkmConnection = new EkmConnection(), }; // Make the request EkmConnection response = await ekmServiceClient.CreateEkmConnectionAsync(request); // End snippet } /// <summary>Snippet for CreateEkmConnection</summary> public void CreateEkmConnection() { // Snippet: CreateEkmConnection(string, string, EkmConnection, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; string ekmConnectionId = ""; EkmConnection ekmConnection = new EkmConnection(); // Make the request EkmConnection response = ekmServiceClient.CreateEkmConnection(parent, ekmConnectionId, ekmConnection); // End snippet } /// <summary>Snippet for CreateEkmConnectionAsync</summary> public async Task CreateEkmConnectionAsync() { // Snippet: CreateEkmConnectionAsync(string, string, EkmConnection, CallSettings) // Additional: CreateEkmConnectionAsync(string, string, EkmConnection, CancellationToken) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; string ekmConnectionId = ""; EkmConnection ekmConnection = new EkmConnection(); // Make the request EkmConnection response = await ekmServiceClient.CreateEkmConnectionAsync(parent, ekmConnectionId, ekmConnection); // End snippet } /// <summary>Snippet for CreateEkmConnection</summary> public void CreateEkmConnectionResourceNames() { // Snippet: CreateEkmConnection(LocationName, string, EkmConnection, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); string ekmConnectionId = ""; EkmConnection ekmConnection = new EkmConnection(); // Make the request EkmConnection response = ekmServiceClient.CreateEkmConnection(parent, ekmConnectionId, ekmConnection); // End snippet } /// <summary>Snippet for CreateEkmConnectionAsync</summary> public async Task CreateEkmConnectionResourceNamesAsync() { // Snippet: CreateEkmConnectionAsync(LocationName, string, EkmConnection, CallSettings) // Additional: CreateEkmConnectionAsync(LocationName, string, EkmConnection, CancellationToken) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); string ekmConnectionId = ""; EkmConnection ekmConnection = new EkmConnection(); // Make the request EkmConnection response = await ekmServiceClient.CreateEkmConnectionAsync(parent, ekmConnectionId, ekmConnection); // End snippet } /// <summary>Snippet for UpdateEkmConnection</summary> public void UpdateEkmConnectionRequestObject() { // Snippet: UpdateEkmConnection(UpdateEkmConnectionRequest, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) UpdateEkmConnectionRequest request = new UpdateEkmConnectionRequest { EkmConnection = new EkmConnection(), UpdateMask = new FieldMask(), }; // Make the request EkmConnection response = ekmServiceClient.UpdateEkmConnection(request); // End snippet } /// <summary>Snippet for UpdateEkmConnectionAsync</summary> public async Task UpdateEkmConnectionRequestObjectAsync() { // Snippet: UpdateEkmConnectionAsync(UpdateEkmConnectionRequest, CallSettings) // Additional: UpdateEkmConnectionAsync(UpdateEkmConnectionRequest, CancellationToken) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) UpdateEkmConnectionRequest request = new UpdateEkmConnectionRequest { EkmConnection = new EkmConnection(), UpdateMask = new FieldMask(), }; // Make the request EkmConnection response = await ekmServiceClient.UpdateEkmConnectionAsync(request); // End snippet } /// <summary>Snippet for UpdateEkmConnection</summary> public void UpdateEkmConnection() { // Snippet: UpdateEkmConnection(EkmConnection, FieldMask, CallSettings) // Create client EkmServiceClient ekmServiceClient = EkmServiceClient.Create(); // Initialize request argument(s) EkmConnection ekmConnection = new EkmConnection(); FieldMask updateMask = new FieldMask(); // Make the request EkmConnection response = ekmServiceClient.UpdateEkmConnection(ekmConnection, updateMask); // End snippet } /// <summary>Snippet for UpdateEkmConnectionAsync</summary> public async Task UpdateEkmConnectionAsync() { // Snippet: UpdateEkmConnectionAsync(EkmConnection, FieldMask, CallSettings) // Additional: UpdateEkmConnectionAsync(EkmConnection, FieldMask, CancellationToken) // Create client EkmServiceClient ekmServiceClient = await EkmServiceClient.CreateAsync(); // Initialize request argument(s) EkmConnection ekmConnection = new EkmConnection(); FieldMask updateMask = new FieldMask(); // Make the request EkmConnection response = await ekmServiceClient.UpdateEkmConnectionAsync(ekmConnection, updateMask); // End snippet } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Linq; using System.Runtime.InteropServices; using Xunit; using Roslyn.Test.PdbUtilities; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MissingAssemblyTests : ExpressionCompilerTestBase { [Fact] public void ErrorsWithAssemblyIdentityArguments() { var identity = new AssemblyIdentity(GetUniqueName()); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity)); } [Fact] public void ErrorsWithAssemblySymbolArguments() { var assembly = CreateCompilation("").Assembly; var identity = assembly.Identity; Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_SingleTypeNameNotFoundFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NameNotInContextPossibleMissingReference, assembly)); } [Fact] public void ErrorsRequiringSystemCore() { var identity = EvaluationContextBase.SystemCoreIdentity; Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NoSuchMemberOrExtension)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicAttributeMissing)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicRequiredTypesMissing)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_QueryNoProviderStandard)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_ExtensionAttrNotFound)); } [Fact] public void MultipleAssemblyArguments() { var identity1 = new AssemblyIdentity(GetUniqueName()); var identity2 = new AssemblyIdentity(GetUniqueName()); Assert.Equal(identity1, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity1, identity2)); Assert.Equal(identity2, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity2, identity1)); } [Fact] public void NoAssemblyArguments() { Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef)); Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, "Not an assembly")); } [Fact] public void ERR_NoTypeDef() { var libSource = @" public class Missing { } "; var source = @" public class C { public void M(Missing parameter) { } } "; var libRef = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib").EmitToImageReference(); var comp = CreateCompilationWithMscorlib(source, new[] { libRef }, TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef); var expectedError = "error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'."; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Lib"); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "parameter", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [Fact] public void ERR_QueryNoProviderStandard() { var source = @" public class C { public void M(int[] array) { } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef }, TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef); var expectedError = "(1,11): error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Select' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?"; var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "from i in array select i", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [WorkItem(1151888, "DevDiv")] [Fact] public void ERR_NoSuchMemberOrExtension_CompilationReferencesSystemCore() { var source = @" using System.Linq; public class C { public void M(int[] array) { } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef }, TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef); var expectedErrorTemplate = "error CS1061: 'int[]' does not contain a definition for '{0}' and no extension method '{0}' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)"; var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "array.Count()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "Count"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "array.NoSuchMethod()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "NoSuchMethod"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } /// <remarks> /// The fact that the compilation does not reference System.Core has no effect since /// this test only covers our ability to identify an assembly to attempt to load, not /// our ability to actually load or consume it. /// </remarks> [WorkItem(1151888, "DevDiv")] [Fact] public void ERR_NoSuchMemberOrExtension_CompilationDoesNotReferenceSystemCore() { var source = @" using System.Linq; public class C { public void M(int[] array) { } } namespace System.Linq { public class Dummy { } } "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef); var expectedErrorTemplate = "error CS1061: 'int[]' does not contain a definition for '{0}' and no extension method '{0}' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)"; var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "array.Count()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "Count"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "array.NoSuchMethod()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "NoSuchMethod"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [Fact] public void ForwardingErrors() { var il = @" .assembly extern mscorlib { } .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder Forwarded { .assembly extern pe2 } .class extern forwarder NS.Forwarded { .assembly extern pe2 } .class public auto ansi beforefieldinit Dummy extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var csharp = @" class C { static void M(Dummy d) { } } "; var ilRef = CompileIL(il, appendDefaultHeader: false); var comp = CreateCompilationWithMscorlib(csharp, new[] { ilRef }); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var expectedMissingAssemblyIdentity = new AssemblyIdentity("pe2"); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "new global::Forwarded()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1068: The type name 'Forwarded' could not be found in the global namespace. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "new Forwarded()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1070: The type name 'Forwarded' could not be found. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "new NS.Forwarded()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1069: The type name 'Forwarded' could not be found in the namespace 'NS'. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [Fact] public unsafe void ShouldTryAgain_Success() { var comp = CreateCompilationWithMscorlib("public class C { }"); using (var pinned = new PinnedMetadata(GetMetadataBytes(comp))) { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { uSize = (uint)pinned.Size; return pinned.Pointer; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentity = new AssemblyIdentity("A"); var missingAssemblyIdentities = ImmutableArray.Create(missingAssemblyIdentity); Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); var newReference = references.Single(); Assert.Equal(pinned.Pointer, newReference.Pointer); Assert.Equal(pinned.Size, newReference.Size); } } [Fact] public unsafe void ShouldTryAgain_Mixed() { var comp1 = CreateCompilationWithMscorlib("public class C { }", assemblyName: GetUniqueName()); var comp2 = CreateCompilationWithMscorlib("public class D { }", assemblyName: GetUniqueName()); using (PinnedMetadata pinned1 = new PinnedMetadata(GetMetadataBytes(comp1)), pinned2 = new PinnedMetadata(GetMetadataBytes(comp2))) { var assemblyIdentity1 = comp1.Assembly.Identity; var assemblyIdentity2 = comp2.Assembly.Identity; Assert.NotEqual(assemblyIdentity1, assemblyIdentity2); DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { if (assemblyIdentity == assemblyIdentity1) { uSize = (uint)pinned1.Size; return pinned1.Pointer; } else if (assemblyIdentity == assemblyIdentity2) { uSize = (uint)pinned2.Size; return pinned2.Pointer; } else { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA)); throw ExceptionUtilities.Unreachable; } }; var references = ImmutableArray.Create(default(MetadataBlock)); var unknownAssemblyIdentity = new AssemblyIdentity(GetUniqueName()); var missingAssemblyIdentities = ImmutableArray.Create(assemblyIdentity1, unknownAssemblyIdentity, assemblyIdentity2); Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Equal(3, references.Length); Assert.Equal(default(MetadataBlock), references[0]); Assert.Equal(pinned1.Pointer, references[1].Pointer); Assert.Equal(pinned1.Size, references[1].Size); Assert.Equal(pinned2.Pointer, references[2].Pointer); Assert.Equal(pinned2.Size, references[2].Size); } } [Fact] public void ShouldTryAgain_CORDBG_E_MISSING_METADATA() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA)); throw ExceptionUtilities.Unreachable; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Empty(references); } [Fact] public void ShouldTryAgain_COR_E_BADIMAGEFORMAT() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.COR_E_BADIMAGEFORMAT)); throw ExceptionUtilities.Unreachable; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Empty(references); } [Fact] public void ShouldTryAgain_OtherException() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { throw new Exception(); }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.Throws<Exception>(() => ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); } [WorkItem(1124725, "DevDiv")] [Fact] public void PseudoVariableType() { var source = @"class C { static void M() { } } "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", CSharpRef, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference); const string expectedError = "error CS0012: The type 'Exception' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'."; var expectedMissingAssemblyIdentity = comp.Assembly.CorLibrary.Identity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "$stowedexception", DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(ExceptionAlias("Microsoft.CSharp.RuntimeBinder.RuntimeBinderException, Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", stowed: true)), DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [WorkItem(1114866)] [ConditionalFact(typeof(OSVersionWin8))] public void NotYetLoadedWinMds() { var source = @"class C { static void M(Windows.Storage.StorageFolder f) { } }"; var comp = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Any()); var context = CreateMethodContextWithReferences(comp, "C.M", ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies)); const string expectedError = "error CS0234: The type or namespace name 'UI' does not exist in the namespace 'Windows' (are you missing an assembly reference?)"; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "typeof(@Windows.UI.Colors)", DkmEvaluationFlags.None, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } /// <remarks> /// Windows.UI.Xaml is the only (win8) winmd with more than two parts. /// </remarks> [WorkItem(1114866)] [ConditionalFact(typeof(OSVersionWin8))] public void NotYetLoadedWinMds_MultipleParts() { var source = @"class C { static void M(Windows.UI.Colors c) { } }"; var comp = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI"); Assert.True(runtimeAssemblies.Any()); var context = CreateMethodContextWithReferences(comp, "C.M", ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies)); const string expectedError = "error CS0234: The type or namespace name 'Xaml' does not exist in the namespace 'Windows.UI' (are you missing an assembly reference?)"; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI.Xaml", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "typeof(Windows.@UI.Xaml.Application)", DkmEvaluationFlags.None, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [WorkItem(1154988)] [Fact] public void CompileWithRetrySameErrorReported() { var source = @" class C { void M() { } }"; var comp = CreateCompilationWithMscorlib(source); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var missingModule = runtime.Modules.First(); var missingIdentity = missingModule.MetadataReader.ReadAssemblyIdentityOrThrow(); var numRetries = 0; string errorMessage; ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(), context, (_, diagnostics) => { numRetries++; Assert.InRange(numRetries, 0, 2); // We don't want to loop forever... diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDef, "MissingType", missingIdentity), Location.None)); return null; }, (AssemblyIdentity assemblyIdentity, out uint uSize) => { uSize = (uint)missingModule.MetadataLength; return missingModule.MetadataAddress; }, out errorMessage); Assert.Equal(2, numRetries); // Ensure that we actually retried and that we bailed out on the second retry if the same identity was seen in the diagnostics. Assert.Equal($"error CS0012: The type 'MissingType' is defined in an assembly that is not referenced. You must add a reference to assembly '{missingIdentity}'.", errorMessage); } [WorkItem(1151888)] [Fact] public void SucceedOnRetry() { var source = @" class C { void M() { } }"; var comp = CreateCompilationWithMscorlib(source); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var missingModule = runtime.Modules.First(); var missingIdentity = missingModule.MetadataReader.ReadAssemblyIdentityOrThrow(); var shouldSucceed = false; string errorMessage; var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(), context, (_, diagnostics) => { if (shouldSucceed) { return TestCompileResult.Instance; } else { shouldSucceed = true; diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDef, "MissingType", missingIdentity), Location.None)); return null; } }, (AssemblyIdentity assemblyIdentity, out uint uSize) => { uSize = (uint)missingModule.MetadataLength; return missingModule.MetadataAddress; }, out errorMessage); Assert.Same(TestCompileResult.Instance, compileResult); Assert.Null(errorMessage); } private sealed class TestCompileResult : CompileResult { public static readonly CompileResult Instance = new TestCompileResult(); private TestCompileResult() : base(null, null, null, null) { } public override CustomTypeInfo GetCustomTypeInfo() { throw new NotImplementedException(); } } private EvaluationContext CreateMethodContextWithReferences(Compilation comp, string methodName, params MetadataReference[] references) { return CreateMethodContextWithReferences(comp, methodName, ImmutableArray.CreateRange(references)); } private EvaluationContext CreateMethodContextWithReferences(Compilation comp, string methodName, ImmutableArray<MetadataReference> references) { byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> unusedReferences; var result = comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out unusedReferences); Assert.True(result); var runtime = CreateRuntimeInstance(GetUniqueName(), references, exeBytes, new SymReader(pdbBytes)); return CreateMethodContext(runtime, methodName); } private static AssemblyIdentity GetMissingAssemblyIdentity(ErrorCode code, params object[] arguments) { var missingAssemblyIdentities = EvaluationContext.GetMissingAssemblyIdentitiesHelper(code, arguments); return missingAssemblyIdentities.IsDefault ? null : missingAssemblyIdentities.Single(); } private static ImmutableArray<byte> GetMetadataBytes(Compilation comp) { var imageReference = (MetadataImageReference)comp.EmitToImageReference(); var assemblyMetadata = (AssemblyMetadata)imageReference.GetMetadata(); var moduleMetadata = assemblyMetadata.GetModules()[0]; return moduleMetadata.Module.PEReaderOpt.GetMetadata().GetContent(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using Xunit; namespace System.Net.Sockets.Tests { // TODO: // // End*: // - Invalid asyncresult type // - asyncresult from different object // - asyncresult with end already called public class ArgumentValidation { private readonly static byte[] s_buffer = new byte[1]; private readonly static IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) }; private readonly static Socket s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private readonly static Socket s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); private static void TheAsyncCallback(IAsyncResult ar) { } private static Socket GetSocket(AddressFamily addressFamily = AddressFamily.InterNetwork) { Debug.Assert(addressFamily == AddressFamily.InterNetwork || addressFamily == AddressFamily.InterNetworkV6); return addressFamily == AddressFamily.InterNetwork ? s_ipv4Socket : s_ipv6Socket; } [Fact] public void BeginAccept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().BeginAccept(TheAsyncCallback, null)); } [Fact] public void BeginAccept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.BeginAccept(TheAsyncCallback, null)); } } [Fact] public void EndAccept_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndAccept(null)); } [Fact] public void BeginConnect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((EndPoint)null, TheAsyncCallback, null)); } [Fact] public void BeginConnect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); } } [Fact] public void BeginConnect_EndPoint_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6), TheAsyncCallback, null)); } [Fact] public void BeginConnect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((string)null, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_Host_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", -1, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", 65536, TheAsyncCallback, null)); } [Fact] public void BeginConnect_Host_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect("localhost", 1, TheAsyncCallback, null)); } } [Fact] public void BeginConnect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress)null, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, -1, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, 65536, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddress_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(IPAddress.IPv6Loopback, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddresses_NullIPAddresses_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress[])null, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddresses_EmptyIPAddresses_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, -1, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, 65536, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddresses_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null)); } } [Fact] public void EndConnect_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndConnect(null)); } [Fact] public void BeginSend_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffers_EmptyBuffers_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void EndSend_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSend(null)); } [Fact] public void BeginSendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); } [Fact] public void BeginSendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(s_buffer, 0, 0, SocketFlags.None, null, TheAsyncCallback, null)); } [Fact] public void BeginSendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); } [Fact] public void BeginSendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, -1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); } [Fact] public void EndSendTo_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSendTo(null)); } [Fact] public void BeginReceive_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffers_EmptyBuffers_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void EndReceive_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceive(null)); } [Fact] public void BeginReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void BeginReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void BeginReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void BeginReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void BeginReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void BeginReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void EndReceiveFrom_NullAsyncResult_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveFrom(null, ref endpoint)); } [Fact] public void BeginReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(null, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void BeginReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint remote = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void BeginReceiveMessageFrom_AddressFamily_Throws_Argument() { EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void BeginReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void BeginReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, -1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void BeginReceiveMessageFrom_NotBound_Throws_InvalidOperation() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void EndReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; // Behavior difference from Desktop: used to throw ArgumentException. Assert.Throws<ArgumentNullException>(() => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_NullAsyncResult_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // Implements the algorithm for distributing loop indices to parallel loop workers // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Threading.Tasks { /// <summary> /// Represents an index range /// </summary> [StructLayout(LayoutKind.Auto)] internal struct IndexRange { // the From and To values for this range. These do not change. internal long _nFromInclusive; internal long _nToExclusive; // The shared index, stored as the offset from nFromInclusive. Using an offset rather than the actual // value saves us from overflows that can happen due to multiple workers racing to increment this. // All updates to this field need to be interlocked. To avoid split interlockeds across cache-lines // in 32-bit processes, in 32-bit processes when the range fits in a 32-bit value, we prefer to use // a 32-bit field, and just use the first 32-bits of the long. And to minimize false sharing, each // value is stored in its own heap-allocated object, which is lazily allocated by the thread using // that range, minimizing the chances it'll be near the objects from other threads. internal volatile Box<long> _nSharedCurrentIndexOffset; // to be set to 1 by the worker that finishes this range. It's OK to do a non-interlocked write here. internal int _bRangeFinished; } /// <summary> /// The RangeWorker struct wraps the state needed by a task that services the parallel loop /// </summary> [StructLayout(LayoutKind.Auto)] internal struct RangeWorker { // reference to the IndexRange array allocated by the range manager internal readonly IndexRange[] _indexRanges; // index of the current index range that this worker is grabbing chunks from internal int _nCurrentIndexRange; // the step for this loop. Duplicated here for quick access (rather than jumping to rangemanager) internal long _nStep; // increment value is the current amount that this worker will use // to increment the shared index of the range it's working on internal long _nIncrementValue; // the increment value is doubled each time this worker finds work, and is capped at this value internal readonly long _nMaxIncrementValue; // whether to use 32-bits or 64-bits of current index in each range internal readonly bool _use32BitCurrentIndex; internal bool IsInitialized { get { return _indexRanges != null; } } /// <summary> /// Initializes a RangeWorker struct /// </summary> internal RangeWorker(IndexRange[] ranges, int nInitialRange, long nStep, bool use32BitCurrentIndex) { _indexRanges = ranges; _use32BitCurrentIndex = use32BitCurrentIndex; _nCurrentIndexRange = nInitialRange; _nStep = nStep; _nIncrementValue = nStep; _nMaxIncrementValue = Parallel.DEFAULT_LOOP_STRIDE * nStep; } /// <summary> /// Implements the core work search algorithm that will be used for this range worker. /// </summary> /// /// Usage pattern is: /// 1) the thread associated with this rangeworker calls FindNewWork /// 2) if we return true, the worker uses the nFromInclusiveLocal and nToExclusiveLocal values /// to execute the sequential loop /// 3) if we return false it means there is no more work left. It's time to quit. /// internal bool FindNewWork(out long nFromInclusiveLocal, out long nToExclusiveLocal) { // since we iterate over index ranges circularly, we will use the // count of visited ranges as our exit condition int numIndexRangesToVisit = _indexRanges.Length; do { // local snap to save array access bounds checks in places where we only read fields IndexRange currentRange = _indexRanges[_nCurrentIndexRange]; if (currentRange._bRangeFinished == 0) { if (_indexRanges[_nCurrentIndexRange]._nSharedCurrentIndexOffset == null) { Interlocked.CompareExchange(ref _indexRanges[_nCurrentIndexRange]._nSharedCurrentIndexOffset, new Box<long>(0), null); } long nMyOffset; if (IntPtr.Size == 4 && _use32BitCurrentIndex) { // In 32-bit processes, we prefer to use 32-bit interlocked operations, to avoid the possibility of doing // a 64-bit interlocked when the target value crosses a cache line, as that can be super expensive. // We use the first 32 bits of the Int64 index in such cases. unsafe { fixed (long* indexPtr = &_indexRanges[_nCurrentIndexRange]._nSharedCurrentIndexOffset.Value) { nMyOffset = Interlocked.Add(ref *(int*)indexPtr, (int)_nIncrementValue) - _nIncrementValue; } } } else { nMyOffset = Interlocked.Add(ref _indexRanges[_nCurrentIndexRange]._nSharedCurrentIndexOffset.Value, _nIncrementValue) - _nIncrementValue; } if (currentRange._nToExclusive - currentRange._nFromInclusive > nMyOffset) { // we found work nFromInclusiveLocal = currentRange._nFromInclusive + nMyOffset; nToExclusiveLocal = unchecked(nFromInclusiveLocal + _nIncrementValue); // Check for going past end of range, or wrapping if ((nToExclusiveLocal > currentRange._nToExclusive) || (nToExclusiveLocal < currentRange._nFromInclusive)) { nToExclusiveLocal = currentRange._nToExclusive; } // We will double our unit of increment until it reaches the maximum. if (_nIncrementValue < _nMaxIncrementValue) { _nIncrementValue *= 2; if (_nIncrementValue > _nMaxIncrementValue) { _nIncrementValue = _nMaxIncrementValue; } } return true; } else { // this index range is completed, mark it so that others can skip it quickly Interlocked.Exchange(ref _indexRanges[_nCurrentIndexRange]._bRangeFinished, 1); } } // move on to the next index range, in circular order. _nCurrentIndexRange = (_nCurrentIndexRange + 1) % _indexRanges.Length; numIndexRangesToVisit--; } while (numIndexRangesToVisit > 0); // we've visited all index ranges possible => there's no work remaining nFromInclusiveLocal = 0; nToExclusiveLocal = 0; return false; } /// <summary> /// 32 bit integer version of FindNewWork. Assumes the ranges were initialized with 32 bit values. /// </summary> internal bool FindNewWork32(out int nFromInclusiveLocal32, out int nToExclusiveLocal32) { long nFromInclusiveLocal; long nToExclusiveLocal; bool bRetVal = FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal); Debug.Assert((nFromInclusiveLocal <= int.MaxValue) && (nFromInclusiveLocal >= int.MinValue) && (nToExclusiveLocal <= int.MaxValue) && (nToExclusiveLocal >= int.MinValue)); // convert to 32 bit before returning nFromInclusiveLocal32 = (int)nFromInclusiveLocal; nToExclusiveLocal32 = (int)nToExclusiveLocal; return bRetVal; } } /// <summary> /// Represents the entire loop operation, keeping track of workers and ranges. /// </summary> /// /// The usage pattern is: /// 1) The Parallel loop entry function (ForWorker) creates an instance of this class /// 2) Every thread joining to service the parallel loop calls RegisterWorker to grab a /// RangeWorker struct to wrap the state it will need to find and execute work, /// and they keep interacting with that struct until the end of the loop internal class RangeManager { internal readonly IndexRange[] _indexRanges; internal readonly bool _use32BitCurrentIndex; internal int _nCurrentIndexRangeToAssign; internal long _nStep; /// <summary> /// Initializes a RangeManager with the given loop parameters, and the desired number of outer ranges /// </summary> internal RangeManager(long nFromInclusive, long nToExclusive, long nStep, int nNumExpectedWorkers) { _nCurrentIndexRangeToAssign = 0; _nStep = nStep; // Our signed math breaks down w/ nNumExpectedWorkers == 1. So change it to 2. if (nNumExpectedWorkers == 1) nNumExpectedWorkers = 2; // // calculate the size of each index range // ulong uSpan = (ulong)(nToExclusive - nFromInclusive); ulong uRangeSize = uSpan / (ulong)nNumExpectedWorkers; // rough estimate first uRangeSize -= uRangeSize % (ulong)nStep; // snap to multiples of nStep // otherwise index range transitions will derail us from nStep if (uRangeSize == 0) { uRangeSize = (ulong)nStep; } // // find the actual number of index ranges we will need // Debug.Assert((uSpan / uRangeSize) < int.MaxValue); int nNumRanges = (int)(uSpan / uRangeSize); if (uSpan % uRangeSize != 0) { nNumRanges++; } // Convert to signed so the rest of the logic works. // Should be fine so long as uRangeSize < Int64.MaxValue, which we guaranteed by setting #workers >= 2. long nRangeSize = (long)uRangeSize; _use32BitCurrentIndex = IntPtr.Size == 4 && nRangeSize <= int.MaxValue; // allocate the array of index ranges _indexRanges = new IndexRange[nNumRanges]; long nCurrentIndex = nFromInclusive; for (int i = 0; i < nNumRanges; i++) { // the fromInclusive of the new index range is always on nCurrentIndex _indexRanges[i]._nFromInclusive = nCurrentIndex; _indexRanges[i]._nSharedCurrentIndexOffset = null; _indexRanges[i]._bRangeFinished = 0; // now increment it to find the toExclusive value for our range nCurrentIndex = unchecked(nCurrentIndex + nRangeSize); // detect integer overflow or range overage and snap to nToExclusive if (nCurrentIndex < unchecked(nCurrentIndex - nRangeSize) || nCurrentIndex > nToExclusive) { // this should only happen at the last index Debug.Assert(i == nNumRanges - 1); nCurrentIndex = nToExclusive; } // now that the end point of the new range is calculated, assign it. _indexRanges[i]._nToExclusive = nCurrentIndex; } } /// <summary> /// The function that needs to be called by each new worker thread servicing the parallel loop /// in order to get a RangeWorker struct that wraps the state for finding and executing indices /// </summary> internal RangeWorker RegisterNewWorker() { Debug.Assert(_indexRanges != null && _indexRanges.Length != 0); int nInitialRange = (Interlocked.Increment(ref _nCurrentIndexRangeToAssign) - 1) % _indexRanges.Length; return new RangeWorker(_indexRanges, nInitialRange, _nStep, _use32BitCurrentIndex); } } }
// 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.Diagnostics; using System.Globalization; using System.IO; using System.Net.Sockets; using System.Text; namespace System.Net { internal enum FtpPrimitive { Upload = 0, Download = 1, CommandOnly = 2 }; internal enum FtpLoginState : byte { NotLoggedIn, LoggedIn, LoggedInButNeedsRelogin, ReloginFailed }; /// <summary> /// <para> /// The FtpControlStream class implements a basic FTP connection, /// This means basic command sending and parsing. /// </para> /// </summary> internal class FtpControlStream : CommandStream { private Socket _dataSocket; private IPEndPoint _passiveEndPoint; private TlsStream _tlsStream; private StringBuilder _bannerMessage; private StringBuilder _welcomeMessage; private StringBuilder _exitMessage; private WeakReference _credentials; private string _currentTypeSetting = string.Empty; private long _contentLength = -1; private DateTime _lastModified; private bool _dataHandshakeStarted = false; private string _loginDirectory = null; private string _establishedServerDirectory = null; private string _requestedServerDirectory = null; private Uri _responseUri; private FtpLoginState _loginState = FtpLoginState.NotLoggedIn; internal FtpStatusCode StatusCode; internal string StatusLine; internal NetworkCredential Credentials { get { if (_credentials != null && _credentials.IsAlive) { return (NetworkCredential)_credentials.Target; } else { return null; } } set { if (_credentials == null) { _credentials = new WeakReference(null); } _credentials.Target = value; } } private static readonly AsyncCallback s_acceptCallbackDelegate = new AsyncCallback(AcceptCallback); private static readonly AsyncCallback s_connectCallbackDelegate = new AsyncCallback(ConnectCallback); private static readonly AsyncCallback s_SSLHandshakeCallback = new AsyncCallback(SSLHandshakeCallback); internal FtpControlStream(TcpClient client) : base(client) { } /// <summary> /// <para>Closes the connecting socket to generate an error.</para> /// </summary> internal void AbortConnect() { Socket socket = _dataSocket; if (socket != null) { try { socket.Close(); } catch (ObjectDisposedException) { } } } /// <summary> /// <para>Provides a wrapper for the async accept operations /// </summary> private static void AcceptCallback(IAsyncResult asyncResult) { FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState; Socket listenSocket = connection._dataSocket; try { connection._dataSocket = listenSocket.EndAccept(asyncResult); if (!connection.ServerAddress.Equals(((IPEndPoint)connection._dataSocket.RemoteEndPoint).Address)) { connection._dataSocket.Close(); throw new WebException(SR.net_ftp_active_address_different, WebExceptionStatus.ProtocolError); } connection.ContinueCommandPipeline(); } catch (Exception e) { connection.CloseSocket(); connection.InvokeRequestCallback(e); } finally { listenSocket.Close(); } } /// <summary> /// <para>Provides a wrapper for the async accept operations</para> /// </summary> private static void ConnectCallback(IAsyncResult asyncResult) { FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState; try { connection._dataSocket.EndConnect(asyncResult); connection.ContinueCommandPipeline(); } catch (Exception e) { connection.CloseSocket(); connection.InvokeRequestCallback(e); } } private static void SSLHandshakeCallback(IAsyncResult asyncResult) { FtpControlStream connection = (FtpControlStream)asyncResult.AsyncState; try { connection._tlsStream.EndAuthenticateAsClient(asyncResult); connection.ContinueCommandPipeline(); } catch (Exception e) { connection.CloseSocket(); connection.InvokeRequestCallback(e); } } // Creates a FtpDataStream object, constructs a TLS stream if needed. // In case SSL and ASYNC we delay sigaling the user stream until the handshake is done. private PipelineInstruction QueueOrCreateFtpDataStream(ref Stream stream) { if (_dataSocket == null) throw new InternalException(); // // Re-entered pipeline with completed read on the TlsStream // if (_tlsStream != null) { stream = new FtpDataStream(_tlsStream, (FtpWebRequest)_request, IsFtpDataStreamWriteable()); _tlsStream = null; return PipelineInstruction.GiveStream; } NetworkStream networkStream = new NetworkStream(_dataSocket, true); if (UsingSecureStream) { FtpWebRequest request = (FtpWebRequest)_request; TlsStream tlsStream = new TlsStream(networkStream, _dataSocket, request.RequestUri.Host, request.ClientCertificates); networkStream = tlsStream; if (_isAsync) { _tlsStream = tlsStream; tlsStream.BeginAuthenticateAsClient(s_SSLHandshakeCallback, this); return PipelineInstruction.Pause; } else { tlsStream.AuthenticateAsClient(); } } stream = new FtpDataStream(networkStream, (FtpWebRequest)_request, IsFtpDataStreamWriteable()); return PipelineInstruction.GiveStream; } protected override void ClearState() { _contentLength = -1; _lastModified = DateTime.MinValue; _responseUri = null; _dataHandshakeStarted = false; StatusCode = FtpStatusCode.Undefined; StatusLine = null; _dataSocket = null; _passiveEndPoint = null; _tlsStream = null; base.ClearState(); } // This is called by underlying base class code, each time a new response is received from the wire or a protocol stage is resumed. // This function controls the setting up of a data socket/connection, and of saving off the server responses. protected override PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Command:{entry?.Command} Description:{response?.StatusDescription}"); // null response is not expected if (response == null) return PipelineInstruction.Abort; FtpStatusCode status = (FtpStatusCode)response.Status; // // Update global "current status" for FtpWebRequest // if (status != FtpStatusCode.ClosingControl) { // A 221 status won't be reflected on the user FTP response // Anything else will (by design?) StatusCode = status; StatusLine = response.StatusDescription; } // If the status code is outside the range defined in RFC (1xx to 5xx) throw if (response.InvalidStatusCode) throw new WebException(SR.net_InvalidStatusCode, WebExceptionStatus.ProtocolError); // Update the banner message if any, this is a little hack because the "entry" param is null if (_index == -1) { if (status == FtpStatusCode.SendUserCommand) { _bannerMessage = new StringBuilder(); _bannerMessage.Append(StatusLine); return PipelineInstruction.Advance; } else if (status == FtpStatusCode.ServiceTemporarilyNotAvailable) { return PipelineInstruction.Reread; } else throw GenerateException(status, response.StatusDescription, null); } // // Check for the result of our attempt to use UTF8 // if (entry.Command == "OPTS utf8 on\r\n") { if (response.PositiveCompletion) { Encoding = Encoding.UTF8; } else { Encoding = Encoding.Default; } return PipelineInstruction.Advance; } // If we are already logged in and the server returns 530 then // the server does not support re-issuing a USER command, // tear down the connection and start all over again if (entry.Command.IndexOf("USER") != -1) { // The server may not require a password for this user, so bypass the password command if (status == FtpStatusCode.LoggedInProceed) { _loginState = FtpLoginState.LoggedIn; _index++; } } // // Throw on an error with possible recovery option // if (response.TransientFailure || response.PermanentFailure) { if (status == FtpStatusCode.ServiceNotAvailable) { MarkAsRecoverableFailure(); } throw GenerateException(status, response.StatusDescription, null); } if (_loginState != FtpLoginState.LoggedIn && entry.Command.IndexOf("PASS") != -1) { // Note the fact that we logged in if (status == FtpStatusCode.NeedLoginAccount || status == FtpStatusCode.LoggedInProceed) _loginState = FtpLoginState.LoggedIn; else throw GenerateException(status, response.StatusDescription, null); } // // Parse special cases // if (entry.HasFlag(PipelineEntryFlags.CreateDataConnection) && (response.PositiveCompletion || response.PositiveIntermediate)) { bool isSocketReady; PipelineInstruction result = QueueOrCreateDataConection(entry, response, timeout, ref stream, out isSocketReady); if (!isSocketReady) return result; // otherwise we have a stream to create } // // This is part of the above case and it's all about giving data stream back // if (status == FtpStatusCode.OpeningData || status == FtpStatusCode.DataAlreadyOpen) { if (_dataSocket == null) { return PipelineInstruction.Abort; } if (!entry.HasFlag(PipelineEntryFlags.GiveDataStream)) { _abortReason = SR.Format(SR.net_ftp_invalid_status_response, status, entry.Command); return PipelineInstruction.Abort; } // Parse out the Content length, if we can TryUpdateContentLength(response.StatusDescription); // Parse out the file name, when it is returned and use it for our ResponseUri FtpWebRequest request = (FtpWebRequest)_request; if (request.MethodInfo.ShouldParseForResponseUri) { TryUpdateResponseUri(response.StatusDescription, request); } return QueueOrCreateFtpDataStream(ref stream); } // // Parse responses by status code exclusivelly // // Update welcome message if (status == FtpStatusCode.LoggedInProceed) { _welcomeMessage.Append(StatusLine); } // OR set the user response ExitMessage else if (status == FtpStatusCode.ClosingControl) { _exitMessage.Append(response.StatusDescription); // And close the control stream socket on "QUIT" CloseSocket(); } // OR set us up for SSL/TLS, after this we'll be writing securely else if (status == FtpStatusCode.ServerWantsSecureSession) { // If NetworkStream is a TlsStream, then this must be in the async callback // from completing the SSL handshake. // So just let the pipeline continue. if (!(NetworkStream is TlsStream)) { FtpWebRequest request = (FtpWebRequest)_request; TlsStream tlsStream = new TlsStream(NetworkStream, Socket, request.RequestUri.Host, request.ClientCertificates); if (_isAsync) { tlsStream.BeginAuthenticateAsClient(ar => { try { tlsStream.EndAuthenticateAsClient(ar); NetworkStream = tlsStream; this.ContinueCommandPipeline(); } catch (Exception e) { this.CloseSocket(); this.InvokeRequestCallback(e); } }, null); return PipelineInstruction.Pause; } else { tlsStream.AuthenticateAsClient(); NetworkStream = tlsStream; } } } // OR parse out the file size or file time, usually a result of sending SIZE/MDTM commands else if (status == FtpStatusCode.FileStatus) { FtpWebRequest request = (FtpWebRequest)_request; if (entry.Command.StartsWith("SIZE ")) { _contentLength = GetContentLengthFrom213Response(response.StatusDescription); } else if (entry.Command.StartsWith("MDTM ")) { _lastModified = GetLastModifiedFrom213Response(response.StatusDescription); } } // OR parse out our login directory else if (status == FtpStatusCode.PathnameCreated) { if (entry.Command == "PWD\r\n" && !entry.HasFlag(PipelineEntryFlags.UserCommand)) { _loginDirectory = GetLoginDirectory(response.StatusDescription); } } // Asserting we have some positive response else { // We only use CWD to reset ourselves back to the login directory. if (entry.Command.IndexOf("CWD") != -1) { _establishedServerDirectory = _requestedServerDirectory; } } // Intermediate responses require rereading if (response.PositiveIntermediate || (!UsingSecureStream && entry.Command == "AUTH TLS\r\n")) { return PipelineInstruction.Reread; } return PipelineInstruction.Advance; } /// <summary> /// <para>Creates an array of commands, that will be sent to the server</para> /// </summary> protected override PipelineEntry[] BuildCommandsList(WebRequest req) { bool resetLoggedInState = false; FtpWebRequest request = (FtpWebRequest)req; if (NetEventSource.IsEnabled) NetEventSource.Info(this); _responseUri = request.RequestUri; ArrayList commandList = new ArrayList(); if (request.EnableSsl && !UsingSecureStream) { commandList.Add(new PipelineEntry(FormatFtpCommand("AUTH", "TLS"))); // According to RFC we need to re-authorize with USER/PASS after we re-authenticate. resetLoggedInState = true; } if (resetLoggedInState) { _loginDirectory = null; _establishedServerDirectory = null; _requestedServerDirectory = null; _currentTypeSetting = string.Empty; if (_loginState == FtpLoginState.LoggedIn) _loginState = FtpLoginState.LoggedInButNeedsRelogin; } if (_loginState != FtpLoginState.LoggedIn) { Credentials = request.Credentials.GetCredential(request.RequestUri, "basic"); _welcomeMessage = new StringBuilder(); _exitMessage = new StringBuilder(); string domainUserName = string.Empty; string password = string.Empty; if (Credentials != null) { domainUserName = Credentials.UserName; string domain = Credentials.Domain; if (!string.IsNullOrEmpty(domain)) { domainUserName = domain + "\\" + domainUserName; } password = Credentials.Password; } if (domainUserName.Length == 0 && password.Length == 0) { domainUserName = "anonymous"; password = "anonymous@"; } commandList.Add(new PipelineEntry(FormatFtpCommand("USER", domainUserName))); commandList.Add(new PipelineEntry(FormatFtpCommand("PASS", password), PipelineEntryFlags.DontLogParameter)); // If SSL, always configure data channel encryption after authentication to maximum RFC compatibility. The RFC allows for // PBSZ/PROT commands to come either before or after the USER/PASS, but some servers require USER/PASS immediately after // the AUTH TLS command. if (request.EnableSsl && !UsingSecureStream) { commandList.Add(new PipelineEntry(FormatFtpCommand("PBSZ", "0"))); commandList.Add(new PipelineEntry(FormatFtpCommand("PROT", "P"))); } commandList.Add(new PipelineEntry(FormatFtpCommand("OPTS", "utf8 on"))); commandList.Add(new PipelineEntry(FormatFtpCommand("PWD", null))); } GetPathOption getPathOption = GetPathOption.Normal; if (request.MethodInfo.HasFlag(FtpMethodFlags.DoesNotTakeParameter)) { getPathOption = GetPathOption.AssumeNoFilename; } else if (request.MethodInfo.HasFlag(FtpMethodFlags.ParameterIsDirectory)) { getPathOption = GetPathOption.AssumeFilename; } string requestPath; string requestDirectory; string requestFilename; GetPathInfo(getPathOption, request.RequestUri, out requestPath, out requestDirectory, out requestFilename); if (requestFilename.Length == 0 && request.MethodInfo.HasFlag(FtpMethodFlags.TakesParameter)) throw new WebException(SR.net_ftp_invalid_uri); // We optimize for having the current working directory staying at the login directory. This ensure that // our relative paths work right and reduces unnecessary CWD commands. // Usually, we don't change the working directory except for some FTP commands. If necessary, // we need to reset our working directory back to the login directory. if (_establishedServerDirectory != null && _loginDirectory != null && _establishedServerDirectory != _loginDirectory) { commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", _loginDirectory), PipelineEntryFlags.UserCommand)); _requestedServerDirectory = _loginDirectory; } // For most commands, we don't need to navigate to the directory since we pass in the full // path as part of the FTP protocol command. However, some commands require it. if (request.MethodInfo.HasFlag(FtpMethodFlags.MustChangeWorkingDirectoryToPath) && requestDirectory.Length > 0) { commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", requestDirectory), PipelineEntryFlags.UserCommand)); _requestedServerDirectory = requestDirectory; } if (!request.MethodInfo.IsCommandOnly) { string requestedTypeSetting = request.UseBinary ? "I" : "A"; if (_currentTypeSetting != requestedTypeSetting) { commandList.Add(new PipelineEntry(FormatFtpCommand("TYPE", requestedTypeSetting))); _currentTypeSetting = requestedTypeSetting; } if (request.UsePassive) { string passiveCommand = (ServerAddress.AddressFamily == AddressFamily.InterNetwork) ? "PASV" : "EPSV"; commandList.Add(new PipelineEntry(FormatFtpCommand(passiveCommand, null), PipelineEntryFlags.CreateDataConnection)); } else { string portCommand = (ServerAddress.AddressFamily == AddressFamily.InterNetwork) ? "PORT" : "EPRT"; CreateFtpListenerSocket(request); commandList.Add(new PipelineEntry(FormatFtpCommand(portCommand, GetPortCommandLine(request)))); } if (request.ContentOffset > 0) { // REST command must always be the last sent before the main file command is sent. commandList.Add(new PipelineEntry(FormatFtpCommand("REST", request.ContentOffset.ToString(CultureInfo.InvariantCulture)))); } } PipelineEntryFlags flags = PipelineEntryFlags.UserCommand; if (!request.MethodInfo.IsCommandOnly) { flags |= PipelineEntryFlags.GiveDataStream; if (!request.UsePassive) flags |= PipelineEntryFlags.CreateDataConnection; } if (request.MethodInfo.Operation == FtpOperation.Rename) { string baseDir = (requestDirectory == string.Empty) ? string.Empty : requestDirectory + "/"; commandList.Add(new PipelineEntry(FormatFtpCommand("RNFR", baseDir + requestFilename), flags)); string renameTo; if (!string.IsNullOrEmpty(request.RenameTo) && request.RenameTo.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { renameTo = request.RenameTo; // Absolute path } else { renameTo = baseDir + request.RenameTo; // Relative path } commandList.Add(new PipelineEntry(FormatFtpCommand("RNTO", renameTo), flags)); } else if (request.MethodInfo.HasFlag(FtpMethodFlags.DoesNotTakeParameter)) { commandList.Add(new PipelineEntry(FormatFtpCommand(request.Method, string.Empty), flags)); } else if (request.MethodInfo.HasFlag(FtpMethodFlags.MustChangeWorkingDirectoryToPath)) { commandList.Add(new PipelineEntry(FormatFtpCommand(request.Method, requestFilename), flags)); } else { commandList.Add(new PipelineEntry(FormatFtpCommand(request.Method, requestPath), flags)); } commandList.Add(new PipelineEntry(FormatFtpCommand("QUIT", null))); return (PipelineEntry[])commandList.ToArray(typeof(PipelineEntry)); } private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream, out bool isSocketReady) { isSocketReady = false; if (_dataHandshakeStarted) { isSocketReady = true; return PipelineInstruction.Pause; //if we already started then this is re-entering into the callback where we proceed with the stream } _dataHandshakeStarted = true; // Handle passive responses by parsing the port and later doing a Connect(...) bool isPassive = false; int port = -1; if (entry.Command == "PASV\r\n" || entry.Command == "EPSV\r\n") { if (!response.PositiveCompletion) { _abortReason = SR.Format(SR.net_ftp_server_failed_passive, response.Status); return PipelineInstruction.Abort; } if (entry.Command == "PASV\r\n") { port = GetPortV4(response.StatusDescription); } else { port = GetPortV6(response.StatusDescription); } isPassive = true; } if (isPassive) { if (port == -1) { NetEventSource.Fail(this, "'port' not set."); } try { _dataSocket = CreateFtpDataSocket((FtpWebRequest)_request, Socket); } catch (ObjectDisposedException) { throw ExceptionHelper.RequestAbortedException; } IPEndPoint localEndPoint = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint).Address, 0); _dataSocket.Bind(localEndPoint); _passiveEndPoint = new IPEndPoint(ServerAddress, port); } PipelineInstruction result; if (_passiveEndPoint != null) { IPEndPoint passiveEndPoint = _passiveEndPoint; _passiveEndPoint = null; if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting Connect()"); if (_isAsync) { _dataSocket.BeginConnect(passiveEndPoint, s_connectCallbackDelegate, this); result = PipelineInstruction.Pause; } else { _dataSocket.Connect(passiveEndPoint); result = PipelineInstruction.Advance; // for passive mode we end up going to the next command } } else { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting Accept()"); if (_isAsync) { _dataSocket.BeginAccept(s_acceptCallbackDelegate, this); result = PipelineInstruction.Pause; } else { Socket listenSocket = _dataSocket; try { _dataSocket = _dataSocket.Accept(); if (!ServerAddress.Equals(((IPEndPoint)_dataSocket.RemoteEndPoint).Address)) { _dataSocket.Close(); throw new WebException(SR.net_ftp_active_address_different, WebExceptionStatus.ProtocolError); } isSocketReady = true; // for active mode we end up creating a stream before advancing the pipeline result = PipelineInstruction.Pause; } finally { listenSocket.Close(); } } } return result; } // // A door into protected CloseSocket() method // internal void Quit() { CloseSocket(); } private enum GetPathOption { Normal, AssumeFilename, AssumeNoFilename } /// <summary> /// <para>Gets the path component of the Uri</para> /// </summary> private static void GetPathInfo(GetPathOption pathOption, Uri uri, out string path, out string directory, out string filename) { path = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped); int index = path.LastIndexOf('/'); if (pathOption == GetPathOption.AssumeFilename && index != -1 && index == path.Length - 1) { // Remove last '/' and continue normal processing path = path.Substring(0, path.Length - 1); index = path.LastIndexOf('/'); } // split path into directory and filename if (pathOption == GetPathOption.AssumeNoFilename) { directory = path; filename = string.Empty; } else { directory = path.Substring(0, index + 1); filename = path.Substring(index + 1, path.Length - (index + 1)); } // strip off trailing '/' on directory if present if (directory.Length > 1 && directory[directory.Length - 1] == '/') directory = directory.Substring(0, directory.Length - 1); } // /// <summary> /// <para>Formats an IP address (contained in a UInt32) to a FTP style command string</para> /// </summary> private String FormatAddress(IPAddress address, int Port) { byte[] localAddressInBytes = address.GetAddressBytes(); // produces a string in FTP IPAddress/Port encoding (a1, a2, a3, a4, p1, p2), for sending as a parameter // to the port command. StringBuilder sb = new StringBuilder(32); foreach (byte element in localAddressInBytes) { sb.Append(element); sb.Append(','); } sb.Append(Port / 256); sb.Append(','); sb.Append(Port % 256); return sb.ToString(); } /// <summary> /// <para>Formats an IP address (v6) to a FTP style command string /// Looks something in this form: |2|1080::8:800:200C:417A|5282| <para> /// |2|4567::0123:5678:0123:5678|0123| /// </summary> private string FormatAddressV6(IPAddress address, int port) { StringBuilder sb = new StringBuilder(43); // based on max size of IPv6 address + port + seperators String addressString = address.ToString(); sb.Append("|2|"); sb.Append(addressString); sb.Append('|'); sb.Append(port.ToString(NumberFormatInfo.InvariantInfo)); sb.Append('|'); return sb.ToString(); } internal long ContentLength { get { return _contentLength; } } internal DateTime LastModified { get { return _lastModified; } } internal Uri ResponseUri { get { return _responseUri; } } /// <summary> /// <para>Returns the server message sent before user credentials are sent</para> /// </summary> internal string BannerMessage { get { return (_bannerMessage != null) ? _bannerMessage.ToString() : null; } } /// <summary> /// <para>Returns the server message sent after user credentials are sent</para> /// </summary> internal string WelcomeMessage { get { return (_welcomeMessage != null) ? _welcomeMessage.ToString() : null; } } /// <summary> /// <para>Returns the exit sent message on shutdown</para> /// </summary> internal string ExitMessage { get { return (_exitMessage != null) ? _exitMessage.ToString() : null; } } /// <summary> /// <para>Parses a response string for content length</para> /// </summary> private long GetContentLengthFrom213Response(string responseString) { string[] parsedList = responseString.Split(new char[] { ' ' }); if (parsedList.Length < 2) throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString)); return Convert.ToInt64(parsedList[1], NumberFormatInfo.InvariantInfo); } /// <summary> /// <para>Parses a response string for last modified time</para> /// </summary> private DateTime GetLastModifiedFrom213Response(string str) { DateTime dateTime = _lastModified; string[] parsedList = str.Split(new char[] { ' ', '.' }); if (parsedList.Length < 2) { return dateTime; } string dateTimeLine = parsedList[1]; if (dateTimeLine.Length < 14) { return dateTime; } int year = Convert.ToInt32(dateTimeLine.Substring(0, 4), NumberFormatInfo.InvariantInfo); int month = Convert.ToInt16(dateTimeLine.Substring(4, 2), NumberFormatInfo.InvariantInfo); int day = Convert.ToInt16(dateTimeLine.Substring(6, 2), NumberFormatInfo.InvariantInfo); int hour = Convert.ToInt16(dateTimeLine.Substring(8, 2), NumberFormatInfo.InvariantInfo); int minute = Convert.ToInt16(dateTimeLine.Substring(10, 2), NumberFormatInfo.InvariantInfo); int second = Convert.ToInt16(dateTimeLine.Substring(12, 2), NumberFormatInfo.InvariantInfo); int millisecond = 0; if (parsedList.Length > 2) { millisecond = Convert.ToInt16(parsedList[2], NumberFormatInfo.InvariantInfo); } try { dateTime = new DateTime(year, month, day, hour, minute, second, millisecond); dateTime = dateTime.ToLocalTime(); // must be handled in local time } catch (ArgumentOutOfRangeException) { } catch (ArgumentException) { } return dateTime; } /// <summary> /// <para>Attempts to find the response Uri /// Typical string looks like this, need to get trailing filename /// "150 Opening BINARY mode data connection for FTP46.tmp."</para> /// </summary> private void TryUpdateResponseUri(string str, FtpWebRequest request) { Uri baseUri = request.RequestUri; // // Not sure what we are doing here but I guess the logic is IIS centric // int start = str.IndexOf("for "); if (start == -1) return; start += 4; int end = str.LastIndexOf('('); if (end == -1) end = str.Length; if (end <= start) return; string filename = str.Substring(start, end - start); filename = filename.TrimEnd(new char[] { ' ', '.', '\r', '\n' }); // Do minimal escaping that we need to get a valid Uri // when combined with the baseUri string escapedFilename; escapedFilename = filename.Replace("%", "%25"); escapedFilename = escapedFilename.Replace("#", "%23"); // help us out if the user forgot to add a slash to the directory name string orginalPath = baseUri.AbsolutePath; if (orginalPath.Length > 0 && orginalPath[orginalPath.Length - 1] != '/') { UriBuilder uriBuilder = new UriBuilder(baseUri); uriBuilder.Path = orginalPath + "/"; baseUri = uriBuilder.Uri; } Uri newUri; if (!Uri.TryCreate(baseUri, escapedFilename, out newUri)) { throw new FormatException(SR.Format(SR.net_ftp_invalid_response_filename, filename)); } else { if (!baseUri.IsBaseOf(newUri) || baseUri.Segments.Length != newUri.Segments.Length - 1) { throw new FormatException(SR.Format(SR.net_ftp_invalid_response_filename, filename)); } else { _responseUri = newUri; } } } /// <summary> /// <para>Parses a response string for content length</para> /// </summary> private void TryUpdateContentLength(string str) { int pos1 = str.LastIndexOf("("); if (pos1 != -1) { int pos2 = str.IndexOf(" bytes)."); if (pos2 != -1 && pos2 > pos1) { pos1++; long result; if (Int64.TryParse(str.Substring(pos1, pos2 - pos1), NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { _contentLength = result; } } } } /// <summary> /// <para>Parses a response string for our login dir in " "</para> /// </summary> private string GetLoginDirectory(string str) { int firstQuote = str.IndexOf('"'); int lastQuote = str.LastIndexOf('"'); if (firstQuote != -1 && lastQuote != -1 && firstQuote != lastQuote) { return str.Substring(firstQuote + 1, lastQuote - firstQuote - 1); } else { return String.Empty; } } /// <summary> /// <para>Parses a response string for a port number</para> /// </summary> private int GetPortV4(string responseString) { string[] parsedList = responseString.Split(new char[] { ' ', '(', ',', ')' }); // We need at least the status code and the port if (parsedList.Length <= 7) { throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString)); } int index = parsedList.Length - 1; // skip the last non-number token (e.g. terminating '.') if (!Char.IsNumber(parsedList[index], 0)) index--; int port = Convert.ToByte(parsedList[index--], NumberFormatInfo.InvariantInfo); port = port | (Convert.ToByte(parsedList[index--], NumberFormatInfo.InvariantInfo) << 8); return port; } /// <summary> /// <para>Parses a response string for a port number</para> /// </summary> private int GetPortV6(string responseString) { int pos1 = responseString.LastIndexOf("("); int pos2 = responseString.LastIndexOf(")"); if (pos1 == -1 || pos2 <= pos1) throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString)); // addressInfo will contain a string of format "|||<tcp-port>|" string addressInfo = responseString.Substring(pos1 + 1, pos2 - pos1 - 1); string[] parsedList = addressInfo.Split(new char[] { '|' }); if (parsedList.Length < 4) throw new FormatException(SR.Format(SR.net_ftp_response_invalid_format, responseString)); return Convert.ToInt32(parsedList[3], NumberFormatInfo.InvariantInfo); } /// <summary> /// <para>Creates the Listener socket</para> /// </summary> private void CreateFtpListenerSocket(FtpWebRequest request) { // Gets an IPEndPoint for the local host for the data socket to bind to. IPEndPoint epListener = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint).Address, 0); try { _dataSocket = CreateFtpDataSocket(request, Socket); } catch (ObjectDisposedException) { throw ExceptionHelper.RequestAbortedException; } // Binds the data socket to the local end point. _dataSocket.Bind(epListener); _dataSocket.Listen(1); // Put the dataSocket in Listen mode } /// <summary> /// <para>Builds a command line to send to the server with proper port and IP address of client</para> /// </summary> private string GetPortCommandLine(FtpWebRequest request) { try { // retrieves the IP address of the local endpoint IPEndPoint localEP = (IPEndPoint)_dataSocket.LocalEndPoint; if (ServerAddress.AddressFamily == AddressFamily.InterNetwork) { return FormatAddress(localEP.Address, localEP.Port); } else if (ServerAddress.AddressFamily == AddressFamily.InterNetworkV6) { return FormatAddressV6(localEP.Address, localEP.Port); } else { throw new InternalException(); } } catch (Exception e) { throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ProtocolError, e); // could not open data connection } } /// <summary> /// <para>Formats a simple FTP command + parameter in correct pre-wire format</para> /// </summary> private string FormatFtpCommand(string command, string parameter) { StringBuilder stringBuilder = new StringBuilder(command.Length + ((parameter != null) ? parameter.Length : 0) + 3 /*size of ' ' \r\n*/); stringBuilder.Append(command); if (!string.IsNullOrEmpty(parameter)) { stringBuilder.Append(' '); stringBuilder.Append(parameter); } stringBuilder.Append("\r\n"); return stringBuilder.ToString(); } /// <summary> /// <para> /// This will handle either connecting to a port or listening for one /// </para> /// </summary> protected Socket CreateFtpDataSocket(FtpWebRequest request, Socket templateSocket) { // Safe to be called under an Assert. Socket socket = new Socket(templateSocket.AddressFamily, templateSocket.SocketType, templateSocket.ProtocolType); return socket; } protected override bool CheckValid(ResponseDescription response, ref int validThrough, ref int completeLength) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CheckValid({response.StatusBuffer})"); // If the response is less than 4 bytes long, it is too short to tell, so return true, valid so far. if (response.StatusBuffer.Length < 4) { return true; } string responseString = response.StatusBuffer.ToString(); // Otherwise, if there is no status code for this response yet, get one. if (response.Status == ResponseDescription.NoStatus) { // If the response does not start with three digits, then it is not a valid response from an FTP server. if (!(Char.IsDigit(responseString[0]) && Char.IsDigit(responseString[1]) && Char.IsDigit(responseString[2]) && (responseString[3] == ' ' || responseString[3] == '-'))) { return false; } else { response.StatusCodeString = responseString.Substring(0, 3); response.Status = Convert.ToInt16(response.StatusCodeString, NumberFormatInfo.InvariantInfo); } // IF a hyphen follows the status code on the first line of the response, then we have a multiline response coming. if (responseString[3] == '-') { response.Multiline = true; } } // If a complete line of response has been received from the server, then see if the // overall response is complete. // If this was not a multiline response, then the response is complete at the end of the line. // If this was a multiline response (indicated by three digits followed by a '-' in the first line), // then we see if the last line received started with the same three digits followed by a space. // If it did, then this is the sign of a complete multiline response. // If the line contained three other digits followed by the response, then this is a violation of the // FTP protocol for multiline responses. // All other cases indicate that the response is not yet complete. int index = 0; while ((index = responseString.IndexOf("\r\n", validThrough)) != -1) // gets the end line. { int lineStart = validThrough; validThrough = index + 2; // validThrough now marks the end of the line being examined. if (!response.Multiline) { completeLength = validThrough; return true; } if (responseString.Length > lineStart + 4) { // If the first three characters of the response line currently being examined // match the status code, then if they are followed by a space, then we // have reached the end of the reply. if (responseString.Substring(lineStart, 3) == response.StatusCodeString) { if (responseString[lineStart + 3] == ' ') { completeLength = validThrough; return true; } } } } return true; } /// <summary> /// <para>Determnines whether the stream we return is Writeable or Readable</para> /// </summary> private TriState IsFtpDataStreamWriteable() { FtpWebRequest request = _request as FtpWebRequest; if (request != null) { if (request.MethodInfo.IsUpload) { return TriState.True; } else if (request.MethodInfo.IsDownload) { return TriState.False; } } return TriState.Unspecified; } } // class FtpControlStream } // namespace System.Net
namespace RazorEngine.Templating { using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Security; using System.Text; using System.Threading.Tasks; using Text; #if RAZOR4 using SectionAction = System.Action<System.IO.TextWriter>; #else using SectionAction = System.Action; #endif /// <summary> /// Provides a base implementation of a template. /// NOTE: This class is not serializable to prevent subtle errors /// in user IActivator implementations which would break the sandbox. /// (because executed in the wrong <see cref="AppDomain"/>) /// </summary> public abstract class TemplateBase : ITemplate { #region Fields /// <summary> /// Because the old API (TemplateService) is designed in a way to make it impossible to init /// the model and the Viewbag at the same time (and because of backwards compatibility), /// we need to call the SetData method twice (only from within TemplateService so we can remove this bool once that has been removed). /// /// But the secound call we only need to set the Viewbag, therefore we save the state in this bool. /// </summary> private bool modelInit = false; private dynamic viewBag = null; #if RAZOR4 private AttributeInfo _attributeInfo; #endif /// <summary> /// The current context, filled when we are currently writing a template instance. /// </summary> protected ExecuteContext _context; #endregion #region Constructor /// <summary> /// Initialises a new instance of <see cref="TemplateBase"/>. /// </summary> protected TemplateBase() { } #endregion #region Properties /// <summary> /// Gets or sets the layout template name. /// </summary> public string Layout { get; set; } internal virtual Type ModelType { get { return null; } } /// <summary> /// Gets or sets the template service. /// </summary> public IInternalTemplateService InternalTemplateService { internal get; set; } /// <summary> /// Gets or sets the template service. /// </summary> [Obsolete("Only provided for backwards compatibility, use RazorEngine instead.")] public ITemplateService TemplateService { get; set; } #if RAZOR4 #else /// <summary> /// Gets or sets the current <see cref="IRazorEngineService"/> instance. /// </summary> [Obsolete("Use the Razor property instead, this is obsolete as it makes it difficult to use the RazorEngine namespace within templates.")] public IRazorEngineService RazorEngine { get { return Razor; } set { Razor = value; } } #endif /// <summary> /// Gets or sets the current <see cref="IRazorEngineService"/> instance. /// </summary> public IRazorEngineService Razor { get; set; } /// <summary> /// Gets the viewbag that allows sharing state between layout and child templates. /// </summary> public dynamic ViewBag { get { return viewBag; } } /// <summary> /// Gets the current writer. /// </summary> public TextWriter CurrentWriter { get { return _context.CurrentWriter; } } #endregion #region Methods /// <summary> /// Set the data for this template. /// </summary> /// <param name="model">the model object for the current run.</param> /// <param name="viewbag">the viewbag for the current run.</param> public virtual void SetData(object model, DynamicViewBag viewbag) { this.viewBag = viewbag ?? ViewBag ?? new DynamicViewBag(); if (!modelInit) { SetModel(model); modelInit = true; } } /// <summary> /// Set the current model. /// </summary> /// <param name="model"></param> public virtual void SetModel(object model) { } /// <summary> /// Defines a section that can written out to a layout. /// </summary> /// <param name="name">The name of the section.</param> /// <param name="action">The delegate used to write the section.</param> public void DefineSection(string name, SectionAction action) { _context.DefineSection(name, action); } /// <summary> /// Includes the template with the specified name. /// </summary> /// <param name="name">The name of the template type in cache.</param> /// <param name="model">The model or NULL if there is no model for the template.</param> /// <param name="modelType"></param> /// <returns>The template writer helper.</returns> public virtual TemplateWriter Include(string name, object model = null, Type modelType = null) { var instance = InternalTemplateService.Resolve(name, model, modelType, (DynamicViewBag)ViewBag, ResolveType.Include); if (instance == null) throw new ArgumentException("No template could be resolved with name '" + name + "'"); // TODO: make TemplateWriter async? return new TemplateWriter(tw => instance.Run( InternalTemplateService.CreateExecuteContext(), tw) #if RAZOR4 .Wait() #endif ); } /// <summary> /// Determines if the section with the specified name has been defined. /// </summary> /// <param name="name">The section name.</param> /// <returns></returns> public virtual bool IsSectionDefined(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("The name of the section to render must be specified."); return (_context.GetSectionDelegate(name) != null); } /// <summary> /// Executes the compiled template. /// </summary> #if RAZOR4 public virtual Task Execute() { return Task.FromResult(0); } #else public virtual void Execute() { } #endif /// <summary> /// Returns the specified string as a raw string. This will ensure it is not encoded. /// </summary> /// <param name="rawString">The raw string to write.</param> /// <returns>An instance of <see cref="IEncodedString"/>.</returns> public IEncodedString Raw(string rawString) { return new RawString(rawString); } /// <summary> /// Resolves the layout template. /// </summary> /// <param name="name">The name of the layout template.</param> /// <returns>An instance of <see cref="ITemplate"/>.</returns> protected virtual ITemplate ResolveLayout(string name) { return InternalTemplateService.Resolve(name, null, null, (DynamicViewBag)ViewBag, ResolveType.Layout); } private static void StreamToTextWriter(MemoryStream memory, TextWriter writer) { memory.Position = 0; using (var r = new StreamReader(memory)) { while (!r.EndOfStream) { writer.Write(r.ReadToEnd()); } } } /// <summary> /// Runs the template and returns the result. /// </summary> /// <param name="context">The current execution context.</param> /// <param name="reader"></param> /// <returns>The merged result of the template.</returns> #if RAZOR4 public async Task Run(ExecuteContext context, TextWriter reader) #else void ITemplate.Run(ExecuteContext context, TextWriter reader) #endif { _context = context; StringBuilder builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { _context.CurrentWriter = writer; #if RAZOR4 await Execute(); #else Execute(); #endif writer.Flush(); _context.CurrentWriter = null; if (Layout != null) { // Get the layout template. var layout = ResolveLayout(Layout); if (layout == null) { throw new ArgumentException("Template you are trying to run uses layout, but no layout found in cache or by resolver."); } // Push the current body instance onto the stack for later execution. var body = new TemplateWriter(tw => tw.Write(builder.ToString())); context.PushBody(body); context.PushSections(); #if RAZOR4 await layout.Run(context, reader); #else layout.Run(context, reader); #endif return; } reader.Write(builder.ToString()); } } /// <summary> /// Renders the section with the specified name. /// </summary> /// <param name="name">The name of the section.</param> /// <param name="required">Flag to specify whether the section is required.</param> /// <returns>The template writer helper.</returns> public virtual TemplateWriter RenderSection(string name, bool required = true) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("The name of the section to render must be specified."); var action = _context.GetSectionDelegate(name); if (action == null && required) throw new ArgumentException("No section has been defined with name '" + name + "'"); if (action == null) #if RAZOR4 action = (tw) => { }; #else action = () => { }; #endif return new TemplateWriter(tw => { _context.PopSections(action, tw); }); } /// <summary> /// Renders the body of the template. /// </summary> /// <returns>The template writer helper.</returns> public TemplateWriter RenderBody() { return _context.PopBody(); } /// <summary> /// Writes the specified object to the result. /// </summary> /// <param name="value">The value to write.</param> public virtual void Write(object value) { WriteTo(_context.CurrentWriter, value); } /// <summary> /// Writes the specified template helper result. /// </summary> /// <param name="helper">The template writer helper.</param> public virtual void Write(TemplateWriter helper) { if (helper == null) return; helper.WriteTo(_context.CurrentWriter); } #if !RAZOR4 /// <summary> /// Writes an attribute to the result. /// </summary> /// <param name="name">The name of the attribute.</param> /// <param name="prefix"></param> /// <param name="suffix"></param> /// <param name="values"></param> public virtual void WriteAttribute(string name, PositionTagged<string> prefix, PositionTagged<string> suffix, params AttributeValue[] values) { WriteAttributeTo(CurrentWriter, name, prefix, suffix, values); } /// <summary> /// Writes an attribute to the specified <see cref="TextWriter"/>. /// </summary> /// <param name="writer">The writer.</param> /// <param name="name">The name of the attribute to be written.</param> /// <param name="prefix"></param> /// <param name="suffix"></param> /// <param name="values"></param> public virtual void WriteAttributeTo(TextWriter writer, string name, PositionTagged<string> prefix, PositionTagged<string> suffix, params AttributeValue[] values) { if (writer == null) throw new ArgumentNullException(nameof(writer)); bool first = true; bool wroteSomething = false; if (values.Length == 0) { // Explicitly empty attribute, so write the prefix and suffix WritePositionTaggedLiteral(writer, prefix); WritePositionTaggedLiteral(writer, suffix); } else { for (int i = 0; i < values.Length; i++) { AttributeValue attrVal = values[i]; PositionTagged<object> val = attrVal.Value; bool? boolVal = null; if (val.Value is bool) { boolVal = (bool)val.Value; } if (val.Value != null && (boolVal == null || boolVal.Value)) { string valStr = val.Value as string; string valToString = valStr; if (valStr == null) { valToString = val.Value.ToString(); } if (boolVal != null) { Debug.Assert(boolVal.Value); valToString = name; } if (first) { WritePositionTaggedLiteral(writer, prefix); first = false; } else { WritePositionTaggedLiteral(writer, attrVal.Prefix); } if (attrVal.Literal) { WriteLiteralTo(writer, valToString); } else { if (val.Value is IEncodedString && boolVal == null) { WriteTo(writer, val.Value); // Write value } else { WriteTo(writer, valToString); // Write value } } wroteSomething = true; } } if (wroteSomething) { WritePositionTaggedLiteral(writer, suffix); } } } #endif #if RAZOR4 /// <summary> /// Writes the specified attribute name to the result. /// </summary> /// <param name="name">The name.</param> /// <param name="prefix">The prefix.</param> /// <param name="prefixOffset">The prefix offset.</param> /// <param name="suffix">The suffix.</param> /// <param name="suffixOffset">The suffix offset</param> /// <param name="attributeValuesCount">The attribute values count.</param> public virtual void BeginWriteAttribute(string name, string prefix, int prefixOffset, string suffix, int suffixOffset, int attributeValuesCount) { BeginWriteAttributeTo(_context.CurrentWriter, name, prefix, prefixOffset, suffix, suffixOffset, attributeValuesCount); } /// <summary> /// Writes the specified attribute name to the specified <see cref="TextWriter"/>. /// </summary> /// <param name="writer">The writer.</param> /// <param name="name">The name.</param> /// <param name="prefix">The prefix.</param> /// <param name="prefixOffset">The prefix offset.</param> /// <param name="suffix">The suffix.</param> /// <param name="suffixOffset">The suffix offset</param> /// <param name="attributeValuesCount">The attribute values count.</param> public virtual void BeginWriteAttributeTo(TextWriter writer, string name, string prefix, int prefixOffset, string suffix, int suffixOffset, int attributeValuesCount) { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (prefix == null) throw new ArgumentNullException(nameof(prefix)); if (suffix == null) throw new ArgumentNullException(nameof(suffix)); _attributeInfo = new AttributeInfo(name, prefix, prefixOffset, suffix, suffixOffset, attributeValuesCount); // Single valued attributes might be omitted in entirety if it the attribute value strictly evaluates to // null or false. Consequently defer the prefix generation until we encounter the attribute value. if (attributeValuesCount != 1) { WritePositionTaggedLiteral(writer, prefix, prefixOffset); } } /// <summary> /// Writes the specified attribute value to the result. /// </summary> /// <param name="prefix">The prefix.</param> /// <param name="prefixOffset">The prefix offset.</param> /// <param name="value">The value.</param> /// <param name="valueOffset">The value offset.</param> /// <param name="valueLength">The value length.</param> /// <param name="isLiteral">The is literal.</param> public void WriteAttributeValue(string prefix, int prefixOffset, object value, int valueOffset, int valueLength, bool isLiteral) { WriteAttributeValueTo(_context.CurrentWriter, prefix, prefixOffset, value, valueOffset, valueLength, isLiteral); } /// <summary> /// Writes the specified attribute value to the specified <see cref="TextWriter"/>. /// </summary> /// <param name="writer">The writer.</param> /// <param name="prefix">The prefix.</param> /// <param name="prefixOffset">The prefix offset.</param> /// <param name="value">The value.</param> /// <param name="valueOffset">The value offset.</param> /// <param name="valueLength">The value length.</param> /// <param name="isLiteral">The is literal.</param> public void WriteAttributeValueTo(TextWriter writer, string prefix, int prefixOffset, object value, int valueOffset, int valueLength, bool isLiteral) { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (_attributeInfo.AttributeValuesCount == 1) { if (IsBoolFalseOrNullValue(prefix, value)) { // Value is either null or the bool 'false' with no prefix; don't render the attribute. _attributeInfo.Suppressed = true; return; } // We are not omitting the attribute. Write the prefix. WritePositionTaggedLiteral(writer, _attributeInfo.Prefix, _attributeInfo.PrefixOffset); if (IsBoolTrueWithEmptyPrefixValue(prefix, value)) { // The value is just the bool 'true', write the attribute name instead of the string 'True'. value = _attributeInfo.Name; } } // This block handles two cases. // 1. Single value with prefix. // 2. Multiple values with or without prefix. if (value != null) { if (!string.IsNullOrEmpty(prefix)) { WritePositionTaggedLiteral(writer, prefix, prefixOffset); } WriteUnprefixedAttributeValueTo(writer, value, isLiteral); } } /// <summary> /// Writes the attribute end to the result. /// </summary> public virtual void EndWriteAttribute() { EndWriteAttributeTo(_context.CurrentWriter); } /// <summary> /// Writes the attribute end to the specified <see cref="TextWriter"/>. /// </summary> /// <param name="writer">The writer.</param> public virtual void EndWriteAttributeTo(TextWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (!_attributeInfo.Suppressed) { WritePositionTaggedLiteral(writer, _attributeInfo.Suffix, _attributeInfo.SuffixOffset); } } private void WritePositionTaggedLiteral(TextWriter writer, string value, int position) { WriteLiteralTo(writer, value); } private void WriteUnprefixedAttributeValueTo(TextWriter writer, object value, bool isLiteral) { var stringValue = value as string; // The extra branching here is to ensure that we call the Write*To(string) overload where possible. if (isLiteral && stringValue != null) { WriteLiteralTo(writer, stringValue); } else if (isLiteral) { WriteLiteralTo(writer, value); } else if (stringValue != null) { WriteTo(writer, stringValue); } else { WriteTo(writer, value); } } private bool IsBoolFalseOrNullValue(string prefix, object value) { return string.IsNullOrEmpty(prefix) && (value == null || (value is bool && !(bool)value)); } private bool IsBoolTrueWithEmptyPrefixValue(string prefix, object value) { // If the value is just the bool 'true', use the attribute name as the value. return string.IsNullOrEmpty(prefix) && (value is bool && (bool)value); } #endif /// <summary> /// Writes the specified string to the result. /// </summary> /// <param name="literal">The literal to write.</param> public virtual void WriteLiteral(string literal) { WriteLiteralTo(_context.CurrentWriter, literal); } #if RAZOR4 /// <summary> /// Writes the specified object to the result. /// </summary> /// <param name="literal">The literal to write.</param> public virtual void WriteLiteral(object literal) { WriteLiteralTo(_context.CurrentWriter, literal); } #endif /// <summary> /// Writes a string literal to the specified <see cref="TextWriter"/>. /// </summary> /// <param name="writer">The writer.</param> /// <param name="literal">The literal to be written.</param> public virtual void WriteLiteralTo(TextWriter writer, string literal) { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (literal == null) return; writer.Write(literal); } #if RAZOR4 /// <summary> /// Writes a string literal to the specified <see cref="TextWriter"/>. /// </summary> /// <param name="writer">The writer.</param> /// <param name="literal">The literal to be written.</param> public virtual void WriteLiteralTo(TextWriter writer, object literal) { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (literal != null) { WriteLiteralTo(writer, literal.ToString()); } } #endif /// <summary> /// Writes a <see cref="PositionTagged{T}" /> literal to the result. /// </summary> /// <param name="writer">The writer.</param> /// <param name="value">The literal to be written.</param> private void WritePositionTaggedLiteral(TextWriter writer, PositionTagged<string> value) { WriteLiteralTo(writer, value.Value); } /// <summary> /// Writes the specified object to the specified <see cref="TextWriter"/>. /// </summary> /// <param name="writer">The writer.</param> /// <param name="value">The value to be written.</param> public virtual void WriteTo(TextWriter writer, object value) { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (value == null) return; if (value is IEncodedString) { writer.Write(value); } else { var encodedString = InternalTemplateService.EncodedStringFactory.CreateEncodedString(value); writer.Write(encodedString); } } #if RAZOR4 /// <summary> /// Writes the specified string to the result. /// </summary> /// <param name="writer">The writer.</param> /// <param name="value">The value to be written.</param> public virtual void WriteTo(TextWriter writer, string value) { if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.Write(value); } #endif /// <summary> /// Writes the specfied template helper result to the specified writer. /// </summary> /// <param name="writer">The writer.</param> /// <param name="helper">The template writer helper.</param> public virtual void WriteTo(TextWriter writer, TemplateWriter helper) { if (helper == null) return; helper.WriteTo(writer); } #if !RAZOR4 /// <summary> /// Resolves the specified path /// </summary> /// <param name="path">The path.</param> /// <returns>The resolved path.</returns> public virtual string ResolveUrl(string path) { // TODO: Actually resolve the url if (path.StartsWith("~")) { path = path.Substring(1); } return path; } #endif #endregion #if RAZOR4 private struct AttributeInfo { public AttributeInfo( string name, string prefix, int prefixOffset, string suffix, int suffixOffset, int attributeValuesCount) { Name = name; Prefix = prefix; PrefixOffset = prefixOffset; Suffix = suffix; SuffixOffset = suffixOffset; AttributeValuesCount = attributeValuesCount; Suppressed = false; } public int AttributeValuesCount { get; } public string Name { get; } public string Prefix { get; } public int PrefixOffset { get; } public string Suffix { get; } public int SuffixOffset { get; } public bool Suppressed { get; set; } } #endif } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Threading; using System.Timers; using Message; #endregion /// <summary> /// Implements SIP client transaction. Defined in rfc 3261 17.1. /// </summary> public class SIP_ClientTransaction : SIP_Transaction { #region Events /// <summary> /// Is raised when transaction received response from remote party. /// </summary> public event EventHandler<SIP_ResponseReceivedEventArgs> ResponseReceived = null; #endregion #region Members private bool m_IsCanceling; private TimerEx m_pTimerA; private TimerEx m_pTimerB; private TimerEx m_pTimerD; private TimerEx m_pTimerE; private TimerEx m_pTimerF; private TimerEx m_pTimerK; private int m_RSeq = -1; #endregion #region Properties /// <summary> /// Gets or sets RSeq value. Value -1 means no reliable provisional response received. /// </summary> internal int RSeq { get { return m_RSeq; } set { m_RSeq = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Owner SIP stack.</param> /// <param name="flow">SIP data flow which is used to send request.</param> /// <param name="request">SIP request that transaction will handle.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>flow</b> or <b>request</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> internal SIP_ClientTransaction(SIP_Stack stack, SIP_Flow flow, SIP_Request request) : base(stack, flow, request) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] created."); } SetState(SIP_TransactionState.WaitingToStart); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public override void Dispose() { lock (SyncRoot) { if (IsDisposed) { return; } // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] disposed."); } // Kill timers. if (m_pTimerA != null) { m_pTimerA.Dispose(); m_pTimerA = null; } if (m_pTimerB != null) { m_pTimerB.Dispose(); m_pTimerB = null; } if (m_pTimerD != null) { m_pTimerD.Dispose(); m_pTimerD = null; } if (m_pTimerE != null) { m_pTimerE.Dispose(); m_pTimerE = null; } if (m_pTimerF != null) { m_pTimerF.Dispose(); m_pTimerF = null; } if (m_pTimerK != null) { m_pTimerK.Dispose(); m_pTimerK = null; } ResponseReceived = null; base.Dispose(); } } /// <summary> /// Starts transaction processing. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>Start</b> is called other state than 'WaitingToStart'.</exception> public void Start() { lock (SyncRoot) { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } else if (State != SIP_TransactionState.WaitingToStart) { throw new InvalidOperationException( "Start method is valid only in 'WaitingToStart' state."); } // Move processing to thread pool. ThreadPool.QueueUserWorkItem(delegate { lock (SyncRoot) { #region INVITE if (Method == SIP_Methods.INVITE) { /* RFC 3261 17.1.1.2. The initial state, "calling", MUST be entered when the TU initiates a new client transaction with an INVITE request. The client transaction MUST pass the request to the transport layer for transmission (see Section 18). If an unreliable transport is being used, the client transaction MUST start timer A with a value of T1. If a reliable transport is being used, the client transaction SHOULD NOT start timer A (Timer A controls request retransmissions). For any transport, the client transaction MUST start timer B with a value of 64*T1 seconds (Timer B controls transaction timeouts). */ SetState(SIP_TransactionState.Calling); try { // Send initial request. Stack.TransportLayer.SendRequest(Flow, Request, this); } catch (Exception x) { OnTransportError(x); // NOTE: TransportError event handler could Dispose this transaction, so we need to check it. if (State != SIP_TransactionState.Disposed) { SetState(SIP_TransactionState.Terminated); } return; } // Start timer A for unreliable transports. if (!Flow.IsReliable) { m_pTimerA = new TimerEx( SIP_TimerConstants.T1, false); m_pTimerA.Elapsed += m_pTimerA_Elapsed; m_pTimerA.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer A(INVITE request retransmission) started, will triger after " + m_pTimerA.Interval + "."); } } // Start timer B. m_pTimerB = new TimerEx( 64*SIP_TimerConstants.T1, false); m_pTimerB.Elapsed += m_pTimerB_Elapsed; m_pTimerB.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer B(INVITE calling state timeout) started, will triger after " + m_pTimerB.Interval + "."); } } #endregion #region Non-INVITE else { /* RFC 3261 17.1.2.2. The "Trying" state is entered when the TU initiates a new client transaction with a request. When entering this state, the client transaction SHOULD set timer F to fire in 64*T1 seconds. The request MUST be passed to the transport layer for transmission. If an unreliable transport is in use, the client transaction MUST set timer E to fire in T1 seconds. */ SetState(SIP_TransactionState.Trying); // Start timer F. m_pTimerF = new TimerEx( 64*SIP_TimerConstants.T1, false); m_pTimerF.Elapsed += m_pTimerF_Elapsed; m_pTimerF.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer F(Non-INVITE trying,proceeding state timeout) started, will triger after " + m_pTimerF.Interval + "."); } try { // Send initial request. Stack.TransportLayer.SendRequest(Flow, Request, this); } catch (Exception x) { OnTransportError(x); // NOTE: TransportError event handler could Dispose this transaction, so we need to check it. if (State != SIP_TransactionState.Disposed) { SetState(SIP_TransactionState.Terminated); } return; } // Start timer E for unreliable transports. if (!Flow.IsReliable) { m_pTimerE = new TimerEx( SIP_TimerConstants.T1, false); m_pTimerE.Elapsed += m_pTimerE_Elapsed; m_pTimerE.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer E(Non-INVITE request retransmission) started, will triger after " + m_pTimerE.Interval + "."); } } } #endregion } }); } } /// <summary> /// Starts canceling transaction. /// </summary> /// <remarks>If client transaction has got final response, canel has no effect and will be ignored.</remarks> /// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception> public override void Cancel() { lock (SyncRoot) { if (State == SIP_TransactionState.Disposed) { throw new ObjectDisposedException(GetType().Name); } else if (State == SIP_TransactionState.WaitingToStart) { SetState(SIP_TransactionState.Terminated); return; } else if (m_IsCanceling) { return; } else if (State == SIP_TransactionState.Terminated) { // RFC 3261 9.1. We got final response, nothing to cancel. return; } if (FinalResponse != null) { return; } m_IsCanceling = true; /* RFC 3261 9.1. If no provisional response has been received, the CANCEL request MUST NOT be sent; rather, the client MUST wait for the arrival of a provisional response before sending the request. */ if (Responses.Length == 0) { // We set canceling flag, so if provisional response arrives, we do cancel. } else { SendCancel(); } } } #endregion #region Event handlers /// <summary> /// Is raised when INVITE timer A triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerA_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 17.1.1.2. When timer A fires, the client transaction MUST retransmit the request by passing it to the transport layer, and MUST reset the timer with a value of 2*T1. The formal definition of retransmit within the context of the transaction layer is to take the message previously sent to the transport layer and pass it to the transport layer once more. When timer A fires 2*T1 seconds later, the request MUST be retransmitted again (assuming the client transaction is still in this state). This process MUST continue so that the request is retransmitted with intervals that double after each transmission. These retransmissions SHOULD only be done while the client transaction is in the "calling" state. */ lock (SyncRoot) { if (State == SIP_TransactionState.Calling) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer A(INVITE request retransmission) triggered."); } try { // Retransmit request. Stack.TransportLayer.SendRequest(Flow, Request, this); } catch (Exception x) { OnTransportError(x); SetState(SIP_TransactionState.Terminated); return; } // Update(double current) next transmit time. m_pTimerA.Interval *= 2; m_pTimerA.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer A(INVITE request retransmission) updated, will triger after " + m_pTimerA.Interval + "."); } } } } /// <summary> /// Is raised when INVITE timer B triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerB_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 17.1.1.2. If the client transaction is still in the "Calling" state when timer B fires, the client transaction SHOULD inform the TU that a timeout has occurred. The client transaction MUST NOT generate an ACK. The value of 64*T1 is equal to the amount of time required to send seven requests in the case of an unreliable transport. */ lock (SyncRoot) { if (State == SIP_TransactionState.Calling) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer B(INVITE calling state timeout) triggered."); } OnTimedOut(); SetState(SIP_TransactionState.Terminated); // Stop timers A,B. if (m_pTimerA != null) { m_pTimerA.Dispose(); m_pTimerA = null; } if (m_pTimerB != null) { m_pTimerB.Dispose(); m_pTimerB = null; } } } } /// <summary> /// Is raised when INVITE timer D triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerD_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 17.1.1.2. If timer D fires while the client transaction is in the "Completed" state, the client transaction MUST move to the terminated state. */ lock (SyncRoot) { if (State == SIP_TransactionState.Completed) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer D(INVITE 3xx - 6xx response retransmission wait) triggered."); } SetState(SIP_TransactionState.Terminated); } } } /// <summary> /// Is raised when Non-INVITE timer E triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerE_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 17.1.2.2. If timer E fires while in Trying state, the timer is reset, but this time with a value of MIN(2*T1, T2). When the timer fires again, it is reset to a MIN(4*T1, T2). This process continues so that retransmissions occur with an exponentially increasing interval that caps at T2. The default value of T2 is 4s, and it represents the amount of time a non-INVITE server transaction will take to respond to a request, if it does not respond immediately. For the default values of T1 and T2, this results in intervals of 500 ms, 1 s, 2 s, 4 s, 4 s, 4 s, etc. */ lock (SyncRoot) { if (State == SIP_TransactionState.Trying) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer E(-NonINVITE request retransmission) triggered."); } try { // Retransmit request. Stack.TransportLayer.SendRequest(Flow, Request, this); } catch (Exception x) { OnTransportError(x); SetState(SIP_TransactionState.Terminated); return; } // Update(double current) next transmit time. m_pTimerE.Interval = Math.Min(m_pTimerE.Interval*2, SIP_TimerConstants.T2); m_pTimerE.Enabled = true; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer E(Non-INVITE request retransmission) updated, will triger after " + m_pTimerE.Interval + "."); } } } } /// <summary> /// Is raised when Non-INVITE timer F triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerF_Elapsed(object sender, ElapsedEventArgs e) { /* RFC 3261 17.1.2.2. If Timer F fires while in the "Trying" state, the client transaction SHOULD inform the TU about the timeout, and then it SHOULD enter the "Terminated" state. If timer F fires while in the "Proceeding" state, the TU MUST be informed of a timeout, and the client transaction MUST transition to the terminated state. */ lock (SyncRoot) { if (State == SIP_TransactionState.Trying || State == SIP_TransactionState.Proceeding) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer F(Non-INVITE trying,proceeding state timeout) triggered."); } OnTimedOut(); SetState(SIP_TransactionState.Terminated); if (m_pTimerE != null) { m_pTimerE.Dispose(); m_pTimerE = null; } if (m_pTimerF != null) { m_pTimerF.Dispose(); m_pTimerF = null; } } } } /// <summary> /// Is raised when Non-INVITE timer K triggered. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pTimerK_Elapsed(object sender, ElapsedEventArgs e) { lock (SyncRoot) { if (State == SIP_TransactionState.Completed) { // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer K(Non-INVITE 3xx - 6xx response retransmission wait) triggered."); } SetState(SIP_TransactionState.Terminated); } } } #endregion #region Utility methods /// <summary> /// Creates and send CANCEL request to remote target. /// </summary> private void SendCancel() { /* RFC 3261 9.1. The following procedures are used to construct a CANCEL request. The Request-URI, Call-ID, To, the numeric part of CSeq, and From header fields in the CANCEL request MUST be identical to those in the request being cancelled, including tags. A CANCEL constructed by a client MUST have only a single Via header field value matching the top Via value in the request being cancelled. Using the same values for these header fields allows the CANCEL to be matched with the request it cancels (Section 9.2 indicates how such matching occurs). However, the method part of the CSeq header field MUST have a value of CANCEL. This allows it to be identified and processed as a transaction in its own right (See Section 17). If the request being cancelled contains a Route header field, the CANCEL request MUST include that Route header field's values. This is needed so that stateless proxies are able to route CANCEL requests properly. */ SIP_Request cancelRequest = new SIP_Request(SIP_Methods.CANCEL); cancelRequest.RequestLine.Uri = Request.RequestLine.Uri; cancelRequest.Via.Add(Request.Via.GetTopMostValue().ToStringValue()); cancelRequest.CallID = Request.CallID; cancelRequest.From = Request.From; cancelRequest.To = Request.To; cancelRequest.CSeq = new SIP_t_CSeq(Request.CSeq.SequenceNumber, SIP_Methods.CANCEL); foreach (SIP_t_AddressParam route in Request.Route.GetAllValues()) { cancelRequest.Route.Add(route.ToStringValue()); } cancelRequest.MaxForwards = 70; // We must use same data flow to send CANCEL what sent initial request. SIP_ClientTransaction transaction = Stack.TransactionLayer.CreateClientTransaction(Flow, cancelRequest, false); transaction.Start(); } /// <summary> /// Creates and sends ACK for final(3xx - 6xx) failure response. /// </summary> /// <param name="response">SIP response.</param> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null.</exception> private void SendAck(SIP_Response response) { if (response == null) { throw new ArgumentNullException("resposne"); } /* RFC 3261 17.1.1.3 Construction of the ACK Request. The ACK request constructed by the client transaction MUST contain values for the Call-ID, From, and Request-URI that are equal to the values of those header fields in the request passed to the transport by the client transaction (call this the "original request"). The To header field in the ACK MUST equal the To header field in the response being acknowledged, and therefore will usually differ from the To header field in the original request by the addition of the tag parameter. The ACK MUST contain a single Via header field, and this MUST be equal to the top Via header field of the original request. The CSeq header field in the ACK MUST contain the same value for the sequence number as was present in the original request, but the method parameter MUST be equal to "ACK". If the INVITE request whose response is being acknowledged had Route header fields, those header fields MUST appear in the ACK. This is to ensure that the ACK can be routed properly through any downstream stateless proxies. */ SIP_Request ackRequest = new SIP_Request(SIP_Methods.ACK); ackRequest.RequestLine.Uri = Request.RequestLine.Uri; ackRequest.Via.AddToTop(Request.Via.GetTopMostValue().ToStringValue()); ackRequest.CallID = Request.CallID; ackRequest.From = Request.From; ackRequest.To = response.To; ackRequest.CSeq = new SIP_t_CSeq(Request.CSeq.SequenceNumber, "ACK"); foreach (SIP_HeaderField h in response.Header.Get("Route:")) { ackRequest.Header.Add("Route:", h.Value); } ackRequest.MaxForwards = 70; try { // Send request to target. Stack.TransportLayer.SendRequest(Flow, ackRequest, this); } catch (SIP_TransportException x) { OnTransportError(x); SetState(SIP_TransactionState.Terminated); } } // FIX ME: /// <summary> /// Raises ResponseReceived event. /// </summary> /// <param name="response">SIP response received.</param> private void OnResponseReceived(SIP_Response response) { if (ResponseReceived != null) { ResponseReceived(this, new SIP_ResponseReceivedEventArgs(Stack, this, response)); } } #endregion #region Internal methods /// <summary> /// Processes specified response through this transaction. /// </summary> /// <param name="flow">SIP data flow what received response.</param> /// <param name="response">SIP response to process.</param> /// <exception cref="ArgumentNullException">Is raised when <b>flow</b>,<b>response</b> is null reference.</exception> internal void ProcessResponse(SIP_Flow flow, SIP_Response response) { if (flow == null) { throw new ArgumentNullException("flow"); } if (response == null) { throw new ArgumentNullException("response"); } lock (SyncRoot) { if (State == SIP_TransactionState.Disposed) { return; } /* RFC 3261 9.1. CANCEL. *) If provisional response, send CANCEL, we should get '478 Request terminated'. *) If final response, skip canceling, nothing to cancel. */ else if (m_IsCanceling && response.StatusCodeType == SIP_StatusCodeType.Provisional) { SendCancel(); return; } // Log if (Stack.Logger != null) { byte[] responseData = response.ToByteData(); Stack.Logger.AddRead(Guid.NewGuid().ToString(), null, 0, "Response [transactionID='" + ID + "'; method='" + response.CSeq.RequestMethod + "'; cseq='" + response.CSeq.SequenceNumber + "'; " + "transport='" + flow.Transport + "'; size='" + responseData.Length + "'; statusCode='" + response.StatusCode + "'; " + "reason='" + response.ReasonPhrase + "'; received '" + flow.LocalEP + "' <- '" + flow.RemoteEP + "'.", flow.LocalEP, flow.RemoteEP, responseData); } #region INVITE /* RFC 3261 17.1.1.2. |INVITE from TU Timer A fires |INVITE sent Reset A, V Timer B fires INVITE sent +-----------+ or Transport Err. +---------| |---------------+inform TU | | Calling | | +-------->| |-------------->| +-----------+ 2xx | | | 2xx to TU | | |1xx | 300-699 +---------------+ |1xx to TU | ACK sent | | | resp. to TU | 1xx V | | 1xx to TU -----------+ | | +---------| | | | | |Proceeding |-------------->| | +-------->| | 2xx | | +-----------+ 2xx to TU | | 300-699 | | | ACK sent, | | | resp. to TU| | | | | NOTE: | 300-699 V | | ACK sent +-----------+Transport Err. | transitions | +---------| |Inform TU | labeled with | | | Completed |-------------->| the event | +-------->| | | over the action | +-----------+ | to take | ^ | | | | | Timer D fires | +--------------+ | - | | | V | +-----------+ | | | | | Terminated|<--------------+ | | +-----------+ */ if (Method == SIP_Methods.INVITE) { #region Calling if (State == SIP_TransactionState.Calling) { // Store response. AddResponse(response); // Stop timer A,B if (m_pTimerA != null) { m_pTimerA.Dispose(); m_pTimerA = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer A(INVITE request retransmission) stoped."); } } if (m_pTimerB != null) { m_pTimerB.Dispose(); m_pTimerB = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer B(INVITE calling state timeout) stoped."); } } // 1xx response. if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { OnResponseReceived(response); SetState(SIP_TransactionState.Proceeding); } // 2xx response. else if (response.StatusCodeType == SIP_StatusCodeType.Success) { OnResponseReceived(response); SetState(SIP_TransactionState.Terminated); } // 3xx - 6xx response. else { SendAck(response); OnResponseReceived(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 17.1.1.2. The client transaction SHOULD start timer D when it enters the "Completed" state, with a value of at least 32 seconds for unreliable transports, and a value of zero seconds for reliable transports. */ m_pTimerD = new TimerEx(Flow.IsReliable ? 0 : Workaround.Definitions.MaxStreamLineLength, false); m_pTimerD.Elapsed += m_pTimerD_Elapsed; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer D(INVITE 3xx - 6xx response retransmission wait) started, will triger after " + m_pTimerD.Interval + "."); } m_pTimerD.Enabled = true; } } #endregion #region Proceeding else if (State == SIP_TransactionState.Proceeding) { // Store response. AddResponse(response); // 1xx response. if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { OnResponseReceived(response); } // 2xx response. else if (response.StatusCodeType == SIP_StatusCodeType.Success) { OnResponseReceived(response); SetState(SIP_TransactionState.Terminated); } // 3xx - 6xx response. else { SendAck(response); OnResponseReceived(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 17.1.1.2. The client transaction SHOULD start timer D when it enters the "Completed" state, with a value of at least 32 seconds for unreliable transports, and a value of zero seconds for reliable transports. */ m_pTimerD = new TimerEx(Flow.IsReliable ? 0 : Workaround.Definitions.MaxStreamLineLength, false); m_pTimerD.Elapsed += m_pTimerD_Elapsed; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer D(INVITE 3xx - 6xx response retransmission wait) started, will triger after " + m_pTimerD.Interval + "."); } m_pTimerD.Enabled = true; } } #endregion #region Completed else if (State == SIP_TransactionState.Completed) { // 3xx - 6xx if (response.StatusCode >= 300) { SendAck(response); } } #endregion #region Terminated else if (State == SIP_TransactionState.Terminated) { // We should never reach here, but if so, do nothing. } #endregion } #endregion #region Non-INVITE /* RFC 3251 17.1.2.2 |Request from TU |send request Timer E V send request +-----------+ +---------| |-------------------+ | | Trying | Timer F | +-------->| | or Transport Err.| +-----------+ inform TU | 200-699 | | | resp. to TU | |1xx | +---------------+ |resp. to TU | | | | | Timer E V Timer F | | send req +-----------+ or Transport Err. | | +---------| | inform TU | | | |Proceeding |------------------>| | +-------->| |-----+ | | +-----------+ |1xx | | | ^ |resp to TU | | 200-699 | +--------+ | | resp. to TU | | | | | | V | | +-----------+ | | | | | | | Completed | | | | | | | +-----------+ | | ^ | | | | | Timer K | +--------------+ | - | | | V | NOTE: +-----------+ | | | | transitions | Terminated|<------------------+ labeled with | | the event +-----------+ over the action to take */ else { #region Trying if (State == SIP_TransactionState.Trying) { // Store response. AddResponse(response); // Stop timer E if (m_pTimerE != null) { m_pTimerE.Dispose(); m_pTimerE = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer E(Non-INVITE request retransmission) stoped."); } } // 1xx response. if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { OnResponseReceived(response); SetState(SIP_TransactionState.Proceeding); } // 2xx - 6xx response. else { // Stop timer F if (m_pTimerF != null) { m_pTimerF.Dispose(); m_pTimerF = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer F(Non-INVITE trying,proceeding state timeout) stoped."); } } OnResponseReceived(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 17.1.2.2. The client transaction enters the "Completed" state, it MUST set Timer K to fire in T4 seconds for unreliable transports, and zero seconds for reliable transports. */ m_pTimerK = new TimerEx(Flow.IsReliable ? 1 : SIP_TimerConstants.T4, false); m_pTimerK.Elapsed += m_pTimerK_Elapsed; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer K(Non-INVITE 3xx - 6xx response retransmission wait) started, will triger after " + m_pTimerK.Interval + "."); } m_pTimerK.Enabled = true; } } #endregion #region Proceeding else if (State == SIP_TransactionState.Proceeding) { // Store response. AddResponse(response); // 1xx response. if (response.StatusCodeType == SIP_StatusCodeType.Provisional) { OnResponseReceived(response); } // 2xx - 6xx response. else { // Stop timer F if (m_pTimerF != null) { m_pTimerF.Dispose(); m_pTimerF = null; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer F(Non-INVITE trying,proceeding state timeout) stoped."); } } OnResponseReceived(response); SetState(SIP_TransactionState.Completed); /* RFC 3261 17.1.2.2. The client transaction enters the "Completed" state, it MUST set Timer K to fire in T4 seconds for unreliable transports, and zero seconds for reliable transports. */ m_pTimerK = new TimerEx(Flow.IsReliable ? 0 : SIP_TimerConstants.T4, false); m_pTimerK.Elapsed += m_pTimerK_Elapsed; // Log if (Stack.Logger != null) { Stack.Logger.AddText(ID, "Transaction [branch='" + ID + "';method='" + Method + "';IsServer=false] timer K(Non-INVITE 3xx - 6xx response retransmission wait) started, will triger after " + m_pTimerK.Interval + "."); } m_pTimerK.Enabled = true; } } #endregion #region Completed else if (State == SIP_TransactionState.Completed) { // Eat retransmited response. } #endregion #region Terminated else if (State == SIP_TransactionState.Terminated) { // We should never reach here, but if so, do nothing. } #endregion } #endregion } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; namespace OpenSim.Tests.Common { /// <summary> /// Utility functions for carrying out user inventory tests. /// </summary> public static class UserInventoryHelpers { public static readonly string PATH_DELIMITER = "/"; /// <summary> /// Add an existing scene object as an item in the user's inventory. /// </summary> /// <remarks> /// Will be added to the system Objects folder. /// </remarks> /// <param name='scene'></param> /// <param name='so'></param> /// <param name='inventoryIdTail'></param> /// <param name='assetIdTail'></param> /// <returns>The inventory item created.</returns> public static InventoryItemBase AddInventoryItem( Scene scene, SceneObjectGroup so, int inventoryIdTail, int assetIdTail) { return AddInventoryItem( scene, so.Name, TestHelpers.ParseTail(inventoryIdTail), InventoryType.Object, AssetHelpers.CreateAsset(TestHelpers.ParseTail(assetIdTail), so), so.OwnerID); } /// <summary> /// Add an existing scene object as an item in the user's inventory at the given path. /// </summary> /// <param name='scene'></param> /// <param name='so'></param> /// <param name='inventoryIdTail'></param> /// <param name='assetIdTail'></param> /// <returns>The inventory item created.</returns> public static InventoryItemBase AddInventoryItem( Scene scene, SceneObjectGroup so, int inventoryIdTail, int assetIdTail, string path) { return AddInventoryItem( scene, so.Name, TestHelpers.ParseTail(inventoryIdTail), InventoryType.Object, AssetHelpers.CreateAsset(TestHelpers.ParseTail(assetIdTail), so), so.OwnerID, path); } /// <summary> /// Adds the given item to the existing system folder for its type (e.g. an object will go in the "Objects" /// folder). /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="itemType"></param> /// <param name="asset">The serialized asset for this item</param> /// <param name="userId"></param> /// <returns></returns> private static InventoryItemBase AddInventoryItem( Scene scene, string itemName, UUID itemId, InventoryType itemType, AssetBase asset, UUID userId) { return AddInventoryItem( scene, itemName, itemId, itemType, asset, userId, scene.InventoryService.GetFolderForType(userId, (AssetType)asset.Type).Name); } /// <summary> /// Adds the given item to an inventory folder /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="itemType"></param> /// <param name="asset">The serialized asset for this item</param> /// <param name="userId"></param> /// <param name="path">Existing inventory path at which to add.</param> /// <returns></returns> private static InventoryItemBase AddInventoryItem( Scene scene, string itemName, UUID itemId, InventoryType itemType, AssetBase asset, UUID userId, string path) { scene.AssetService.Store(asset); InventoryItemBase item = new InventoryItemBase(); item.Name = itemName; item.AssetID = asset.FullID; item.ID = itemId; item.Owner = userId; item.AssetType = asset.Type; item.InvType = (int)itemType; InventoryFolderBase folder = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, userId, path)[0]; item.Folder = folder.ID; scene.AddInventoryItem(item); return item; } /// <summary> /// Creates a notecard in the objects folder and specify an item id. /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="userId"></param> /// <returns></returns> public static InventoryItemBase CreateInventoryItem(Scene scene, string itemName, UUID userId) { return CreateInventoryItem(scene, itemName, UUID.Random(), UUID.Random(), userId, InventoryType.Notecard); } /// <summary> /// Creates an item of the given type with an accompanying asset. /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="userId"></param> /// <param name="type">Type of item to create</param> /// <returns></returns> public static InventoryItemBase CreateInventoryItem( Scene scene, string itemName, UUID userId, InventoryType type) { return CreateInventoryItem(scene, itemName, UUID.Random(), UUID.Random(), userId, type); } /// <summary> /// Creates a notecard in the objects folder and specify an item id. /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="assetId"></param> /// <param name="userId"></param> /// <param name="type">Type of item to create</param> /// <returns></returns> public static InventoryItemBase CreateInventoryItem( Scene scene, string itemName, UUID itemId, UUID assetId, UUID userId, InventoryType itemType) { AssetBase asset = null; if (itemType == InventoryType.Notecard) { asset = AssetHelpers.CreateNotecardAsset(); asset.CreatorID = userId.ToString(); } else if (itemType == InventoryType.Object) { asset = AssetHelpers.CreateAsset(assetId, SceneHelpers.CreateSceneObject(1, userId)); } else { throw new Exception(string.Format("Inventory type {0} not supported", itemType)); } return AddInventoryItem(scene, itemName, itemId, itemType, asset, userId); } /// <summary> /// Create inventory folders starting from the user's root folder. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"> /// The folders to create. Multiple folders can be specified on a path delimited by the PATH_DELIMITER /// </param> /// <param name="useExistingFolders"> /// If true, then folders in the path which already the same name are /// used. This applies to the terminal folder as well. /// If false, then all folders in the path are created, even if there is already a folder at a particular /// level with the same name. /// </param> /// <returns> /// The folder created. If the path contains multiple folders then the last one created is returned. /// Will return null if the root folder could not be found. /// </returns> public static InventoryFolderBase CreateInventoryFolder( IInventoryService inventoryService, UUID userId, string path, bool useExistingFolders) { return CreateInventoryFolder(inventoryService, userId, UUID.Random(), path, useExistingFolders); } /// <summary> /// Create inventory folders starting from the user's root folder. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="folderId"></param> /// <param name="path"> /// The folders to create. Multiple folders can be specified on a path delimited by the PATH_DELIMITER /// </param> /// <param name="useExistingFolders"> /// If true, then folders in the path which already the same name are /// used. This applies to the terminal folder as well. /// If false, then all folders in the path are created, even if there is already a folder at a particular /// level with the same name. /// </param> /// <returns> /// The folder created. If the path contains multiple folders then the last one created is returned. /// Will return null if the root folder could not be found. /// </returns> public static InventoryFolderBase CreateInventoryFolder( IInventoryService inventoryService, UUID userId, UUID folderId, string path, bool useExistingFolders) { InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId); if (null == rootFolder) return null; return CreateInventoryFolder(inventoryService, folderId, rootFolder, path, useExistingFolders); } /// <summary> /// Create inventory folders starting from a given parent folder /// </summary> /// <remarks> /// If any stem of the path names folders that already exist then these are not recreated. This includes the /// final folder. /// TODO: May need to make it an option to create duplicate folders. /// </remarks> /// <param name="inventoryService"></param> /// <param name="folderId">ID of the folder to create</param> /// <param name="parentFolder"></param> /// <param name="path"> /// The folder to create. /// </param> /// <param name="useExistingFolders"> /// If true, then folders in the path which already the same name are /// used. This applies to the terminal folder as well. /// If false, then all folders in the path are created, even if there is already a folder at a particular /// level with the same name. /// </param> /// <returns> /// The folder created. If the path contains multiple folders then the last one created is returned. /// </returns> public static InventoryFolderBase CreateInventoryFolder( IInventoryService inventoryService, UUID folderId, InventoryFolderBase parentFolder, string path, bool useExistingFolders) { string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None); InventoryFolderBase folder = null; if (useExistingFolders) folder = InventoryArchiveUtils.FindFolderByPath(inventoryService, parentFolder, components[0]); if (folder == null) { // Console.WriteLine("Creating folder {0} at {1}", components[0], parentFolder.Name); UUID folderIdForCreate; if (components.Length > 1) folderIdForCreate = UUID.Random(); else folderIdForCreate = folderId; folder = new InventoryFolderBase( folderIdForCreate, components[0], parentFolder.Owner, (short)AssetType.Unknown, parentFolder.ID, 0); inventoryService.AddFolder(folder); } // else // { // Console.WriteLine("Found existing folder {0}", folder.Name); // } if (components.Length > 1) return CreateInventoryFolder(inventoryService, folderId, folder, components[1], useExistingFolders); else return folder; } /// <summary> /// Get the inventory folder that matches the path name. If there are multiple folders then only the first /// is returned. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>null if no folder matching the path was found</returns> public static InventoryFolderBase GetInventoryFolder(IInventoryService inventoryService, UUID userId, string path) { List<InventoryFolderBase> folders = GetInventoryFolders(inventoryService, userId, path); if (folders.Count != 0) return folders[0]; else return null; } /// <summary> /// Get the inventory folders that match the path name. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>An empty list if no matching folders were found</returns> public static List<InventoryFolderBase> GetInventoryFolders(IInventoryService inventoryService, UUID userId, string path) { return InventoryArchiveUtils.FindFoldersByPath(inventoryService, userId, path); } /// <summary> /// Get the inventory item that matches the path name. If there are multiple items then only the first /// is returned. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>null if no item matching the path was found</returns> public static InventoryItemBase GetInventoryItem(IInventoryService inventoryService, UUID userId, string path) { return InventoryArchiveUtils.FindItemByPath(inventoryService, userId, path); } /// <summary> /// Get the inventory items that match the path name. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>An empty list if no matching items were found.</returns> public static List<InventoryItemBase> GetInventoryItems(IInventoryService inventoryService, UUID userId, string path) { return InventoryArchiveUtils.FindItemsByPath(inventoryService, userId, path); } } }
// 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, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows.Forms; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Project; namespace Microsoft.PythonTools.Profiling { /// <summary> /// Top level node for our UI Hierarchy which includes all of the various performance sessions. /// /// We need one top-level node which we'll add the other nodes to. We treat the other nodes /// as nested hierarchies. /// </summary> class SessionsNode : BaseHierarchyNode, IVsHierarchyDeleteHandler { private readonly List<SessionNode> _sessions = new List<SessionNode>(); internal readonly EventSinkCollection _sessionsCollection = new EventSinkCollection(); private readonly IServiceProvider _serviceProvider; private readonly IVsUIHierarchyWindow _window; internal uint _activeSession = VSConstants.VSITEMID_NIL; internal static ImageList _imageList = InitImageList(); internal SessionsNode(IServiceProvider serviceProvider, IVsUIHierarchyWindow window) { _serviceProvider = serviceProvider; _window = window; } internal SessionNode AddTarget(ProfilingTarget target, string filename, bool save) { Debug.Assert(filename.EndsWithOrdinal(".pyperf", ignoreCase: true)); // ensure a unique name string newBaseName = Path.GetFileNameWithoutExtension(filename); string tempBaseName = newBaseName; int append = 0; bool dupFound; do { dupFound = false; for (int i = 0; i < _sessions.Count; i++) { if (Path.GetFileNameWithoutExtension(_sessions[i].Filename) == newBaseName) { dupFound = true; } } if (dupFound) { append++; newBaseName = tempBaseName + append; } } while (dupFound); string newFilename = newBaseName + ".pyperf"; // add directory name back if present... string dirName = Path.GetDirectoryName(filename); if (!string.IsNullOrEmpty(dirName)) { newFilename = Path.Combine(dirName, newFilename); } filename = newFilename; // save to the unique item if desired (we save whenever we have an active solution as we have a place to put it)... if (save) { using (var fs = new FileStream(filename, FileMode.Create)) { ProfilingTarget.Serializer.Serialize(fs, target); } } var node = OpenTarget(target, filename); if (!save) { node.MarkDirty(); node._neverSaved = true; } return node; } internal SessionNode OpenTarget(ProfilingTarget target, string filename) { for (int i = 0; i < _sessions.Count; i++) { if (_sessions[i].Filename == filename) { throw new InvalidOperationException(Strings.PerformanceSessionAlreadyOpen.FormatUI(filename)); } } uint prevSibl; if (_sessions.Count > 0) { prevSibl = _sessions[_sessions.Count - 1].ItemId; } else { prevSibl = VSConstants.VSITEMID_NIL; } var node = new SessionNode(_serviceProvider, this, target, filename); _sessions.Add(node); OnItemAdded(VSConstants.VSITEMID_ROOT, prevSibl, node.ItemId); if (_activeSession == VSConstants.VSITEMID_NIL) { SetActiveSession(node); } return node; } internal void SetActiveSession(SessionNode node) { uint oldItem = _activeSession; if (oldItem != VSConstants.VSITEMID_NIL) { _window.ExpandItem(this, _activeSession, EXPANDFLAGS.EXPF_UnBoldItem); } _activeSession = node.ItemId; _window.ExpandItem(this, _activeSession, EXPANDFLAGS.EXPF_BoldItem); } #region IVsUIHierarchy Members public override int GetNestedHierarchy(uint itemid, ref Guid iidHierarchyNested, out IntPtr ppHierarchyNested, out uint pitemidNested) { var item = _sessionsCollection[itemid]; if (item != null) { if (iidHierarchyNested == typeof(IVsHierarchy).GUID || iidHierarchyNested == typeof(IVsUIHierarchy).GUID) { ppHierarchyNested = System.Runtime.InteropServices.Marshal.GetComInterfaceForObject(item, typeof(IVsUIHierarchy)); pitemidNested = VSConstants.VSITEMID_ROOT; return VSConstants.S_OK; } } return base.GetNestedHierarchy(itemid, ref iidHierarchyNested, out ppHierarchyNested, out pitemidNested); } public override int GetProperty(uint itemid, int propid, out object pvar) { // GetProperty is called many many times for this particular property pvar = null; var prop = (__VSHPROPID)propid; switch (prop) { case __VSHPROPID.VSHPROPID_CmdUIGuid: pvar = new Guid(GuidList.guidPythonProfilingPkgString); break; case __VSHPROPID.VSHPROPID_Parent: if (itemid != VSConstants.VSITEMID_ROOT) { pvar = VSConstants.VSITEMID_ROOT; } break; case __VSHPROPID.VSHPROPID_FirstChild: if (itemid == VSConstants.VSITEMID_ROOT && _sessions.Count > 0) pvar = _sessions[0].ItemId; else pvar = VSConstants.VSITEMID_NIL; break; case __VSHPROPID.VSHPROPID_NextSibling: pvar = VSConstants.VSITEMID_NIL; for(int i = 0; i<_sessions.Count; i++) { if (_sessions[i].ItemId == itemid && i < _sessions.Count - 1) { pvar = _sessions[i + 1].ItemId; } } break; case __VSHPROPID.VSHPROPID_Expandable: pvar = true; break; case __VSHPROPID.VSHPROPID_ExpandByDefault: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = true; } break; case __VSHPROPID.VSHPROPID_IconImgList: case __VSHPROPID.VSHPROPID_OpenFolderIconHandle: pvar = (int)_imageList.Handle; break; case __VSHPROPID.VSHPROPID_IconIndex: case __VSHPROPID.VSHPROPID_OpenFolderIconIndex: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = 0; } else { pvar = (int)TreeViewIconIndex.PerformanceSession; } break; case __VSHPROPID.VSHPROPID_SaveName: if (itemid != VSConstants.VSITEMID_ROOT) { pvar = GetItem(itemid).Filename; } break; case __VSHPROPID.VSHPROPID_Caption: if (itemid != VSConstants.VSITEMID_ROOT) { pvar = GetItem(itemid).Caption; } break; case __VSHPROPID.VSHPROPID_ParentHierarchy: if (_sessionsCollection[itemid] != null) { pvar = this as IVsHierarchy; } break; } if (pvar != null) return VSConstants.S_OK; return VSConstants.DISP_E_MEMBERNOTFOUND; } #endregion #region IVsHierarchyDeleteHandler Members public int DeleteItem(uint dwDelItemOp, uint itemid) { var item = GetItem(itemid); if (item != null) { switch ((__VSDELETEITEMOPERATION)dwDelItemOp) { case __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage: File.Delete(item.Filename); goto case __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject; case __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject: item.Removed(); _sessions.Remove(item); _sessionsCollection.RemoveAt(itemid); OnItemDeleted(itemid); // our itemids have all changed, invalidate them OnInvalidateItems(VSConstants.VSITEMID_ROOT); break; } if (itemid == _activeSession) { if (_sessions.Count > 0) { SetActiveSession(_sessions[0]); } else { _activeSession = VSConstants.VSITEMID_NIL; } } return VSConstants.S_OK; } return VSConstants.E_FAIL; } public int QueryDeleteItem(uint dwDelItemOp, uint itemid, out int pfCanDelete) { pfCanDelete = 1; return VSConstants.S_OK; } #endregion private static ImageList InitImageList() { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.PythonTools.ProfilingTreeView.bmp"); return Utilities.GetImageList( stream ); } private SessionNode GetItem(uint itemid) { return (SessionNode)_sessionsCollection[itemid]; } internal void StartProfiling() { if (_activeSession != VSConstants.VSITEMID_NIL) { GetItem(_activeSession).StartProfiling(); } } public List<SessionNode> Sessions { get { return _sessions; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Automation Client /// </summary> public partial class AutomationClient : ServiceClient<AutomationClient>, IAutomationClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Identifies this specific client request. /// </summary> public string ClientRequestId { get; set; } /// <summary> /// The name of the automation account. /// </summary> public System.Guid AutomationAccountName { get; set; } /// <summary> /// The name of the resource group within user's subscription. /// </summary> public string ResourceGroupName1 { get; set; } /// <summary> /// subscription id for tenant issuing the request. /// </summary> public System.Guid SubscriptionId1 { get; set; } /// <summary> /// The name of the software update configuration to be created. /// </summary> public string SoftwareUpdateConfigurationName { get; set; } /// <summary> /// The Id of the software update configuration run. /// </summary> public System.Guid SoftwareUpdateConfigurationRunId { get; set; } /// <summary> /// The Id of the software update configuration machine run. /// </summary> public System.Guid SoftwareUpdateConfigurationMachineRunId { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IAutomationAccountOperations. /// </summary> public virtual IAutomationAccountOperations AutomationAccount { get; private set; } /// <summary> /// Gets the IOperations. /// </summary> public virtual IOperations Operations { get; private set; } /// <summary> /// Gets the IStatisticsOperations. /// </summary> public virtual IStatisticsOperations Statistics { get; private set; } /// <summary> /// Gets the IUsagesOperations. /// </summary> public virtual IUsagesOperations Usages { get; private set; } /// <summary> /// Gets the ICertificateOperations. /// </summary> public virtual ICertificateOperations Certificate { get; private set; } /// <summary> /// Gets the IConnectionOperations. /// </summary> public virtual IConnectionOperations Connection { get; private set; } /// <summary> /// Gets the IConnectionTypeOperations. /// </summary> public virtual IConnectionTypeOperations ConnectionType { get; private set; } /// <summary> /// Gets the ICredentialOperations. /// </summary> public virtual ICredentialOperations Credential { get; private set; } /// <summary> /// Gets the IDscCompilationJobOperations. /// </summary> public virtual IDscCompilationJobOperations DscCompilationJob { get; private set; } /// <summary> /// Gets the IDscConfigurationOperations. /// </summary> public virtual IDscConfigurationOperations DscConfiguration { get; private set; } /// <summary> /// Gets the IAgentRegistrationInformationOperations. /// </summary> public virtual IAgentRegistrationInformationOperations AgentRegistrationInformation { get; private set; } /// <summary> /// Gets the IDscNodeOperations. /// </summary> public virtual IDscNodeOperations DscNode { get; private set; } /// <summary> /// Gets the INodeReportsOperations. /// </summary> public virtual INodeReportsOperations NodeReports { get; private set; } /// <summary> /// Gets the IDscNodeConfigurationOperations. /// </summary> public virtual IDscNodeConfigurationOperations DscNodeConfiguration { get; private set; } /// <summary> /// Gets the IHybridRunbookWorkerGroupOperations. /// </summary> public virtual IHybridRunbookWorkerGroupOperations HybridRunbookWorkerGroup { get; private set; } /// <summary> /// Gets the IJobOperations. /// </summary> public virtual IJobOperations Job { get; private set; } /// <summary> /// Gets the IJobStreamOperations. /// </summary> public virtual IJobStreamOperations JobStream { get; private set; } /// <summary> /// Gets the IJobScheduleOperations. /// </summary> public virtual IJobScheduleOperations JobSchedule { get; private set; } /// <summary> /// Gets the IActivityOperations. /// </summary> public virtual IActivityOperations Activity { get; private set; } /// <summary> /// Gets the IModuleOperations. /// </summary> public virtual IModuleOperations Module { get; private set; } /// <summary> /// Gets the IObjectDataTypesOperations. /// </summary> public virtual IObjectDataTypesOperations ObjectDataTypes { get; private set; } /// <summary> /// Gets the IFieldsOperations. /// </summary> public virtual IFieldsOperations Fields { get; private set; } /// <summary> /// Gets the IRunbookDraftOperations. /// </summary> public virtual IRunbookDraftOperations RunbookDraft { get; private set; } /// <summary> /// Gets the IRunbookOperations. /// </summary> public virtual IRunbookOperations Runbook { get; private set; } /// <summary> /// Gets the ITestJobStreamsOperations. /// </summary> public virtual ITestJobStreamsOperations TestJobStreams { get; private set; } /// <summary> /// Gets the ITestJobsOperations. /// </summary> public virtual ITestJobsOperations TestJobs { get; private set; } /// <summary> /// Gets the IScheduleOperations. /// </summary> public virtual IScheduleOperations Schedule { get; private set; } /// <summary> /// Gets the IVariableOperations. /// </summary> public virtual IVariableOperations Variable { get; private set; } /// <summary> /// Gets the IWebhookOperations. /// </summary> public virtual IWebhookOperations Webhook { get; private set; } /// <summary> /// Gets the ISoftwareUpdateConfigurationsOperations. /// </summary> public virtual ISoftwareUpdateConfigurationsOperations SoftwareUpdateConfigurations { get; private set; } /// <summary> /// Gets the ISoftwareUpdateConfigurationRunsOperations. /// </summary> public virtual ISoftwareUpdateConfigurationRunsOperations SoftwareUpdateConfigurationRuns { get; private set; } /// <summary> /// Gets the ISoftwareUpdateConfigurationMachineRunsOperations. /// </summary> public virtual ISoftwareUpdateConfigurationMachineRunsOperations SoftwareUpdateConfigurationMachineRuns { get; private set; } /// <summary> /// Initializes a new instance of the AutomationClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutomationClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutomationClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutomationClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutomationClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutomationClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutomationClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutomationClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutomationClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutomationClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutomationClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutomationClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutomationClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutomationClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutomationClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutomationClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { AutomationAccount = new AutomationAccountOperations(this); Operations = new Operations(this); Statistics = new StatisticsOperations(this); Usages = new UsagesOperations(this); Certificate = new CertificateOperations(this); Connection = new ConnectionOperations(this); ConnectionType = new ConnectionTypeOperations(this); Credential = new CredentialOperations(this); DscCompilationJob = new DscCompilationJobOperations(this); DscConfiguration = new DscConfigurationOperations(this); AgentRegistrationInformation = new AgentRegistrationInformationOperations(this); DscNode = new DscNodeOperations(this); NodeReports = new NodeReportsOperations(this); DscNodeConfiguration = new DscNodeConfigurationOperations(this); HybridRunbookWorkerGroup = new HybridRunbookWorkerGroupOperations(this); Job = new JobOperations(this); JobStream = new JobStreamOperations(this); JobSchedule = new JobScheduleOperations(this); Activity = new ActivityOperations(this); Module = new ModuleOperations(this); ObjectDataTypes = new ObjectDataTypesOperations(this); Fields = new FieldsOperations(this); RunbookDraft = new RunbookDraftOperations(this); Runbook = new RunbookOperations(this); TestJobStreams = new TestJobStreamsOperations(this); TestJobs = new TestJobsOperations(this); Schedule = new ScheduleOperations(this); Variable = new VariableOperations(this); Webhook = new WebhookOperations(this); SoftwareUpdateConfigurations = new SoftwareUpdateConfigurationsOperations(this); SoftwareUpdateConfigurationRuns = new SoftwareUpdateConfigurationRunsOperations(this); SoftwareUpdateConfigurationMachineRuns = new SoftwareUpdateConfigurationMachineRunsOperations(this); BaseUri = new System.Uri("https://management.azure.com/"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<UpdateConfiguration>("operatingSystem")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<UpdateConfiguration>("operatingSystem")); CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; // to be used for REST-->Grid shortly using System.Reflection; using System.Text; using System.Threading; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Mono.Data.SqliteClient; using Mono.Addins; using Caps = OpenSim.Framework.Capabilities.Caps; using OSD = OpenMetaverse.StructuredData.OSD; using OSDMap = OpenMetaverse.StructuredData.OSDMap; namespace OpenSim.Region.UserStatistics { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WebStatsModule")] public class WebStatsModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static SqliteConnection dbConn; /// <summary> /// User statistics sessions keyed by agent ID /// </summary> private Dictionary<UUID, UserSession> m_sessions = new Dictionary<UUID, UserSession>(); private List<Scene> m_scenes = new List<Scene>(); private Dictionary<string, IStatsController> reports = new Dictionary<string, IStatsController>(); private Dictionary<UUID, USimStatsData> m_simstatsCounters = new Dictionary<UUID, USimStatsData>(); private const int updateStatsMod = 6; private int updateLogMod = 1; private volatile int updateLogCounter = 0; private volatile int concurrencyCounter = 0; private bool enabled = false; private string m_loglines = String.Empty; private volatile int lastHit = 12000; #region ISharedRegionModule public virtual void Initialise(IConfigSource config) { IConfig cnfg = config.Configs["WebStats"]; if (cnfg != null) enabled = cnfg.GetBoolean("enabled", false); } public virtual void PostInitialise() { if (!enabled) return; if (Util.IsWindows()) Util.LoadArchSpecificWindowsDll("sqlite3.dll"); //IConfig startupConfig = config.Configs["Startup"]; dbConn = new SqliteConnection("URI=file:LocalUserStatistics.db,version=3"); dbConn.Open(); CreateTables(dbConn); Prototype_distributor protodep = new Prototype_distributor(); Updater_distributor updatedep = new Updater_distributor(); ActiveConnectionsAJAX ajConnections = new ActiveConnectionsAJAX(); SimStatsAJAX ajSimStats = new SimStatsAJAX(); LogLinesAJAX ajLogLines = new LogLinesAJAX(); Default_Report defaultReport = new Default_Report(); Clients_report clientReport = new Clients_report(); Sessions_Report sessionsReport = new Sessions_Report(); reports.Add("prototype.js", protodep); reports.Add("updater.js", updatedep); reports.Add("activeconnectionsajax.html", ajConnections); reports.Add("simstatsajax.html", ajSimStats); reports.Add("activelogajax.html", ajLogLines); reports.Add("default.report", defaultReport); reports.Add("clients.report", clientReport); reports.Add("sessions.report", sessionsReport); reports.Add("sim.css", new Prototype_distributor("sim.css")); reports.Add("sim.html", new Prototype_distributor("sim.html")); reports.Add("jquery.js", new Prototype_distributor("jquery.js")); //// // Add Your own Reports here (Do Not Modify Lines here Devs!) //// //// // End Own reports section //// MainServer.Instance.AddHTTPHandler("/SStats/", HandleStatsRequest); MainServer.Instance.AddHTTPHandler("/CAPS/VS/", HandleUnknownCAPSRequest); } public virtual void AddRegion(Scene scene) { if (!enabled) return; lock (m_scenes) { m_scenes.Add(scene); updateLogMod = m_scenes.Count * 2; m_simstatsCounters.Add(scene.RegionInfo.RegionID, new USimStatsData(scene.RegionInfo.RegionID)); scene.EventManager.OnRegisterCaps += OnRegisterCaps; scene.EventManager.OnDeregisterCaps += OnDeRegisterCaps; scene.EventManager.OnClientClosed += OnClientClosed; scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.StatsReporter.OnSendStatsResult += ReceiveClassicSimStatsPacket; } } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (!enabled) return; lock (m_scenes) { m_scenes.Remove(scene); updateLogMod = m_scenes.Count * 2; m_simstatsCounters.Remove(scene.RegionInfo.RegionID); } } public virtual void Close() { if (!enabled) return; dbConn.Close(); dbConn.Dispose(); m_sessions.Clear(); m_scenes.Clear(); reports.Clear(); m_simstatsCounters.Clear(); } public virtual string Name { get { return "ViewerStatsModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion private void ReceiveClassicSimStatsPacket(SimStats stats) { if (!enabled) return; try { // Ignore the update if there's a report running right now // ignore the update if there hasn't been a hit in 30 seconds. if (concurrencyCounter > 0 || System.Environment.TickCount - lastHit > 30000) return; // We will conduct this under lock so that fields such as updateLogCounter do not potentially get // confused if a scene is removed. // XXX: Possibly the scope of this lock could be reduced though it's not critical. lock (m_scenes) { if (updateLogMod != 0 && updateLogCounter++ % updateLogMod == 0) { m_loglines = readLogLines(10); if (updateLogCounter > 10000) updateLogCounter = 1; } USimStatsData ss = m_simstatsCounters[stats.RegionUUID]; if ((++ss.StatsCounter % updateStatsMod) == 0) { ss.ConsumeSimStats(stats); } } } catch (KeyNotFoundException) { } } private Hashtable HandleUnknownCAPSRequest(Hashtable request) { //string regpath = request["uri"].ToString(); int response_code = 200; string contenttype = "text/html"; UpdateUserStats(ParseViewerStats(request["body"].ToString(), UUID.Zero), dbConn); Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = response_code; responsedata["content_type"] = contenttype; responsedata["keepalive"] = false; responsedata["str_response_string"] = string.Empty; return responsedata; } private Hashtable HandleStatsRequest(Hashtable request) { lastHit = System.Environment.TickCount; Hashtable responsedata = new Hashtable(); string regpath = request["uri"].ToString(); int response_code = 404; string contenttype = "text/html"; bool jsonFormatOutput = false; string strOut = string.Empty; // The request patch should be "/SStats/reportName" where 'reportName' // is one of the names added to the 'reports' hashmap. regpath = regpath.Remove(0, 8); if (regpath.Length == 0) regpath = "default.report"; if (reports.ContainsKey(regpath)) { IStatsController rep = reports[regpath]; Hashtable repParams = new Hashtable(); if (request.ContainsKey("json")) jsonFormatOutput = true; if (request.ContainsKey("requestvars")) repParams["RequestVars"] = request["requestvars"]; else repParams["RequestVars"] = new Hashtable(); if (request.ContainsKey("querystringkeys")) repParams["QueryStringKeys"] = request["querystringkeys"]; else repParams["QueryStringKeys"] = new string[0]; repParams["DatabaseConnection"] = dbConn; repParams["Scenes"] = m_scenes; repParams["SimStats"] = m_simstatsCounters; repParams["LogLines"] = m_loglines; repParams["Reports"] = reports; concurrencyCounter++; if (jsonFormatOutput) { strOut = rep.RenderJson(rep.ProcessModel(repParams)); contenttype = "text/json"; } else { strOut = rep.RenderView(rep.ProcessModel(repParams)); } if (regpath.EndsWith("js")) { contenttype = "text/javascript"; } if (regpath.EndsWith("css")) { contenttype = "text/css"; } concurrencyCounter--; response_code = 200; } else { strOut = MainServer.Instance.GetHTTP404(""); } responsedata["int_response_code"] = response_code; responsedata["content_type"] = contenttype; responsedata["keepalive"] = false; responsedata["str_response_string"] = strOut; return responsedata; } private void CreateTables(SqliteConnection db) { using (SqliteCommand createcmd = new SqliteCommand(SQL_STATS_TABLE_CREATE, db)) { createcmd.ExecuteNonQuery(); } } private void OnRegisterCaps(UUID agentID, Caps caps) { // m_log.DebugFormat("[WEB STATS MODULE]: OnRegisterCaps: agentID {0} caps {1}", agentID, caps); string capsPath = "/CAPS/VS/" + UUID.Random(); caps.RegisterHandler( "ViewerStats", new RestStreamHandler( "POST", capsPath, (request, path, param, httpRequest, httpResponse) => ViewerStatsReport(request, path, param, agentID, caps), "ViewerStats", agentID.ToString())); } private void OnDeRegisterCaps(UUID agentID, Caps caps) { } protected virtual void AddEventHandlers() { lock (m_scenes) { updateLogMod = m_scenes.Count * 2; foreach (Scene scene in m_scenes) { scene.EventManager.OnRegisterCaps += OnRegisterCaps; scene.EventManager.OnDeregisterCaps += OnDeRegisterCaps; scene.EventManager.OnClientClosed += OnClientClosed; scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; } } } private void OnMakeRootAgent(ScenePresence agent) { // m_log.DebugFormat( // "[WEB STATS MODULE]: Looking for session {0} for {1} in {2}", // agent.ControllingClient.SessionId, agent.Name, agent.Scene.Name); lock (m_sessions) { UserSession uid; if (!m_sessions.ContainsKey(agent.UUID)) { UserSessionData usd = UserSessionUtil.newUserSessionData(); uid = new UserSession(); uid.name_f = agent.Firstname; uid.name_l = agent.Lastname; uid.session_data = usd; m_sessions.Add(agent.UUID, uid); } else { uid = m_sessions[agent.UUID]; } uid.region_id = agent.Scene.RegionInfo.RegionID; uid.session_id = agent.ControllingClient.SessionId; } } private void OnClientClosed(UUID agentID, Scene scene) { lock (m_sessions) { if (m_sessions.ContainsKey(agentID) && m_sessions[agentID].region_id == scene.RegionInfo.RegionID) { m_sessions.Remove(agentID); } } } private string readLogLines(int amount) { Encoding encoding = Encoding.ASCII; int sizeOfChar = encoding.GetByteCount("\n"); byte[] buffer = encoding.GetBytes("\n"); string logfile = Util.logFile(); FileStream fs = new FileStream(logfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Int64 tokenCount = 0; Int64 endPosition = fs.Length / sizeOfChar; for (Int64 position = sizeOfChar; position < endPosition; position += sizeOfChar) { fs.Seek(-position, SeekOrigin.End); fs.Read(buffer, 0, buffer.Length); if (encoding.GetString(buffer) == "\n") { tokenCount++; if (tokenCount == amount) { byte[] returnBuffer = new byte[fs.Length - fs.Position]; fs.Read(returnBuffer, 0, returnBuffer.Length); fs.Close(); fs.Dispose(); return encoding.GetString(returnBuffer); } } } // handle case where number of tokens in file is less than numberOfTokens fs.Seek(0, SeekOrigin.Begin); buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); fs.Dispose(); return encoding.GetString(buffer); } /// <summary> /// Callback for a viewerstats cap /// </summary> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="agentID"></param> /// <param name="caps"></param> /// <returns></returns> private string ViewerStatsReport(string request, string path, string param, UUID agentID, Caps caps) { // m_log.DebugFormat("[WEB STATS MODULE]: Received viewer starts report from {0}", agentID); UpdateUserStats(ParseViewerStats(request, agentID), dbConn); return String.Empty; } private UserSession ParseViewerStats(string request, UUID agentID) { UserSession uid = new UserSession(); UserSessionData usd; OSD message = OSDParser.DeserializeLLSDXml(request); OSDMap mmap; lock (m_sessions) { if (agentID != UUID.Zero) { if (!m_sessions.ContainsKey(agentID)) { m_log.WarnFormat("[WEB STATS MODULE]: no session for stat disclosure for agent {0}", agentID); return new UserSession(); } uid = m_sessions[agentID]; // m_log.DebugFormat("[WEB STATS MODULE]: Got session {0} for {1}", uid.session_id, agentID); } else { // parse through the beginning to locate the session if (message.Type != OSDType.Map) return new UserSession(); mmap = (OSDMap)message; { UUID sessionID = mmap["session_id"].AsUUID(); if (sessionID == UUID.Zero) return new UserSession(); // search through each session looking for the owner foreach (UUID usersessionid in m_sessions.Keys) { // got it! if (m_sessions[usersessionid].session_id == sessionID) { agentID = usersessionid; uid = m_sessions[usersessionid]; break; } } // can't find a session if (agentID == UUID.Zero) { return new UserSession(); } } } } usd = uid.session_data; if (message.Type != OSDType.Map) return new UserSession(); mmap = (OSDMap)message; { if (mmap["agent"].Type != OSDType.Map) return new UserSession(); OSDMap agent_map = (OSDMap)mmap["agent"]; usd.agent_id = agentID; usd.name_f = uid.name_f; usd.name_l = uid.name_l; usd.region_id = uid.region_id; usd.a_language = agent_map["language"].AsString(); usd.mem_use = (float)agent_map["mem_use"].AsReal(); usd.meters_traveled = (float)agent_map["meters_traveled"].AsReal(); usd.regions_visited = agent_map["regions_visited"].AsInteger(); usd.run_time = (float)agent_map["run_time"].AsReal(); usd.start_time = (float)agent_map["start_time"].AsReal(); usd.client_version = agent_map["version"].AsString(); UserSessionUtil.UpdateMultiItems(ref usd, agent_map["agents_in_view"].AsInteger(), (float)agent_map["ping"].AsReal(), (float)agent_map["sim_fps"].AsReal(), (float)agent_map["fps"].AsReal()); if (mmap["downloads"].Type != OSDType.Map) return new UserSession(); OSDMap downloads_map = (OSDMap)mmap["downloads"]; usd.d_object_kb = (float)downloads_map["object_kbytes"].AsReal(); usd.d_texture_kb = (float)downloads_map["texture_kbytes"].AsReal(); usd.d_world_kb = (float)downloads_map["workd_kbytes"].AsReal(); // m_log.DebugFormat("[WEB STATS MODULE]: mmap[\"session_id\"] = [{0}]", mmap["session_id"].AsUUID()); usd.session_id = mmap["session_id"].AsUUID(); if (mmap["system"].Type != OSDType.Map) return new UserSession(); OSDMap system_map = (OSDMap)mmap["system"]; usd.s_cpu = system_map["cpu"].AsString(); usd.s_gpu = system_map["gpu"].AsString(); usd.s_os = system_map["os"].AsString(); usd.s_ram = system_map["ram"].AsInteger(); if (mmap["stats"].Type != OSDType.Map) return new UserSession(); OSDMap stats_map = (OSDMap)mmap["stats"]; { if (stats_map["failures"].Type != OSDType.Map) return new UserSession(); OSDMap stats_failures = (OSDMap)stats_map["failures"]; usd.f_dropped = stats_failures["dropped"].AsInteger(); usd.f_failed_resends = stats_failures["failed_resends"].AsInteger(); usd.f_invalid = stats_failures["invalid"].AsInteger(); usd.f_resent = stats_failures["resent"].AsInteger(); usd.f_send_packet = stats_failures["send_packet"].AsInteger(); if (stats_map["net"].Type != OSDType.Map) return new UserSession(); OSDMap stats_net = (OSDMap)stats_map["net"]; { if (stats_net["in"].Type != OSDType.Map) return new UserSession(); OSDMap net_in = (OSDMap)stats_net["in"]; usd.n_in_kb = (float)net_in["kbytes"].AsReal(); usd.n_in_pk = net_in["packets"].AsInteger(); if (stats_net["out"].Type != OSDType.Map) return new UserSession(); OSDMap net_out = (OSDMap)stats_net["out"]; usd.n_out_kb = (float)net_out["kbytes"].AsReal(); usd.n_out_pk = net_out["packets"].AsInteger(); } } } uid.session_data = usd; m_sessions[agentID] = uid; // m_log.DebugFormat( // "[WEB STATS MODULE]: Parse data for {0} {1}, session {2}", uid.name_f, uid.name_l, uid.session_id); return uid; } private void UpdateUserStats(UserSession uid, SqliteConnection db) { // m_log.DebugFormat( // "[WEB STATS MODULE]: Updating user stats for {0} {1}, session {2}", uid.name_f, uid.name_l, uid.session_id); if (uid.session_id == UUID.Zero) return; lock (db) { using (SqliteCommand updatecmd = new SqliteCommand(SQL_STATS_TABLE_INSERT, db)) { updatecmd.Parameters.Add(new SqliteParameter(":session_id", uid.session_data.session_id.ToString())); updatecmd.Parameters.Add(new SqliteParameter(":agent_id", uid.session_data.agent_id.ToString())); updatecmd.Parameters.Add(new SqliteParameter(":region_id", uid.session_data.region_id.ToString())); updatecmd.Parameters.Add(new SqliteParameter(":last_updated", (int) uid.session_data.last_updated)); updatecmd.Parameters.Add(new SqliteParameter(":remote_ip", uid.session_data.remote_ip)); updatecmd.Parameters.Add(new SqliteParameter(":name_f", uid.session_data.name_f)); updatecmd.Parameters.Add(new SqliteParameter(":name_l", uid.session_data.name_l)); updatecmd.Parameters.Add(new SqliteParameter(":avg_agents_in_view", uid.session_data.avg_agents_in_view)); updatecmd.Parameters.Add(new SqliteParameter(":min_agents_in_view", (int) uid.session_data.min_agents_in_view)); updatecmd.Parameters.Add(new SqliteParameter(":max_agents_in_view", (int) uid.session_data.max_agents_in_view)); updatecmd.Parameters.Add(new SqliteParameter(":mode_agents_in_view", (int) uid.session_data.mode_agents_in_view)); updatecmd.Parameters.Add(new SqliteParameter(":avg_fps", uid.session_data.avg_fps)); updatecmd.Parameters.Add(new SqliteParameter(":min_fps", uid.session_data.min_fps)); updatecmd.Parameters.Add(new SqliteParameter(":max_fps", uid.session_data.max_fps)); updatecmd.Parameters.Add(new SqliteParameter(":mode_fps", uid.session_data.mode_fps)); updatecmd.Parameters.Add(new SqliteParameter(":a_language", uid.session_data.a_language)); updatecmd.Parameters.Add(new SqliteParameter(":mem_use", uid.session_data.mem_use)); updatecmd.Parameters.Add(new SqliteParameter(":meters_traveled", uid.session_data.meters_traveled)); updatecmd.Parameters.Add(new SqliteParameter(":avg_ping", uid.session_data.avg_ping)); updatecmd.Parameters.Add(new SqliteParameter(":min_ping", uid.session_data.min_ping)); updatecmd.Parameters.Add(new SqliteParameter(":max_ping", uid.session_data.max_ping)); updatecmd.Parameters.Add(new SqliteParameter(":mode_ping", uid.session_data.mode_ping)); updatecmd.Parameters.Add(new SqliteParameter(":regions_visited", uid.session_data.regions_visited)); updatecmd.Parameters.Add(new SqliteParameter(":run_time", uid.session_data.run_time)); updatecmd.Parameters.Add(new SqliteParameter(":avg_sim_fps", uid.session_data.avg_sim_fps)); updatecmd.Parameters.Add(new SqliteParameter(":min_sim_fps", uid.session_data.min_sim_fps)); updatecmd.Parameters.Add(new SqliteParameter(":max_sim_fps", uid.session_data.max_sim_fps)); updatecmd.Parameters.Add(new SqliteParameter(":mode_sim_fps", uid.session_data.mode_sim_fps)); updatecmd.Parameters.Add(new SqliteParameter(":start_time", uid.session_data.start_time)); updatecmd.Parameters.Add(new SqliteParameter(":client_version", uid.session_data.client_version)); updatecmd.Parameters.Add(new SqliteParameter(":s_cpu", uid.session_data.s_cpu)); updatecmd.Parameters.Add(new SqliteParameter(":s_gpu", uid.session_data.s_gpu)); updatecmd.Parameters.Add(new SqliteParameter(":s_os", uid.session_data.s_os)); updatecmd.Parameters.Add(new SqliteParameter(":s_ram", uid.session_data.s_ram)); updatecmd.Parameters.Add(new SqliteParameter(":d_object_kb", uid.session_data.d_object_kb)); updatecmd.Parameters.Add(new SqliteParameter(":d_texture_kb", uid.session_data.d_texture_kb)); updatecmd.Parameters.Add(new SqliteParameter(":d_world_kb", uid.session_data.d_world_kb)); updatecmd.Parameters.Add(new SqliteParameter(":n_in_kb", uid.session_data.n_in_kb)); updatecmd.Parameters.Add(new SqliteParameter(":n_in_pk", uid.session_data.n_in_pk)); updatecmd.Parameters.Add(new SqliteParameter(":n_out_kb", uid.session_data.n_out_kb)); updatecmd.Parameters.Add(new SqliteParameter(":n_out_pk", uid.session_data.n_out_pk)); updatecmd.Parameters.Add(new SqliteParameter(":f_dropped", uid.session_data.f_dropped)); updatecmd.Parameters.Add(new SqliteParameter(":f_failed_resends", uid.session_data.f_failed_resends)); updatecmd.Parameters.Add(new SqliteParameter(":f_invalid", uid.session_data.f_invalid)); updatecmd.Parameters.Add(new SqliteParameter(":f_off_circuit", uid.session_data.f_off_circuit)); updatecmd.Parameters.Add(new SqliteParameter(":f_resent", uid.session_data.f_resent)); updatecmd.Parameters.Add(new SqliteParameter(":f_send_packet", uid.session_data.f_send_packet)); // StringBuilder parameters = new StringBuilder(); // SqliteParameterCollection spc = updatecmd.Parameters; // foreach (SqliteParameter sp in spc) // parameters.AppendFormat("{0}={1},", sp.ParameterName, sp.Value); // // m_log.DebugFormat("[WEB STATS MODULE]: Parameters {0}", parameters); // m_log.DebugFormat("[WEB STATS MODULE]: Database stats update for {0}", uid.session_data.agent_id); updatecmd.ExecuteNonQuery(); } } } #region SQL private const string SQL_STATS_TABLE_CREATE = @"CREATE TABLE IF NOT EXISTS stats_session_data ( session_id VARCHAR(36) NOT NULL PRIMARY KEY, agent_id VARCHAR(36) NOT NULL DEFAULT '', region_id VARCHAR(36) NOT NULL DEFAULT '', last_updated INT NOT NULL DEFAULT '0', remote_ip VARCHAR(16) NOT NULL DEFAULT '', name_f VARCHAR(50) NOT NULL DEFAULT '', name_l VARCHAR(50) NOT NULL DEFAULT '', avg_agents_in_view FLOAT NOT NULL DEFAULT '0', min_agents_in_view INT NOT NULL DEFAULT '0', max_agents_in_view INT NOT NULL DEFAULT '0', mode_agents_in_view INT NOT NULL DEFAULT '0', avg_fps FLOAT NOT NULL DEFAULT '0', min_fps FLOAT NOT NULL DEFAULT '0', max_fps FLOAT NOT NULL DEFAULT '0', mode_fps FLOAT NOT NULL DEFAULT '0', a_language VARCHAR(25) NOT NULL DEFAULT '', mem_use FLOAT NOT NULL DEFAULT '0', meters_traveled FLOAT NOT NULL DEFAULT '0', avg_ping FLOAT NOT NULL DEFAULT '0', min_ping FLOAT NOT NULL DEFAULT '0', max_ping FLOAT NOT NULL DEFAULT '0', mode_ping FLOAT NOT NULL DEFAULT '0', regions_visited INT NOT NULL DEFAULT '0', run_time FLOAT NOT NULL DEFAULT '0', avg_sim_fps FLOAT NOT NULL DEFAULT '0', min_sim_fps FLOAT NOT NULL DEFAULT '0', max_sim_fps FLOAT NOT NULL DEFAULT '0', mode_sim_fps FLOAT NOT NULL DEFAULT '0', start_time FLOAT NOT NULL DEFAULT '0', client_version VARCHAR(255) NOT NULL DEFAULT '', s_cpu VARCHAR(255) NOT NULL DEFAULT '', s_gpu VARCHAR(255) NOT NULL DEFAULT '', s_os VARCHAR(2255) NOT NULL DEFAULT '', s_ram INT NOT NULL DEFAULT '0', d_object_kb FLOAT NOT NULL DEFAULT '0', d_texture_kb FLOAT NOT NULL DEFAULT '0', d_world_kb FLOAT NOT NULL DEFAULT '0', n_in_kb FLOAT NOT NULL DEFAULT '0', n_in_pk INT NOT NULL DEFAULT '0', n_out_kb FLOAT NOT NULL DEFAULT '0', n_out_pk INT NOT NULL DEFAULT '0', f_dropped INT NOT NULL DEFAULT '0', f_failed_resends INT NOT NULL DEFAULT '0', f_invalid INT NOT NULL DEFAULT '0', f_off_circuit INT NOT NULL DEFAULT '0', f_resent INT NOT NULL DEFAULT '0', f_send_packet INT NOT NULL DEFAULT '0' );"; private const string SQL_STATS_TABLE_INSERT = @"INSERT OR REPLACE INTO stats_session_data ( session_id, agent_id, region_id, last_updated, remote_ip, name_f, name_l, avg_agents_in_view, min_agents_in_view, max_agents_in_view, mode_agents_in_view, avg_fps, min_fps, max_fps, mode_fps, a_language, mem_use, meters_traveled, avg_ping, min_ping, max_ping, mode_ping, regions_visited, run_time, avg_sim_fps, min_sim_fps, max_sim_fps, mode_sim_fps, start_time, client_version, s_cpu, s_gpu, s_os, s_ram, d_object_kb, d_texture_kb, d_world_kb, n_in_kb, n_in_pk, n_out_kb, n_out_pk, f_dropped, f_failed_resends, f_invalid, f_off_circuit, f_resent, f_send_packet ) VALUES ( :session_id, :agent_id, :region_id, :last_updated, :remote_ip, :name_f, :name_l, :avg_agents_in_view, :min_agents_in_view, :max_agents_in_view, :mode_agents_in_view, :avg_fps, :min_fps, :max_fps, :mode_fps, :a_language, :mem_use, :meters_traveled, :avg_ping, :min_ping, :max_ping, :mode_ping, :regions_visited, :run_time, :avg_sim_fps, :min_sim_fps, :max_sim_fps, :mode_sim_fps, :start_time, :client_version, :s_cpu, :s_gpu, :s_os, :s_ram, :d_object_kb, :d_texture_kb, :d_world_kb, :n_in_kb, :n_in_pk, :n_out_kb, :n_out_pk, :f_dropped, :f_failed_resends, :f_invalid, :f_off_circuit, :f_resent, :f_send_packet ) "; #endregion } public static class UserSessionUtil { public static UserSessionData newUserSessionData() { UserSessionData obj = ZeroSession(new UserSessionData()); return obj; } public static void UpdateMultiItems(ref UserSessionData s, int agents_in_view, float ping, float sim_fps, float fps) { // don't insert zero values here or it'll skew the statistics. if (agents_in_view == 0 && fps == 0 && sim_fps == 0 && ping == 0) return; s._agents_in_view.Add(agents_in_view); s._fps.Add(fps); s._sim_fps.Add(sim_fps); s._ping.Add(ping); int[] __agents_in_view = s._agents_in_view.ToArray(); s.avg_agents_in_view = ArrayAvg_i(__agents_in_view); s.min_agents_in_view = ArrayMin_i(__agents_in_view); s.max_agents_in_view = ArrayMax_i(__agents_in_view); s.mode_agents_in_view = ArrayMode_i(__agents_in_view); float[] __fps = s._fps.ToArray(); s.avg_fps = ArrayAvg_f(__fps); s.min_fps = ArrayMin_f(__fps); s.max_fps = ArrayMax_f(__fps); s.mode_fps = ArrayMode_f(__fps); float[] __sim_fps = s._sim_fps.ToArray(); s.avg_sim_fps = ArrayAvg_f(__sim_fps); s.min_sim_fps = ArrayMin_f(__sim_fps); s.max_sim_fps = ArrayMax_f(__sim_fps); s.mode_sim_fps = ArrayMode_f(__sim_fps); float[] __ping = s._ping.ToArray(); s.avg_ping = ArrayAvg_f(__ping); s.min_ping = ArrayMin_f(__ping); s.max_ping = ArrayMax_f(__ping); s.mode_ping = ArrayMode_f(__ping); } #region Statistics public static int ArrayMin_i(int[] arr) { int cnt = arr.Length; if (cnt == 0) return 0; Array.Sort(arr); return arr[0]; } public static int ArrayMax_i(int[] arr) { int cnt = arr.Length; if (cnt == 0) return 0; Array.Sort(arr); return arr[cnt-1]; } public static float ArrayMin_f(float[] arr) { int cnt = arr.Length; if (cnt == 0) return 0; Array.Sort(arr); return arr[0]; } public static float ArrayMax_f(float[] arr) { int cnt = arr.Length; if (cnt == 0) return 0; Array.Sort(arr); return arr[cnt - 1]; } public static float ArrayAvg_i(int[] arr) { int cnt = arr.Length; if (cnt == 0) return 0; float result = arr[0]; for (int i = 1; i < cnt; i++) result += arr[i]; return result / cnt; } public static float ArrayAvg_f(float[] arr) { int cnt = arr.Length; if (cnt == 0) return 0; float result = arr[0]; for (int i = 1; i < cnt; i++) result += arr[i]; return result / cnt; } public static float ArrayMode_f(float[] arr) { List<float> mode = new List<float>(); float[] srtArr = new float[arr.Length]; float[,] freq = new float[arr.Length, 2]; Array.Copy(arr, srtArr, arr.Length); Array.Sort(srtArr); float tmp = srtArr[0]; int index = 0; int i = 0; while (i < srtArr.Length) { freq[index, 0] = tmp; while (tmp == srtArr[i]) { freq[index, 1]++; i++; if (i > srtArr.Length - 1) break; } if (i < srtArr.Length) { tmp = srtArr[i]; index++; } } Array.Clear(srtArr, 0, srtArr.Length); for (i = 0; i < srtArr.Length; i++) srtArr[i] = freq[i, 1]; Array.Sort(srtArr); if ((srtArr[srtArr.Length - 1]) == 0 || (srtArr[srtArr.Length - 1]) == 1) return 0; float freqtest = (float)freq.Length / freq.Rank; for (i = 0; i < freqtest; i++) { if (freq[i, 1] == srtArr[index]) mode.Add(freq[i, 0]); } return mode.ToArray()[0]; } public static int ArrayMode_i(int[] arr) { List<int> mode = new List<int>(); int[] srtArr = new int[arr.Length]; int[,] freq = new int[arr.Length, 2]; Array.Copy(arr, srtArr, arr.Length); Array.Sort(srtArr); int tmp = srtArr[0]; int index = 0; int i = 0; while (i < srtArr.Length) { freq[index, 0] = tmp; while (tmp == srtArr[i]) { freq[index, 1]++; i++; if (i > srtArr.Length - 1) break; } if (i < srtArr.Length) { tmp = srtArr[i]; index++; } } Array.Clear(srtArr, 0, srtArr.Length); for (i = 0; i < srtArr.Length; i++) srtArr[i] = freq[i, 1]; Array.Sort(srtArr); if ((srtArr[srtArr.Length - 1]) == 0 || (srtArr[srtArr.Length - 1]) == 1) return 0; float freqtest = (float)freq.Length / freq.Rank; for (i = 0; i < freqtest; i++) { if (freq[i, 1] == srtArr[index]) mode.Add(freq[i, 0]); } return mode.ToArray()[0]; } #endregion private static UserSessionData ZeroSession(UserSessionData s) { s.session_id = UUID.Zero; s.agent_id = UUID.Zero; s.region_id = UUID.Zero; s.last_updated = Util.UnixTimeSinceEpoch(); s.remote_ip = ""; s.name_f = ""; s.name_l = ""; s.avg_agents_in_view = 0; s.min_agents_in_view = 0; s.max_agents_in_view = 0; s.mode_agents_in_view = 0; s.avg_fps = 0; s.min_fps = 0; s.max_fps = 0; s.mode_fps = 0; s.a_language = ""; s.mem_use = 0; s.meters_traveled = 0; s.avg_ping = 0; s.min_ping = 0; s.max_ping = 0; s.mode_ping = 0; s.regions_visited = 0; s.run_time = 0; s.avg_sim_fps = 0; s.min_sim_fps = 0; s.max_sim_fps = 0; s.mode_sim_fps = 0; s.start_time = 0; s.client_version = ""; s.s_cpu = ""; s.s_gpu = ""; s.s_os = ""; s.s_ram = 0; s.d_object_kb = 0; s.d_texture_kb = 0; s.d_world_kb = 0; s.n_in_kb = 0; s.n_in_pk = 0; s.n_out_kb = 0; s.n_out_pk = 0; s.f_dropped = 0; s.f_failed_resends = 0; s.f_invalid = 0; s.f_off_circuit = 0; s.f_resent = 0; s.f_send_packet = 0; s._ping = new List<float>(); s._fps = new List<float>(); s._sim_fps = new List<float>(); s._agents_in_view = new List<int>(); return s; } } #region structs public class UserSession { public UUID session_id; public UUID region_id; public string name_f; public string name_l; public UserSessionData session_data; } public struct UserSessionData { public UUID session_id; public UUID agent_id; public UUID region_id; public float last_updated; public string remote_ip; public string name_f; public string name_l; public float avg_agents_in_view; public float min_agents_in_view; public float max_agents_in_view; public float mode_agents_in_view; public float avg_fps; public float min_fps; public float max_fps; public float mode_fps; public string a_language; public float mem_use; public float meters_traveled; public float avg_ping; public float min_ping; public float max_ping; public float mode_ping; public int regions_visited; public float run_time; public float avg_sim_fps; public float min_sim_fps; public float max_sim_fps; public float mode_sim_fps; public float start_time; public string client_version; public string s_cpu; public string s_gpu; public string s_os; public int s_ram; public float d_object_kb; public float d_texture_kb; public float d_world_kb; public float n_in_kb; public int n_in_pk; public float n_out_kb; public int n_out_pk; public int f_dropped; public int f_failed_resends; public int f_invalid; public int f_off_circuit; public int f_resent; public int f_send_packet; public List<float> _ping; public List<float> _fps; public List<float> _sim_fps; public List<int> _agents_in_view; } #endregion public class USimStatsData { private UUID m_regionID = UUID.Zero; private volatile int m_statcounter = 0; private volatile float m_timeDilation; private volatile float m_simFps; private volatile float m_physicsFps; private volatile float m_agentUpdates; private volatile float m_rootAgents; private volatile float m_childAgents; private volatile float m_totalPrims; private volatile float m_activePrims; private volatile float m_totalFrameTime; private volatile float m_netFrameTime; private volatile float m_physicsFrameTime; private volatile float m_otherFrameTime; private volatile float m_imageFrameTime; private volatile float m_inPacketsPerSecond; private volatile float m_outPacketsPerSecond; private volatile float m_unackedBytes; private volatile float m_agentFrameTime; private volatile float m_pendingDownloads; private volatile float m_pendingUploads; private volatile float m_activeScripts; private volatile float m_scriptLinesPerSecond; public UUID RegionId { get { return m_regionID; } } public int StatsCounter { get { return m_statcounter; } set { m_statcounter = value;}} public float TimeDilation { get { return m_timeDilation; } } public float SimFps { get { return m_simFps; } } public float PhysicsFps { get { return m_physicsFps; } } public float AgentUpdates { get { return m_agentUpdates; } } public float RootAgents { get { return m_rootAgents; } } public float ChildAgents { get { return m_childAgents; } } public float TotalPrims { get { return m_totalPrims; } } public float ActivePrims { get { return m_activePrims; } } public float TotalFrameTime { get { return m_totalFrameTime; } } public float NetFrameTime { get { return m_netFrameTime; } } public float PhysicsFrameTime { get { return m_physicsFrameTime; } } public float OtherFrameTime { get { return m_otherFrameTime; } } public float ImageFrameTime { get { return m_imageFrameTime; } } public float InPacketsPerSecond { get { return m_inPacketsPerSecond; } } public float OutPacketsPerSecond { get { return m_outPacketsPerSecond; } } public float UnackedBytes { get { return m_unackedBytes; } } public float AgentFrameTime { get { return m_agentFrameTime; } } public float PendingDownloads { get { return m_pendingDownloads; } } public float PendingUploads { get { return m_pendingUploads; } } public float ActiveScripts { get { return m_activeScripts; } } public float ScriptLinesPerSecond { get { return m_scriptLinesPerSecond; } } public USimStatsData(UUID pRegionID) { m_regionID = pRegionID; } public void ConsumeSimStats(SimStats stats) { m_regionID = stats.RegionUUID; m_timeDilation = stats.StatsBlock[0].StatValue; m_simFps = stats.StatsBlock[1].StatValue; m_physicsFps = stats.StatsBlock[2].StatValue; m_agentUpdates = stats.StatsBlock[3].StatValue; m_rootAgents = stats.StatsBlock[4].StatValue; m_childAgents = stats.StatsBlock[5].StatValue; m_totalPrims = stats.StatsBlock[6].StatValue; m_activePrims = stats.StatsBlock[7].StatValue; m_totalFrameTime = stats.StatsBlock[8].StatValue; m_netFrameTime = stats.StatsBlock[9].StatValue; m_physicsFrameTime = stats.StatsBlock[10].StatValue; m_otherFrameTime = stats.StatsBlock[11].StatValue; m_imageFrameTime = stats.StatsBlock[12].StatValue; m_inPacketsPerSecond = stats.StatsBlock[13].StatValue; m_outPacketsPerSecond = stats.StatsBlock[14].StatValue; m_unackedBytes = stats.StatsBlock[15].StatValue; m_agentFrameTime = stats.StatsBlock[16].StatValue; m_pendingDownloads = stats.StatsBlock[17].StatValue; m_pendingUploads = stats.StatsBlock[18].StatValue; m_activeScripts = stats.StatsBlock[19].StatValue; m_scriptLinesPerSecond = stats.ExtraStatsBlock[0].StatValue; } } }
using System; namespace angeldnd.dap { public static class Convertor { public const string Null = "null"; public const string UnknownType = "[N/A]"; public readonly static BoolConvertor BoolConvertor = new BoolConvertor(); public readonly static IntConvertor IntConvertor = new IntConvertor(); public readonly static LongConvertor LongConvertor = new LongConvertor(); public readonly static FloatConvertor FloatConvertor = new FloatConvertor(); public readonly static DoubleConvertor DoubleConvertor = new DoubleConvertor(); public readonly static StringConvertor StringConvertor = new StringConvertor(); public readonly static DataConvertor DataConvertor = new DataConvertor(); public readonly static DataTypeConvertor DataTypeConvertor = new DataTypeConvertor(); //These will NOT be registered. public readonly static DataCodeConvertor DataCodeConvertor = new DataCodeConvertor(); private static Vars _Convertors; static Convertor() { _Convertors = new Vars(null, "Convertors"); RegisterConvertor<bool>(BoolConvertor); RegisterConvertor<int>(IntConvertor); RegisterConvertor<long>(LongConvertor); RegisterConvertor<float>(FloatConvertor); RegisterConvertor<double>(DoubleConvertor); RegisterConvertor<string>(StringConvertor); RegisterConvertor<Data>(DataConvertor); RegisterConvertor<DataType>(DataTypeConvertor); } public static bool RegisterConvertor<T>(Convertor<T> convertor) { return _Convertors.AddVar(typeof(T).FullName, convertor) != null; } public static Convertor<T> GetConvertor<T>(bool isDebug = false) { if (isDebug) { return _Convertors.GetValue<Convertor<T>>(typeof(T).FullName, null); } else { return _Convertors.GetValue<Convertor<T>>(typeof(T).FullName); } } public static bool TryParse<T>(string str, out T val, bool isDebug = false) { Convertor<T> convertor = GetConvertor<T>(); if (convertor != null) { return convertor.TryParse(str, out val, isDebug); } else { val = default(T); Log.ErrorOrDebug(isDebug, "Parse Failed, Unknown Type: <{0}> {1}", GetTypeStr(typeof(T)), str); } return false; } public static T Parse<T>(string str) { Convertor<T> convertor = GetConvertor<T>(); if (convertor != null) { return convertor.Parse(str); } else { throw new DapException("Parse Failed, Unknown Type: <{0}> {1}", GetTypeStr(typeof(T)), str); } } public static string Convert<T>(T val) { Convertor<T> convertor = GetConvertor<T>(); if (convertor != null) { return convertor.Convert(val); } else { Log.Error("Convert Failed, Unknown Type: <{0}> {1}", GetTypeStr(typeof(T)), val); } return UnknownType; } private static InternalConvertor GetInternalConvertor(Type type) { if (type == null) return null; IVar v = _Convertors.Get(type.FullName, true); if (v != null) { return angeldnd.dap.DapExtension.As<InternalConvertor>(v.GetValue()); } return null; } public static string GetTypeStr(object val) { if (val == null) return UnknownType; return val.GetType().FullName; } public static string GetTypeStr(Type type) { return type == null ? UnknownType : type.FullName; } public static bool TryParse(Type type, string str, out object val, bool isDebug = false) { InternalConvertor convertor = GetInternalConvertor(type); if (convertor != null) { return convertor._TryParseInternal(str, out val, isDebug); } else { val = null; Log.ErrorOrDebug(isDebug, "Parse Failed, Unknown Type: <{0}> {1}", GetTypeStr(type), str); } return false; } public static object Parse(Type type, string str) { InternalConvertor convertor = GetInternalConvertor(type); if (convertor != null) { return convertor._ParseInternal(str); } else { throw new DapException("Parse Failed, Unknown Type: <{0}> {1}", GetTypeStr(type), str); } } //Not giving isDebug default value, othewise with get conflict with the generic version public static string Convert(object val, bool isDebug) { if (val == null) return Null; InternalConvertor convertor = GetInternalConvertor(val.GetType()); if (convertor != null) { return convertor._ConvertInternal(val); } else { Log.ErrorOrDebug(isDebug, "Convert Failed, Unknown Type: <{0}> {1}", GetTypeStr(val), val); return val.ToString(); } } } public interface IConvertor<T> { bool TryParse(string str, out T val, bool isDebug = false); T Parse(string str); string Convert(T val); } public abstract class InternalConvertor { internal abstract bool _TryParseInternal(string str, out object val, bool isDebug = false); internal abstract object _ParseInternal(string str); internal abstract string _ConvertInternal(object val); } public abstract class Convertor<T> : InternalConvertor, IConvertor<T> { internal override bool _TryParseInternal(string str, out object val, bool isDebug = false) { try { val = _ParseInternal(str); return true; } catch (Exception e) { Log.ErrorOrDebug(isDebug, "Parse Failed: <{0}> {1} -> \n{2}", typeof(T).FullName, str, e); } val = default(T); return false; } internal override object _ParseInternal(string str) { return Parse(str); } internal override string _ConvertInternal(object val) { T _val = angeldnd.dap.DapExtension.As<T>(val); return Convert(_val); } public bool TryParse(string str, out T val, bool isDebug = false) { try { val = Parse(str); return true; } catch (Exception e) { Log.ErrorOrDebug(isDebug, "Parse Failed: <{0}> {1} -> \n{2}", typeof(T).FullName, str, e); } val = default(T); return false; } public abstract T Parse(string str); public abstract string Convert(T val); } public class BoolConvertor : Convertor<bool> { public override string Convert(bool val) { return val ? "true" : "false"; } public override bool Parse(string str) { return str != null && str.ToLower() == "true"; } } public class IntConvertor : Convertor<int> { public override string Convert(int val) { return val.ToString(); } public override int Parse(string str) { return System.Convert.ToInt32(str); } } public class LongConvertor : Convertor<long> { public override string Convert(long val) { return val.ToString(); } public override long Parse(string str) { return System.Convert.ToInt64(str); } } public class FloatConvertor : Convertor<float> { public override string Convert(float val) { return val.ToString(); } public override float Parse(string str) { return System.Convert.ToSingle(str); } } public class DoubleConvertor : Convertor<double> { public override string Convert(double val) { return val.ToString(); } public override double Parse(string str) { return System.Convert.ToDouble(str); } } public class StringConvertor : Convertor<string> { public override string Convert(string val) { return val == null ? Convertor.Null : val.ToString(); } public override string Parse(string str) { return str; } } }