context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace YAMP.Sets { using System; using System.Collections.Generic; using YAMP.Converter; using YAMP; using YAMP.Exceptions; using System.Text; using System.IO; using ISetValueDictionary = System.Collections.Generic.ISet<SetValue.ValueWrap>; //SortedSet is NOT implemented in Silverlight. Borrowed implementation from CoreFX. using SortedSetValueWrap = YAMPSystem.Collections.Generic.SortedSet<SetValue.ValueWrap>; using HashSetValueWrap = System.Collections.Generic.HashSet<SetValue.ValueWrap>; using BaseType = YAMP.Value; /// <summary> /// The SetValue class. /// </summary> public sealed partial class SetValue : Value, IEquatable<SetValue> //, IFunction, ISetFunction { #region ctor /// <summary> /// Creates a new SetValue instance. /// </summary> public SetValue() : this(String.Empty, null, false) { } /// <summary> /// Creates a new unsorted instance with a name. /// </summary> /// <param name="name">The name of the set.</param> public SetValue(string name) : this(name, null, false) { } /// <summary> /// Creates a new instance with a name. /// </summary> /// <param name="name">The name of the set.</param> public SetValue(string name, bool ordered) : this(name, null, ordered) { } /// <summary> /// Creates a new instance and sets the values. /// </summary> /// <param name="name">The name ot the set.</param> /// <param name="set">The initial values to use.</param> public SetValue(string name, ISetValueDictionary set) : this(name, set, false) { } /// <summary> /// Creates a new instance and sets the values. /// </summary> /// <param name="name">The name ot the set.</param> /// <param name="set">The initial values to use.</param> /// <param name="set">Ordered or Unordered set.</param> public SetValue(string name, ISetValueDictionary set, bool ordered) { this._set = CreateSet(ordered, set); this.Name = name; this.ordered = ordered; } /// <summary> /// Creates a new instance and sets the values. /// </summary> /// <param name="name">The name ot the set.</param> /// <param name="set">The initial values to use.</param> /// <param name="set">Ordered or Unordered set.</param> public SetValue(string name, bool ordered, ScalarValue[] scalarValues) : this(name) { this._set = CreateSet(ordered, null); this.Name = name; this.ordered = ordered; for (int i = 0; i < scalarValues.Length; i++) { _set.Add(new ValueWrap(scalarValues[i])); } } private ISetValueDictionary CreateSet(bool ordered) { return CreateSet(ordered, null); } private static ISetValueDictionary CreateSet(bool ordered, ISetValueDictionary source) { if (source == null) return ordered ? (ISetValueDictionary)new SortedSetValueWrap() : (ISetValueDictionary)new HashSetValueWrap(); return ordered ? (ISetValueDictionary)new SortedSetValueWrap(source) : (ISetValueDictionary)new HashSetValueWrap(source); } #endregion #region Fields static readonly String Indentation = " "; readonly ISetValueDictionary _set; string _name = string.Empty; bool ordered = false; #endregion #region Properties /// <summary> /// Gets or sets the HashSet name. /// </summary> [StringToStringConverter] public String Name { get { return _name; } set { _name = value; } } public bool Sorted { get { return ordered; } private set { } } public ISetValueDictionary Set { get { return _set; } private set { } } #endregion #region Serialization /// <summary> /// Returns a copy of this object value instance. /// </summary> /// <returns>The cloned object value.</returns> public override Value Copy() { return new SetValue(Name, _set, Sorted); } /// <summary> /// Transforms the instance into a binary representation. /// </summary> /// <returns>The binary representation.</returns> public override Byte[] Serialize() { var mem = new MemoryStream(); SerializeString(mem, Name); SerializeString(mem, Sorted ? "O" : "U"); SerializeValueDictionary(mem, _set); return mem.ToArray(); } /// <summary> /// Transforms a binary representation into a new instance. /// </summary> /// <param name="content">The binary data.</param> /// <returns>The new instance.</returns> public override Value Deserialize(Byte[] content) { var mem = new MemoryStream(content); mem.Position = 0; string name = DeserializeString(mem); string setType = DeserializeString(mem); var unit = DeserializeSet(mem, name, setType == "O"); return unit; } #endregion #region Methods /// <summary> /// Registers the member operator. /// </summary> protected override void RegisterOperators() { Register.BinaryOperator(OpDefinitionsSet.EqOperator, typeof(SetValue), typeof(SetValue), (left, right) => new ScalarValue(((SetValue)left) == ((SetValue)right))); Register.BinaryOperator(OpDefinitionsSet.StandardNeqOperator, typeof(SetValue), typeof(SetValue), (left, right) => new ScalarValue(((SetValue)left) != ((SetValue)right))); Register.BinaryOperator(OpDefinitionsSet.AliasNeqOperator, typeof(SetValue), typeof(SetValue), (left, right) => new ScalarValue(((SetValue)left) != ((SetValue)right))); Register.BinaryOperator(OpDefinitionsSet.UnionOperator, typeof(SetValue), typeof(SetValue), (left, right) => SetValue.TUnion(((SetValue)left), new ArgumentsValue(right))); Register.BinaryOperator(OpDefinitionsSet.IntersectOperator, typeof(SetValue), typeof(SetValue), (left, right) => SetValue.TIntersect(((SetValue)left), new ArgumentsValue(right))); Register.BinaryOperator(OpDefinitionsSet.ExceptOperator, typeof(SetValue), typeof(SetValue), (left, right) => SetValue.TExcept(((SetValue)left), new ArgumentsValue(right))); Register.BinaryOperator(OpDefinitionsSet.ExceptXorOperator, typeof(SetValue), typeof(SetValue), (left, right) => SetValue.TExceptXor(((SetValue)left), new ArgumentsValue(right))); } /// <summary> /// Returns the string content of this instance. /// </summary> /// <param name="context">The context of the invocation.</param> /// <returns>The value of the object.</returns> public override String ToString(ParseContext context) { var sb = new StringBuilder(); sb.AppendLine("{"); sb.AppendLine(string.Format("Name = {0}, Sorted = {1}, Count = {2}", Name, Sorted, _set.Count)); foreach (var element in _set) { //sb.AppendLine(); sb.Append(element.ToString(context)); } sb.Append("}"); return sb.ToString(); } #endregion #region Helpers static String Indent(String value) { var lines = value.Split(new[] { Environment.NewLine }, StringSplitOptions.None); return String.Join(Environment.NewLine + Indentation, lines); } public static void SerializeString(MemoryStream mem, String value) { var bytes = Encoding.Unicode.GetBytes(value); var length = BitConverter.GetBytes(bytes.Length); mem.Write(length, 0, length.Length); mem.Write(bytes, 0, bytes.Length); } private void SerializeValueDictionary(MemoryStream mem, ISetValueDictionary set) { var bytes = BitConverter.GetBytes(set.Count); mem.Write(bytes, 0, bytes.Length); foreach (var setItem in set) { setItem.Serialize(mem); } } public static string DeserializeString(MemoryStream mem) { var buffer = new Byte[4]; mem.Read(buffer, 0, buffer.Length); var length = BitConverter.ToInt32(buffer, 0); buffer = new Byte[length]; mem.Read(buffer, 0, buffer.Length); return Encoding.Unicode.GetString(buffer, 0, buffer.Length); } private SetValue DeserializeSet(MemoryStream mem, string name, bool ordered) { var buffer = new Byte[sizeof(int)]; mem.Read(buffer, 0, buffer.Length); var count = BitConverter.ToInt32(buffer, 0); SetValue ret = new SetValue(name, null, ordered); var set = ret._set; for (int i = 0; i < count; i++) { ValueWrap item = new ValueWrap(); item.Deserialize(mem); set.Add(item); } return ret; } public override bool Equals(object obj) { return obj is SetValue && Equals((SetValue)obj); } /// <summary> /// Equality. /// </summary> /// <param name="l">Set l</param> /// <param name="r">Set r</param> /// <returns>l == r</returns> public static Boolean operator ==(SetValue l, SetValue r) { if (ReferenceEquals(l, r)) { return true; } if (ReferenceEquals(l, null) || ReferenceEquals(r, null)) { return false; } return l.Equals(r); } /// <summary> /// Inequality. /// </summary> /// <param name="l">Set l</param> /// <param name="r">Set r</param> /// <returns>l != r</returns> public static Boolean operator !=(SetValue l, SetValue r) { return !(l == r); } /// <summary> /// Equals implementation. Only care on Set's content /// </summary> /// <param name="other"></param> /// <returns></returns> public bool Equals(SetValue other) { if (ReferenceEquals(other, null)) return false; bool eq = this.Set.SetEquals(other.Set); return eq; } public override int GetHashCode() { int hash = this.Set.GetHashCode(); return hash; } /// <summary> /// Adds elements to a set /// </summary> /// <param name="scalarValues">The array of elements to add</param> /// <returns>Number of elements that didn't existed and were added</returns> public int AddElements(ScalarValue[] scalarValues) { int added = 0; for (int i = 0; i < scalarValues.Length; i++) { if (_set.Add(new ValueWrap(scalarValues[i]))) added++; } return added; } /// <summary> /// Removes elements from a set /// </summary> /// <param name="scalarValues">The array of elements to remove</param> /// <returns>Number of elements that didn't existed and were removed</returns> public int RemoveElements(ScalarValue[] scalarValues) { int removed = 0; for (int i = 0; i < scalarValues.Length; i++) { if (_set.Remove(new ValueWrap(scalarValues[i]))) removed++; } return removed; } #endregion #region Nested types /// <summary> /// Represents one Entry in the Set. /// </summary> public struct ValueWrap : IEquatable<ValueWrap>, IComparable<ValueWrap> { private BaseType _id; public ValueWrap(BaseType id) { _id = id; } public static implicit operator ValueWrap(NumericValue id) // explicit NumericValue to ValueWrap conversion operator { return new ValueWrap(id); } public static implicit operator ValueWrap(Int64 id) // explicit Int64 to ValueWrap conversion operator { return new ValueWrap(new ScalarValue(id)); } public static implicit operator ValueWrap(String id) // explicit String to ValueWrap conversion operator { return new ValueWrap(new StringValue(id)); } public BaseType ID { get { return _id; } private set { } } internal void SerializeID(MemoryStream mem, BaseType id) { SerializeValue(mem, id); } internal void SerializeValue(MemoryStream mem, Value val) { SetValue.SerializeString(mem, val.Header); var bytes = val.Serialize(); var bytesLen = BitConverter.GetBytes(bytes.Length); mem.Write(bytesLen, 0, bytesLen.Length); mem.Write(bytes, 0, bytes.Length); } internal void Serialize(MemoryStream mem) { SerializeID(mem, _id); } internal void DeserializeID(MemoryStream mem) { _id = DeserializeValue(mem); } internal Value DeserializeValue(MemoryStream mem) { string header = SetValue.DeserializeString(mem); var buffer = new Byte[sizeof(int)]; mem.Read(buffer, 0, buffer.Length); var len = BitConverter.ToInt32(buffer, 0); buffer = new Byte[len]; mem.Read(buffer, 0, buffer.Length); Value val = Value.Deserialize(header, buffer); return val; } internal void Deserialize(MemoryStream mem) { DeserializeID(mem); } public override string ToString() { return ToString(new ParseContext()); } internal string ToString(ParseContext context) { var sb = new StringBuilder(); sb.Append(Indentation); sb.AppendLine(string.Format("ID = {0}", _id)); return sb.ToString(); } public override int GetHashCode() { int hash = _id.GetHashCode(); return hash; } public static bool operator ==(ValueWrap x, ValueWrap y) { return x._id == y._id; } public static bool operator !=(ValueWrap x, ValueWrap y) { return !(x == y); } public override bool Equals(object obj) { return obj is ValueWrap && Equals((ValueWrap)obj); } public bool Equals(ValueWrap other) { bool eq = _id.Equals(other._id); return eq; } public int CompareTo(ValueWrap other) { Value left = this._id; Value right = other._id; if (left == null && right == null) return 0; if (right == null) return 1; if (left == null) return -1; if (left is ScalarValue && right is ScalarValue) return (left as ScalarValue).Value.CompareTo((right as ScalarValue).Value); if (left is StringValue && right is StringValue) return (left as StringValue).Value.CompareTo((right as StringValue).Value); //ScalarValues will always "preceed" strings... if (left is ScalarValue && right is StringValue) return -1; if (left is StringValue && right is ScalarValue) return 1; //Other types cannot be compared... throw new ArgumentException("OrderedSet Element is not ScalarValue neither StringValue"); } } #endregion #region MemberFunctionsHelpers /// <summary> /// Create a new Set, with the Union of Sets /// </summary> /// <param name="set">The set</param> /// <param name="args">Sets to Union</param> /// <returns>The new set</returns> internal static SetValue TUnion(SetValue set, ArgumentsValue args) { string newName = string.Format("({0}", set.Name); var newSet = set.Copy() as SetValue; int iArgs = 1; //First is "name" foreach (var arg in args) { iArgs++; SetValue otherSet = arg as SetValue; newName += string.Format("+{0}", otherSet.Name); if (!ReferenceEquals(otherSet, null)) newSet.Set.UnionWith(otherSet.Set); else throw new YAMPArgumentInvalidException("Element is not SetValue", iArgs); } newName += ")"; newSet.Name = newName; return newSet; } /// <summary> /// Create a new Set, with the Intersection of Sets /// </summary> /// <param name="set">The set</param> /// <param name="args">Sets to Intersect</param> /// <returns>The new set</returns> internal static SetValue TIntersect(SetValue set, ArgumentsValue args) { string newName = string.Format("({0}", set.Name); var newSet = set.Copy() as SetValue; int iArgs = 1; //First is "name" foreach (var arg in args) { iArgs++; SetValue otherSet = arg as SetValue; newName += string.Format("&{0}", otherSet.Name); if (!ReferenceEquals(otherSet, null)) newSet.Set.IntersectWith(otherSet.Set); else throw new YAMPArgumentInvalidException("Element is not SetValue", iArgs); } newName += ")"; newSet.Name = newName; return newSet; } /// <summary> /// Create a new Set, with the first Set Except(ed) of the other Sets /// </summary> /// <param name="set">The set</param> /// <param name="args">Sets to Except</param> /// <returns>The new set</returns> internal static SetValue TExcept(SetValue set, ArgumentsValue args) { string newName = string.Format("({0}", set.Name); var newSet = set.Copy() as SetValue; int iArgs = 1; //First is "name" foreach (var arg in args) { iArgs++; SetValue otherSet = arg as SetValue; newName += string.Format("-{0}", otherSet.Name); if (!ReferenceEquals(otherSet, null)) newSet.Set.ExceptWith(otherSet.Set); else throw new YAMPArgumentInvalidException("Element is not SetValue", iArgs); } newName += ")"; newSet.Name = newName; return newSet; } /// <summary> /// Create a new Set, with the Symmetric Except(XOR) of all Sets /// </summary> /// <param name="set">The set</param> /// <param name="args">Sets to Except(XOR)</param> /// <returns>The new set</returns> internal static SetValue TExceptXor(SetValue set, ArgumentsValue args) { string newName = string.Format("({0}", set.Name); var newSet = set.Copy() as SetValue; int iArgs = 1; //First is "name" foreach (var arg in args) { iArgs++; SetValue otherSet = arg as SetValue; newName += string.Format("^{0}", otherSet.Name); if (!ReferenceEquals(otherSet, null)) newSet.Set.SymmetricExceptWith(otherSet.Set); else throw new YAMPArgumentInvalidException("Element is not SetValue", iArgs); } newName += ")"; newSet.Name = newName; return newSet; } /// <summary> /// Get the number of elements in the Set /// </summary> /// <param name="set"></param> /// <returns>Number of elements in the set</returns> internal static ScalarValue TCount(SetValue set) { if (ReferenceEquals(set, null)) throw new YAMPArgumentValueException("null", new string[] { "Set" }); return new ScalarValue(set.Set.Count); } /// <summary> /// Compares two sets /// </summary> /// <param name="set"></param> /// <returns></returns> internal static ScalarValue TEquals(SetValue set1, SetValue set2) { //They should never be null if (ReferenceEquals(set1, null) || ReferenceEquals(set2, null)) return new ScalarValue(false); return new ScalarValue(set1.Set.SetEquals(set2.Set)); } public MatrixValue ToMatrix() { return TToMatrix(this); } internal static MatrixValue TToMatrix(SetValue set) { List<ScalarValue> values = new List<ScalarValue>(); foreach (var el in set.Set) { if (el.ID is ScalarValue) values.Add(el.ID as ScalarValue); } MatrixValue matrix = new MatrixValue(values.ToArray(), 1, values.Count); return matrix; } #endregion #region MemberFunctions [Description("The SetAdd Object function.")] [Kind(PopularKinds.Function)] sealed class AddFunction : MemberFunction { [Description("Adds the element to the Set, and returns the set. If Matrix, all its elements will be added")] public SetValue Function(Value id) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetAdd"); if (id is MatrixValue) { set.AddElements((id as MatrixValue).ToArray()); } else { set.Set.Add(new SetValue.ValueWrap(id)); } return set; } } [Description("The SetAsSort Object function.")] [Kind(PopularKinds.Function)] sealed class AsSortFunction : MemberFunction { [Description("Creates a copied sorted Set")] public SetValue Function() { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetAsSort"); var newSet = new SetValue(set.Name, set.Set, true); return newSet; } } [Description("The SetAsUnsort Object function.")] [Kind(PopularKinds.Function)] sealed class AsUnsortFunction : MemberFunction { [Description("Creates a copied unsorted Set")] public SetValue Function() { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetAsUnsort"); var newSet = new SetValue(set.Name, set.Set, false); return newSet; } } [Description("The SetContains Object function.")] [Kind(PopularKinds.Function)] sealed class ContainsFunction : MemberFunction { [Description("Determines whether the set contains the given element's id")] public ScalarValue Function(Value id) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetContains"); bool eq = set.Set.Contains(new SetValue.ValueWrap(id)); return new ScalarValue(eq); } } [Description("The SetCount Object function.")] [Kind(PopularKinds.Function)] sealed class CountFunction : MemberFunction //, IObjectFunctions { [Description("Get the number of elements in the Set")] public ScalarValue Function() { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetCount"); return new ScalarValue(set.Set.Count); } } [Description("The SetEquals Object function.")] [Kind(PopularKinds.Function)] sealed class EqualsFunction : MemberFunction { [Description("Compares two sets")] public ScalarValue Function(SetValue set2) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetEquals"); bool eq = set.Set.SetEquals(set2.Set); return new ScalarValue(eq); } } [Description("The SetExcept Object function.")] [Kind(PopularKinds.Function)] sealed class ExceptFunction : MemberFunction { [Description("Create a new Set, with the first Set Except(ed) of the other Sets")] [Arguments(0, 0)] public SetValue Function(ArgumentsValue args) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetExcept"); return SetValue.TExcept(set, args); } } [Description("The SetExceptXor Object function.")] [Kind(PopularKinds.Function)] sealed class ExceptXorFunction : MemberFunction { [Description("Create a new Set, with the Symmetric Except(XOR) of all Sets")] [Arguments(0, 0)] public SetValue Function(ArgumentsValue args) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetExceptXor"); return SetValue.TExceptXor(set, args); } } [Description("The SetIntersect Object function.")] [Kind(PopularKinds.Function)] sealed class IntersectFunction : MemberFunction { [Description("Create a new Set, with the Intersection of Sets")] [Arguments(0, 0)] public SetValue Function(ArgumentsValue args) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetIntersect"); return SetValue.TIntersect(set, args); } } [Description("The SetIsProperSubsetOf Object function.")] [Kind(PopularKinds.Function)] sealed class IsProperSubsetOfFunction : MemberFunction { [Description("Determines whether set1 is a proper subset of set2")] public ScalarValue Function(SetValue set2) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetIsProperSubsetOf"); bool eq = set.Set.IsProperSubsetOf(set2.Set); return new ScalarValue(eq); } } [Description("The SetIsProperSupersetOf Object function.")] [Kind(PopularKinds.Function)] sealed class IsProperSupersetOfFunction : MemberFunction { [Description("Determines whether set1 is a proper superset of set2")] public ScalarValue Function(SetValue set2) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetIsProperSupersetOf"); bool eq = set.Set.IsProperSupersetOf(set2.Set); return new ScalarValue(eq); } } [Description("The SetIsSorted Object function.")] [Kind(PopularKinds.Function)] sealed class IsSortedFunction : MemberFunction { [Description("Determines whether set is of Sorted type")] public ScalarValue Function() { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetIsSorted"); bool eq = set.Sorted; return new ScalarValue(eq); } } [Description("The SetIsSubsetOf Object function.")] [Kind(PopularKinds.Function)] sealed class IsSubsetOfFunction : MemberFunction { [Description("Determines whether set1 is a subset of set2")] public ScalarValue Function(SetValue set2) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetIsSubsetOf"); bool eq = set.Set.IsSubsetOf(set2.Set); return new ScalarValue(eq); } } [Description("The SetIsSupersetOf Object function.")] [Kind(PopularKinds.Function)] sealed class IsSupersetOfFunction : MemberFunction { [Description("Determines whether set1 is a superset of set2")] public ScalarValue Function(SetValue set2) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetIsSupersetOf"); bool eq = set.Set.IsSupersetOf(set2.Set); return new ScalarValue(eq); } } [Description("The SetOverlaps Object function.")] [Kind(PopularKinds.Function)] sealed class OverlapsFunction : MemberFunction { [Description("Determines whether the sets overlap over at least one common element")] public ScalarValue Function(SetValue set2) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetOverlaps"); bool eq = set.Set.Overlaps(set2.Set); return new ScalarValue(eq); } } [Description("The SetRemove Object function.")] [Kind(PopularKinds.Function)] sealed class RemoveFunction : MemberFunction { [Description("Removes the specified element from the Set, and returns the set. If Matrix, all its elements will be removed")] public SetValue Function(Value id) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetRemove"); if (id is MatrixValue) { set.RemoveElements((id as MatrixValue).ToArray()); } else { set.Set.Remove(new SetValue.ValueWrap(id)); } return set; } } [Description("The SetToMatrix Object function.")] [Kind(PopularKinds.Function)] sealed class ToMatrixFunction : MemberFunction { [Description("Create a single row Matrix with all Numeric keys")] public MatrixValue Function() { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetToMatrix"); return SetValue.TToMatrix(set); } } [Description("The SetUnion Object function.")] [Kind(PopularKinds.Function)] sealed class UnionFunction : MemberFunction { [Description("Create a new Set, with the Union of Sets")] [Arguments(0, 0)] public SetValue Function(ArgumentsValue args) { SetValue set = @this as SetValue; if (ReferenceEquals(set, null)) throw new YAMPSetsFunctionNotMemberException("SetUnion"); return SetValue.TUnion(set, args); } } #endregion } }
// Copyright 2021 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 gagvc = Google.Ads.GoogleAds.V8.Common; using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedLabelServiceClientTest { [Category("Autogenerated")][Test] public void GetLabelRequestObject() { moq::Mock<LabelService.LabelServiceClient> mockGrpcClient = new moq::Mock<LabelService.LabelServiceClient>(moq::MockBehavior.Strict); GetLabelRequest request = new GetLabelRequest { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; gagvr::Label expectedResponse = new gagvr::Label { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), Status = gagve::LabelStatusEnum.Types.LabelStatus.Enabled, TextLabel = new gagvc::TextLabel(), Id = -6774108720365892680L, LabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LabelServiceClient client = new LabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::Label response = client.GetLabel(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetLabelRequestObjectAsync() { moq::Mock<LabelService.LabelServiceClient> mockGrpcClient = new moq::Mock<LabelService.LabelServiceClient>(moq::MockBehavior.Strict); GetLabelRequest request = new GetLabelRequest { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; gagvr::Label expectedResponse = new gagvr::Label { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), Status = gagve::LabelStatusEnum.Types.LabelStatus.Enabled, TextLabel = new gagvc::TextLabel(), Id = -6774108720365892680L, LabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Label>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LabelServiceClient client = new LabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::Label responseCallSettings = await client.GetLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Label responseCancellationToken = await client.GetLabelAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetLabel() { moq::Mock<LabelService.LabelServiceClient> mockGrpcClient = new moq::Mock<LabelService.LabelServiceClient>(moq::MockBehavior.Strict); GetLabelRequest request = new GetLabelRequest { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; gagvr::Label expectedResponse = new gagvr::Label { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), Status = gagve::LabelStatusEnum.Types.LabelStatus.Enabled, TextLabel = new gagvc::TextLabel(), Id = -6774108720365892680L, LabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LabelServiceClient client = new LabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::Label response = client.GetLabel(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetLabelAsync() { moq::Mock<LabelService.LabelServiceClient> mockGrpcClient = new moq::Mock<LabelService.LabelServiceClient>(moq::MockBehavior.Strict); GetLabelRequest request = new GetLabelRequest { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; gagvr::Label expectedResponse = new gagvr::Label { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), Status = gagve::LabelStatusEnum.Types.LabelStatus.Enabled, TextLabel = new gagvc::TextLabel(), Id = -6774108720365892680L, LabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Label>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LabelServiceClient client = new LabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::Label responseCallSettings = await client.GetLabelAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Label responseCancellationToken = await client.GetLabelAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetLabelResourceNames() { moq::Mock<LabelService.LabelServiceClient> mockGrpcClient = new moq::Mock<LabelService.LabelServiceClient>(moq::MockBehavior.Strict); GetLabelRequest request = new GetLabelRequest { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; gagvr::Label expectedResponse = new gagvr::Label { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), Status = gagve::LabelStatusEnum.Types.LabelStatus.Enabled, TextLabel = new gagvc::TextLabel(), Id = -6774108720365892680L, LabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LabelServiceClient client = new LabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::Label response = client.GetLabel(request.ResourceNameAsLabelName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetLabelResourceNamesAsync() { moq::Mock<LabelService.LabelServiceClient> mockGrpcClient = new moq::Mock<LabelService.LabelServiceClient>(moq::MockBehavior.Strict); GetLabelRequest request = new GetLabelRequest { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; gagvr::Label expectedResponse = new gagvr::Label { ResourceNameAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), Status = gagve::LabelStatusEnum.Types.LabelStatus.Enabled, TextLabel = new gagvc::TextLabel(), Id = -6774108720365892680L, LabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Label>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LabelServiceClient client = new LabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::Label responseCallSettings = await client.GetLabelAsync(request.ResourceNameAsLabelName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Label responseCancellationToken = await client.GetLabelAsync(request.ResourceNameAsLabelName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateLabelsRequestObject() { moq::Mock<LabelService.LabelServiceClient> mockGrpcClient = new moq::Mock<LabelService.LabelServiceClient>(moq::MockBehavior.Strict); MutateLabelsRequest request = new MutateLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new LabelOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateLabelsResponse expectedResponse = new MutateLabelsResponse { Results = { new MutateLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateLabels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LabelServiceClient client = new LabelServiceClientImpl(mockGrpcClient.Object, null); MutateLabelsResponse response = client.MutateLabels(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateLabelsRequestObjectAsync() { moq::Mock<LabelService.LabelServiceClient> mockGrpcClient = new moq::Mock<LabelService.LabelServiceClient>(moq::MockBehavior.Strict); MutateLabelsRequest request = new MutateLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new LabelOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateLabelsResponse expectedResponse = new MutateLabelsResponse { Results = { new MutateLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateLabelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateLabelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LabelServiceClient client = new LabelServiceClientImpl(mockGrpcClient.Object, null); MutateLabelsResponse responseCallSettings = await client.MutateLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateLabelsResponse responseCancellationToken = await client.MutateLabelsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateLabels() { moq::Mock<LabelService.LabelServiceClient> mockGrpcClient = new moq::Mock<LabelService.LabelServiceClient>(moq::MockBehavior.Strict); MutateLabelsRequest request = new MutateLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new LabelOperation(), }, }; MutateLabelsResponse expectedResponse = new MutateLabelsResponse { Results = { new MutateLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateLabels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LabelServiceClient client = new LabelServiceClientImpl(mockGrpcClient.Object, null); MutateLabelsResponse response = client.MutateLabels(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateLabelsAsync() { moq::Mock<LabelService.LabelServiceClient> mockGrpcClient = new moq::Mock<LabelService.LabelServiceClient>(moq::MockBehavior.Strict); MutateLabelsRequest request = new MutateLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new LabelOperation(), }, }; MutateLabelsResponse expectedResponse = new MutateLabelsResponse { Results = { new MutateLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateLabelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateLabelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LabelServiceClient client = new LabelServiceClientImpl(mockGrpcClient.Object, null); MutateLabelsResponse responseCallSettings = await client.MutateLabelsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateLabelsResponse responseCancellationToken = await client.MutateLabelsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Apache.Cordova { // Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue']" [global::Android.Runtime.Register ("org/apache/cordova/NativeToJsMessageQueue", DoNotGenerateAcw=true)] public partial class NativeToJsMessageQueue : global::Java.Lang.Object { // Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue.BridgeMode']" [global::Android.Runtime.Register ("org/apache/cordova/NativeToJsMessageQueue$BridgeMode", DoNotGenerateAcw=true)] public abstract partial class BridgeMode : global::Java.Lang.Object { protected BridgeMode (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} } [global::Android.Runtime.Register ("org/apache/cordova/NativeToJsMessageQueue$BridgeMode", DoNotGenerateAcw=true)] internal partial class BridgeModeInvoker : BridgeMode { public BridgeModeInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {} protected override global::System.Type ThresholdType { get { return typeof (BridgeModeInvoker); } } } // Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue.JsMessage']" [global::Android.Runtime.Register ("org/apache/cordova/NativeToJsMessageQueue$JsMessage", DoNotGenerateAcw=true)] public partial class JsMessage : global::Java.Lang.Object { protected JsMessage (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} } // Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue.LoadUrlBridgeMode']" [global::Android.Runtime.Register ("org/apache/cordova/NativeToJsMessageQueue$LoadUrlBridgeMode", DoNotGenerateAcw=true)] public partial class LoadUrlBridgeMode : global::Org.Apache.Cordova.NativeToJsMessageQueue.BridgeMode { protected LoadUrlBridgeMode (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} } // Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue.OnlineEventsBridgeMode']" [global::Android.Runtime.Register ("org/apache/cordova/NativeToJsMessageQueue$OnlineEventsBridgeMode", DoNotGenerateAcw=true)] public partial class OnlineEventsBridgeMode : global::Org.Apache.Cordova.NativeToJsMessageQueue.BridgeMode { protected OnlineEventsBridgeMode (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} } // Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue.PollingBridgeMode']" [global::Android.Runtime.Register ("org/apache/cordova/NativeToJsMessageQueue$PollingBridgeMode", DoNotGenerateAcw=true)] public partial class PollingBridgeMode : global::Org.Apache.Cordova.NativeToJsMessageQueue.BridgeMode { protected PollingBridgeMode (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} } // Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue.PrivateApiBridgeMode']" [global::Android.Runtime.Register ("org/apache/cordova/NativeToJsMessageQueue$PrivateApiBridgeMode", DoNotGenerateAcw=true)] public partial class PrivateApiBridgeMode : global::Org.Apache.Cordova.NativeToJsMessageQueue.BridgeMode { protected PrivateApiBridgeMode (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/apache/cordova/NativeToJsMessageQueue", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (NativeToJsMessageQueue); } } protected NativeToJsMessageQueue (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Lorg_apache_cordova_CordovaWebView_Lorg_apache_cordova_CordovaInterface_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue']/constructor[@name='NativeToJsMessageQueue' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.CordovaWebView'] and parameter[2][@type='org.apache.cordova.CordovaInterface']]" [Register (".ctor", "(Lorg/apache/cordova/CordovaWebView;Lorg/apache/cordova/CordovaInterface;)V", "")] public NativeToJsMessageQueue (global::Org.Apache.Cordova.CordovaWebView p0, global::Org.Apache.Cordova.ICordovaInterface p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (NativeToJsMessageQueue)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/CordovaWebView;Lorg/apache/cordova/CordovaInterface;)V", new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/CordovaWebView;Lorg/apache/cordova/CordovaInterface;)V", new JValue (p0), new JValue (p1)); return; } if (id_ctor_Lorg_apache_cordova_CordovaWebView_Lorg_apache_cordova_CordovaInterface_ == IntPtr.Zero) id_ctor_Lorg_apache_cordova_CordovaWebView_Lorg_apache_cordova_CordovaInterface_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/CordovaWebView;Lorg/apache/cordova/CordovaInterface;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_CordovaWebView_Lorg_apache_cordova_CordovaInterface_, new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_CordovaWebView_Lorg_apache_cordova_CordovaInterface_, new JValue (p0), new JValue (p1)); } static Delegate cb_isBridgeEnabled; #pragma warning disable 0169 static Delegate GetIsBridgeEnabledHandler () { if (cb_isBridgeEnabled == null) cb_isBridgeEnabled = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsBridgeEnabled); return cb_isBridgeEnabled; } static bool n_IsBridgeEnabled (IntPtr jnienv, IntPtr native__this) { global::Org.Apache.Cordova.NativeToJsMessageQueue __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.NativeToJsMessageQueue> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.IsBridgeEnabled; } #pragma warning restore 0169 static IntPtr id_isBridgeEnabled; public virtual bool IsBridgeEnabled { // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue']/method[@name='isBridgeEnabled' and count(parameter)=0]" [Register ("isBridgeEnabled", "()Z", "GetIsBridgeEnabledHandler")] get { if (id_isBridgeEnabled == IntPtr.Zero) id_isBridgeEnabled = JNIEnv.GetMethodID (class_ref, "isBridgeEnabled", "()Z"); if (GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (Handle, id_isBridgeEnabled); else return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isBridgeEnabled", "()Z")); } } static Delegate cb_addJavaScript_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetAddJavaScript_Ljava_lang_String_Handler () { if (cb_addJavaScript_Ljava_lang_String_ == null) cb_addJavaScript_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_AddJavaScript_Ljava_lang_String_); return cb_addJavaScript_Ljava_lang_String_; } static void n_AddJavaScript_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Apache.Cordova.NativeToJsMessageQueue __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.NativeToJsMessageQueue> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); __this.AddJavaScript (p0); } #pragma warning restore 0169 static IntPtr id_addJavaScript_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue']/method[@name='addJavaScript' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("addJavaScript", "(Ljava/lang/String;)V", "GetAddJavaScript_Ljava_lang_String_Handler")] public virtual void AddJavaScript (string p0) { if (id_addJavaScript_Ljava_lang_String_ == IntPtr.Zero) id_addJavaScript_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "addJavaScript", "(Ljava/lang/String;)V"); IntPtr native_p0 = JNIEnv.NewString (p0); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_addJavaScript_Ljava_lang_String_, new JValue (native_p0)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "addJavaScript", "(Ljava/lang/String;)V"), new JValue (native_p0)); JNIEnv.DeleteLocalRef (native_p0); } static Delegate cb_addPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetAddPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_Handler () { if (cb_addPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_ == null) cb_addPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_AddPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_); return cb_addPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_; } static void n_AddPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Org.Apache.Cordova.NativeToJsMessageQueue __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.NativeToJsMessageQueue> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Apache.Cordova.PluginResult p0 = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (native_p0, JniHandleOwnership.DoNotTransfer); string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer); __this.AddPluginResult (p0, p1); } #pragma warning restore 0169 static IntPtr id_addPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue']/method[@name='addPluginResult' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.PluginResult'] and parameter[2][@type='java.lang.String']]" [Register ("addPluginResult", "(Lorg/apache/cordova/PluginResult;Ljava/lang/String;)V", "GetAddPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_Handler")] public virtual void AddPluginResult (global::Org.Apache.Cordova.PluginResult p0, string p1) { if (id_addPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_ == IntPtr.Zero) id_addPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "addPluginResult", "(Lorg/apache/cordova/PluginResult;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_addPluginResult_Lorg_apache_cordova_PluginResult_Ljava_lang_String_, new JValue (p0), new JValue (native_p1)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "addPluginResult", "(Lorg/apache/cordova/PluginResult;Ljava/lang/String;)V"), new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); } static Delegate cb_popAndEncode_Z; #pragma warning disable 0169 static Delegate GetPopAndEncode_ZHandler () { if (cb_popAndEncode_Z == null) cb_popAndEncode_Z = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool, IntPtr>) n_PopAndEncode_Z); return cb_popAndEncode_Z; } static IntPtr n_PopAndEncode_Z (IntPtr jnienv, IntPtr native__this, bool p0) { global::Org.Apache.Cordova.NativeToJsMessageQueue __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.NativeToJsMessageQueue> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.PopAndEncode (p0)); } #pragma warning restore 0169 static IntPtr id_popAndEncode_Z; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue']/method[@name='popAndEncode' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("popAndEncode", "(Z)Ljava/lang/String;", "GetPopAndEncode_ZHandler")] public virtual string PopAndEncode (bool p0) { if (id_popAndEncode_Z == IntPtr.Zero) id_popAndEncode_Z = JNIEnv.GetMethodID (class_ref, "popAndEncode", "(Z)Ljava/lang/String;"); if (GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_popAndEncode_Z, new JValue (p0)), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "popAndEncode", "(Z)Ljava/lang/String;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static Delegate cb_reset; #pragma warning disable 0169 static Delegate GetResetHandler () { if (cb_reset == null) cb_reset = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Reset); return cb_reset; } static void n_Reset (IntPtr jnienv, IntPtr native__this) { global::Org.Apache.Cordova.NativeToJsMessageQueue __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.NativeToJsMessageQueue> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Reset (); } #pragma warning restore 0169 static IntPtr id_reset; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue']/method[@name='reset' and count(parameter)=0]" [Register ("reset", "()V", "GetResetHandler")] public virtual void Reset () { if (id_reset == IntPtr.Zero) id_reset = JNIEnv.GetMethodID (class_ref, "reset", "()V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_reset); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "reset", "()V")); } static Delegate cb_setBridgeMode_I; #pragma warning disable 0169 static Delegate GetSetBridgeMode_IHandler () { if (cb_setBridgeMode_I == null) cb_setBridgeMode_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_SetBridgeMode_I); return cb_setBridgeMode_I; } static void n_SetBridgeMode_I (IntPtr jnienv, IntPtr native__this, int p0) { global::Org.Apache.Cordova.NativeToJsMessageQueue __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.NativeToJsMessageQueue> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.SetBridgeMode (p0); } #pragma warning restore 0169 static IntPtr id_setBridgeMode_I; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue']/method[@name='setBridgeMode' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("setBridgeMode", "(I)V", "GetSetBridgeMode_IHandler")] public virtual void SetBridgeMode (int p0) { if (id_setBridgeMode_I == IntPtr.Zero) id_setBridgeMode_I = JNIEnv.GetMethodID (class_ref, "setBridgeMode", "(I)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setBridgeMode_I, new JValue (p0)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setBridgeMode", "(I)V"), new JValue (p0)); } static Delegate cb_setPaused_Z; #pragma warning disable 0169 static Delegate GetSetPaused_ZHandler () { if (cb_setPaused_Z == null) cb_setPaused_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_SetPaused_Z); return cb_setPaused_Z; } static void n_SetPaused_Z (IntPtr jnienv, IntPtr native__this, bool p0) { global::Org.Apache.Cordova.NativeToJsMessageQueue __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.NativeToJsMessageQueue> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.SetPaused (p0); } #pragma warning restore 0169 static IntPtr id_setPaused_Z; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='NativeToJsMessageQueue']/method[@name='setPaused' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setPaused", "(Z)V", "GetSetPaused_ZHandler")] public virtual void SetPaused (bool p0) { if (id_setPaused_Z == IntPtr.Zero) id_setPaused_Z = JNIEnv.GetMethodID (class_ref, "setPaused", "(Z)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setPaused_Z, new JValue (p0)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setPaused", "(Z)V"), new JValue (p0)); } } }
using System; using System.Collections.Generic; using NUnit.Framework; using Palaso.Annotations; using Palaso.Tests.Code; using Palaso.Text; namespace Palaso.Tests.Text { [TestFixture] public class LanguageFormIClonableGenericTests:IClonableGenericTests<Annotatable> { public override Annotatable CreateNewClonable() { return new LanguageForm(); } public override string ExceptionList { //_parent: We are doing top down clones. Children shouldn't make clones of their parents, but parents of their children. get { return "|_parent|"; } } public override string EqualsExceptionList { //_spans: is a List<T> which doesn't compare well with Equals (two separate empty lists are deemed different for example) get { return "|_spans|"; } } protected override List<ValuesToSet> DefaultValuesForTypes { get { return new List<ValuesToSet> { new ValuesToSet("string", "not string"), new ValuesToSet(new Annotation{IsOn = false}, new Annotation{IsOn = true}), new ValuesToSet(new List<LanguageForm.FormatSpan>(), new List<LanguageForm.FormatSpan>{new LanguageForm.FormatSpan()}) }; } } } [TestFixture] public class LanguageFormTest { LanguageForm _languageFormToCompare; LanguageForm _languageForm; [SetUp] public void Setup() { _languageFormToCompare = new LanguageForm(); _languageForm = new LanguageForm(); } [Test] public void CompareTo_Null_ReturnsGreater() { _languageFormToCompare = null; Assert.AreEqual(1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlphabeticallyEarlierWritingSystemIdWithIdenticalForm_ReturnsLess() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "en"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(-1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlpahbeticallyLaterWritingSystemIdWithIdenticalForm_ReturnsGreater() { _languageForm.WritingSystemId = "en"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_IdenticalWritingSystemIdWithIdenticalForm_Returns_Equal() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(0, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlphabeticallyEarlierFormWithIdenticalWritingSystem_ReturnsLess() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word2"; Assert.AreEqual(-1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlphabeticallyLaterFormWithIdenticalWritingSystem_ReturnsGreater() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word2"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_IdenticalFormWithIdenticalWritingSystem_ReturnsEqual() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(0, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlphabeticallyEarlierWritingSystemAlphabeticallyLaterForm_ReturnsLess() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word2"; _languageFormToCompare.WritingSystemId = "en"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(-1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlphabeticallyEarlierFormAlphabeticallyLaterWritingSystem_ReturnsGreater() { _languageForm.WritingSystemId = "en"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word2"; Assert.AreEqual(1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void Equals_SameObject_True() { var form = new LanguageForm(); Assert.That(form.Equals(form), Is.True); } [Test] public void Equals_OneStarredOtherIsNot_False() { var form1 = new LanguageForm(); var form2 = new LanguageForm(); form1.IsStarred = true; Assert.That(form1.Equals(form2), Is.False); } [Test] public void Equals_OneContainsWritingSystemOtherDoesNot_False() { var form1 = new LanguageForm{WritingSystemId = "en"}; var form2 = new LanguageForm{WritingSystemId = "de"}; Assert.That(form1.Equals(form2), Is.False); } [Test] public void Equals_OneContainsFormInWritingSystemOtherDoesNot_False() { var form1 = new LanguageForm { WritingSystemId = "en", Form = "form1"}; var form2 = new LanguageForm { WritingSystemId = "en", Form = "form2" }; Assert.That(form1.Equals(form2), Is.False); } [Test] public void Equals_StarredWritingSystemAndFormAreIdentical_True() { var form1 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; var form2 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; Assert.That(form1.Equals(form2), Is.True); } [Test] public void Equals_Null_False() { var form1 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; LanguageForm form2 = null; Assert.That(form1.Equals(form2), Is.False); } [Test] public void ObjectEquals_SameObject_True() { var form = new LanguageForm(); Assert.That(form.Equals((object) form), Is.True); } [Test] public void ObjectEquals_OneStarredOtherIsNot_False() { var form1 = new LanguageForm(); var form2 = new LanguageForm(); form1.IsStarred = true; Assert.That(form1.Equals((object)form2), Is.False); } [Test] public void ObjectEquals_OneContainsWritingSystemOtherDoesNot_False() { var form1 = new LanguageForm { WritingSystemId = "en" }; var form2 = new LanguageForm { WritingSystemId = "de" }; Assert.That(form1.Equals((object)form2), Is.False); } [Test] public void ObjectEquals_OneContainsFormInWritingSystemOtherDoesNot_False() { var form1 = new LanguageForm { WritingSystemId = "en", Form = "form1" }; var form2 = new LanguageForm { WritingSystemId = "en", Form = "form2" }; Assert.That(form1.Equals((object)form2), Is.False); } [Test] public void ObjectEquals_StarredWritingSystemAndFormAreIdentical_True() { var form1 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; var form2 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; Assert.That(form1.Equals((object)form2), Is.True); } [Test] public void ObjectEquals_Null_False() { var form1 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; LanguageForm form2 = null; Assert.That(form1.Equals((object)form2), Is.False); } [Test] public void UpdateSpans_Insert() { // In these tests, we're testing (inserting) edits to the formatted string // "This is a <span class='Strong'>test</span> of <span class='Weak'>something</span> or other." // See http://jira.palaso.org/issues/browse/WS-34799 for a discussion of what we want to achieve. List<LanguageForm.FormatSpan> spans = new List<LanguageForm.FormatSpan>(); string oldString = "This is a test of something or other."; // before any spans (add 3 characters) var expected = CreateSpans(spans, 3, 0, 3, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This isn't a test of something or other.", spans); VerifySpans(expected, spans); // before any spans, but right next to the first span (add 5 characters) expected = CreateSpans(spans, 5, 0, 5, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a good test of something or other.", spans); VerifySpans(expected, spans); // after any spans (add 5 characters, but spans don't change) expected = CreateSpans(spans, 0, 0, 0, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a test of something else or other.", spans); VerifySpans(expected, spans); // inside the first span (increase its length by 2) expected = CreateSpans(spans, 0, 2, 2, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a tessst of something or other.", spans); VerifySpans(expected, spans); // after the first span, but right next to it (increase its length by 3) expected = CreateSpans(spans, 0, 3, 3, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a testing of something or other.", spans); VerifySpans(expected, spans); // inside the second span (increase its length by 9) expected = CreateSpans(spans, 0, 0, 0, 9); LanguageForm.AdjustSpansForTextChange(oldString, "This is a test of some kind of thing or other.", spans); VerifySpans(expected, spans); // between the two spans (effectively add 1 character) expected = CreateSpans(spans, 0, 0, 1, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a test for something or other.", spans); VerifySpans(expected, spans); } [Test] public void AdjustSpans_Delete() { // In these tests, we're testing (deleting) edits to the formatted string // "This is a <span class='Strong'>test</span> of <span class='Weak'>something</span> or other." // See http://jira.palaso.org/issues/browse/WS-34799 for a discussion of what we want to achieve. List<LanguageForm.FormatSpan> spans = new List<LanguageForm.FormatSpan>(); string oldString = "This is a test of something or other."; // before any spans (remove 3 characters) var expected = CreateSpans(spans, -3, 0, -3, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This a test of something or other.", spans); VerifySpans(expected, spans); // before any spans, but next to first span (remove 2 characters) expected = CreateSpans(spans, -2, 0, -2, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is test of something or other.", spans); VerifySpans(expected, spans); // start before any spans, but including part of first span (remove 2 before and 2 inside span) expected = CreateSpans(spans, -2, -2, -4, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is st of something or other.", spans); VerifySpans(expected, spans); // start before any spans, but extending past first span (remove 2 before, 4 inside, and 4 after/between) // The span length going negative is okay, and the same as going to zero: the span is ignored thereafter. expected = CreateSpans(spans, -2, -8, -10, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is something or other.", spans); VerifySpans(expected, spans); // delete exactly the first span (remove 4 inside) expected = CreateSpans(spans, 0, -4, -4, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a of something or other.", spans); VerifySpans(expected, spans); // after any spans (effectively no change) expected = CreateSpans(spans, 0, 0, 0, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a test of something or other", spans); VerifySpans(expected, spans); // after any spans, but adjacent to last span (effectively no change) expected = CreateSpans(spans, 0, 0, 0, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a test of somethingther.", spans); VerifySpans(expected, spans); // delete from middle of first span to middle of second span expected = CreateSpans(spans, 0, -2, -6, -7); LanguageForm.AdjustSpansForTextChange(oldString, "This is a teng or other.", spans); VerifySpans(expected, spans); // change text without changing length of string // (alas, we can't handle this kind of wholesale change, so effectively no change to the spans) expected = CreateSpans(spans, 0, 0, 0, 0); LanguageForm.AdjustSpansForTextChange(oldString, "That is a joke of some other topic!!!", spans); VerifySpans(expected, spans); } static List<LanguageForm.FormatSpan> CreateSpans(List<LanguageForm.FormatSpan> spans, int deltaloc1, int deltalen1, int deltaloc2, int deltalen2) { spans.Clear(); spans.Add(new LanguageForm.FormatSpan { Index = 10, Length = 4, Class = "Strong" }); spans.Add(new LanguageForm.FormatSpan { Index = 18, Length = 9, Class = "Weak" }); var expected = new List<LanguageForm.FormatSpan>(); expected.Add(new LanguageForm.FormatSpan { Index = 10 + deltaloc1, Length = 4 + deltalen1, Class = "Strong" }); expected.Add(new LanguageForm.FormatSpan { Index = 18 + deltaloc2, Length = 9 + deltalen2, Class = "Weak" }); return expected; } void VerifySpans (List<LanguageForm.FormatSpan> expected, List<LanguageForm.FormatSpan> spans) { Assert.AreEqual(expected[0].Index, spans[0].Index, "first span index wrong"); Assert.AreEqual(expected[0].Length, spans[0].Length, "first span length wrong"); Assert.AreEqual(expected[0].Class, spans[0].Class, "first span class wrong"); Assert.AreEqual(expected[1].Index, spans[1].Index, "second span index wrong"); Assert.AreEqual(expected[1].Length, spans[1].Length, "second span length wrong"); Assert.AreEqual(expected[1].Class, spans[1].Class, "second span class wrong"); } } }
using CmdrCompanion.Core; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Threading; using Microsoft.Practices.ServiceLocation; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace CmdrCompanion.Interface.ViewModel { public class JumpFinderViewModel : LocalViewModelBase { public JumpFinderViewModel() { FromStationSelector = new StationSelectorViewModel() { UserCanSelectAny = true, UserCanSelectCurrent = true, }; FromStationSelector.PropertyChanged += FromStationSelector_PropertyChanged; ToStationSelector = new StationSelectorViewModel() { UserCanSelectAny = true, UserCanSelectCurrent = true, }; ToStationSelector.PropertyChanged += ToStationSelector_PropertyChanged; FromStationSelector.Filter = FromStationFilter; ToStationSelector.Filter = ToStationFilter; _resultsList = new ObservableCollection<TradeJumpDataViewModel>(); ResultsView = new ListCollectionView(_resultsList); ResultsView.Filter = ResultsViewFilter; StartUpdatingCommand = new RelayCommand(StartUpdating); MaxDistance = 500; CargoReference = 4; MaximumPrice = 1000; LowerProfitsThreshold = 1; } private void ToStationSelector_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch(e.PropertyName) { case "SelectedStation": FromStationSelector.Refresh(); RaisePropertyChanged("MaxDistanceEnabled"); break; } } private void FromStationSelector_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "SelectedStation": ToStationSelector.Refresh(); RaisePropertyChanged("MaxDistanceEnabled"); break; } } private float _maxDistance; public float MaxDistance { get { return _maxDistance; } set { if (value != _maxDistance) { _maxDistance = value; RaisePropertyChanged("MaxDistance"); } } } public bool MaxDistanceEnabled { get { return ToStationSelector.SelectedStation == null || FromStationSelector.SelectedStation == null; } } private bool FromStationFilter(object fromStation) { if (ToStationSelector.SelectedStation == null) return true; return fromStation != ToStationSelector.SelectedStation; } private bool ToStationFilter(object toStation) { if (FromStationSelector.SelectedStation == null) return true; return toStation != FromStationSelector.SelectedStation; } public StationSelectorViewModel FromStationSelector { get; private set; } public StationSelectorViewModel ToStationSelector { get; private set; } private bool _isWorking; public bool IsWorking { get { return _isWorking; } set { if(value != _isWorking) { _isWorking = value; RaisePropertyChanged("IsWorking"); } } } private bool _showCargoIndicators; public bool ShowCargoIndicators { get { return _showCargoIndicators; } set { if(value != _showCargoIndicators) { _showCargoIndicators = value; RaisePropertyChanged("ShowCargoIndicators"); RaisePropertyChanged("CanFilterMaximumPrice"); } } } private int _cargoReference; public int CargoReference { get { return _cargoReference; } set { if(value != _cargoReference) { _cargoReference = value; RaisePropertyChanged("CargoReference"); } } } private bool _filterLowerProfits; public bool FilterLowerProfits { get { return _filterLowerProfits; } set { if(value != _filterLowerProfits) { _filterLowerProfits = value; RaisePropertyChanged("FilterLowerProfits"); ResultsView.Refresh(); } } } private float _lowerProfitsThreshold; public float LowerProfitsThreshold { get { return _lowerProfitsThreshold; } set { if(value != _lowerProfitsThreshold) { _lowerProfitsThreshold = value; RaisePropertyChanged("LowerProfitsThreshold"); if (FilterLowerProfits) ResultsView.Refresh(); } } } private bool _filterMaximumPrice; public bool FilterMaximumPrice { get { return _filterMaximumPrice; } set { if(value != _filterMaximumPrice) { _filterMaximumPrice = value; RaisePropertyChanged("FilterMaximumPrice"); ResultsView.Refresh(); } } } private float _maximumPrice; public float MaximumPrice { get { return _maximumPrice; } set { if(value != _maximumPrice) { _maximumPrice = value; RaisePropertyChanged("MaximumPrice"); if (FilterMaximumPrice) ResultsView.Refresh(); } } } public bool CanFilterMaximumPrice { get { return ShowCargoIndicators; } } public RelayCommand StartUpdatingCommand { get; private set; } public void StartUpdating() { UpdateResults(); } private ObservableCollection<TradeJumpDataViewModel> _resultsList; public ListCollectionView ResultsView { get; private set; } private bool ResultsViewFilter(object data) { if(data is TradeJumpDataViewModel) { TradeJumpDataViewModel vmData = (TradeJumpDataViewModel)data; return !(FilterLowerProfits && vmData.RawData.ProfitPerUnit < LowerProfitsThreshold) && !(FilterMaximumPrice && vmData.TotalCost > MaximumPrice); } return false; } private BackgroundWorker _updateResultsWorker; private void UpdateResults() { if (_updateResultsWorker != null) { _updateResultsWorker.CancelAsync(); } foreach (TradeJumpDataViewModel data in _resultsList) data.Cleanup(); _resultsList.Clear(); _updateResultsWorker = new BackgroundWorker(); _updateResultsWorker.DoWork += UpdateResultsWorker_DoWork; _updateResultsWorker.WorkerSupportsCancellation = true; _updateResultsWorker.RunWorkerCompleted += UpdateResultsWorker_RunWorkerCompleted; AstronomicalObject[] sList = null; if (FromStationSelector.SelectedStation == null || ToStationSelector.SelectedStation == null) sList = Environment.Stations.ToArray(); IsWorking = true; _updateResultsWorker.RunWorkerAsync(new UpdateResultsData() { from = FromStationSelector.SelectedStation, to = ToStationSelector.SelectedStation, maxDistance = MaxDistance, stationList = sList, }); } void UpdateResultsWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { _updateResultsWorker = null; IsWorking = false; } private void UpdateResultsWorker_DoWork(object sender, DoWorkEventArgs e) { UpdateResultsData data = (UpdateResultsData)e.Argument; BackgroundWorker worker = (BackgroundWorker)sender; if (data.from == null) { if (data.to == null) { foreach (AstronomicalObject s1 in data.stationList) { foreach (AstronomicalObject s2 in data.stationList) { if (worker.CancellationPending) return; if (s1 == s2) continue; if (!s1.Star.KnownObjectProximities.ContainsKey(s2.Star) || s1.Star.KnownObjectProximities[s2.Star] > data.maxDistance) continue; IEnumerable<TradeJumpDataViewModel> results = s1.FindTradesWith(s2).Select(tjd => new TradeJumpDataViewModel(tjd, this)); DispatcherHelper.UIDispatcher.BeginInvoke(new Action<IEnumerable<TradeJumpDataViewModel>>(AddResult), results); } } } else { foreach (AstronomicalObject s in data.stationList) { if (worker.CancellationPending) return; if (s == data.to) continue; if (!s.Star.KnownObjectProximities.ContainsKey(data.to.Star) || s.Star.KnownObjectProximities[data.to.Star] > data.maxDistance) continue; IEnumerable<TradeJumpDataViewModel> results = s.FindTradesWith(data.to).Select(tjd => new TradeJumpDataViewModel(tjd, this)); DispatcherHelper.UIDispatcher.BeginInvoke(new Action<IEnumerable<TradeJumpDataViewModel>>(AddResult), results); } } } else { if (data.to == null) { foreach (AstronomicalObject s in data.stationList) { if (worker.CancellationPending) return; if (s == data.from) continue; if (!data.from.Star.KnownObjectProximities.ContainsKey(s.Star) || data.from.Star.KnownObjectProximities[s.Star] > data.maxDistance) continue; IEnumerable<TradeJumpDataViewModel> results = data.from.FindTradesWith(s).Select(tjd => new TradeJumpDataViewModel(tjd, this)); DispatcherHelper.UIDispatcher.BeginInvoke(new Action<IEnumerable<TradeJumpDataViewModel>>(AddResult), results); } } else { // EZ IEnumerable<TradeJumpDataViewModel> results = data.from.FindTradesWith(data.to).Select(tjd => new TradeJumpDataViewModel(tjd, this)); DispatcherHelper.UIDispatcher.BeginInvoke(new Action<IEnumerable<TradeJumpDataViewModel>>(AddResult), results); } } } private void AddResult(IEnumerable<TradeJumpDataViewModel> results) { foreach (TradeJumpDataViewModel data in results) _resultsList.Add(data); } public class TradeJumpDataViewModel : ViewModelBase { internal TradeJumpDataViewModel(TradeJumpData data, JumpFinderViewModel container) { RawData = data; if (data.From.Station.Star.KnownObjectProximities.ContainsKey(data.To.Station.Star)) Distance = data.From.Station.Star.KnownObjectProximities[data.To.Station.Star]; container.PropertyChanged += ContainerPropertyChanged; _container = container; } void ContainerPropertyChanged(object sender, PropertyChangedEventArgs e) { if (!_container.ShowCargoIndicators) return; if(e.PropertyName == "CargoReference") { RaisePropertyChanged("TotalCost"); RaisePropertyChanged("TotalProfit"); RaisePropertyChanged("TotalRevenue"); } } private JumpFinderViewModel _container; public TradeJumpData RawData { get; private set; } public float Distance { get; private set; } public float TotalCost { get { return _container.CargoReference * RawData.From.SellingPrice; } } public float TotalProfit { get { return _container.CargoReference * RawData.ProfitPerUnit; } } public float TotalRevenue { get { return _container.CargoReference * RawData.To.BuyingPrice; } } public override void Cleanup() { _container.PropertyChanged -= ContainerPropertyChanged; base.Cleanup(); } } private sealed class UpdateResultsData { public AstronomicalObject from; public AstronomicalObject to; public float maxDistance; public AstronomicalObject[] stationList; } } }
// InflaterHuffmanTree.cs // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // ************************************************************************* // // Name: InflaterHuffmanTree.cs // // Created: 19-02-2008 SharedCache.com, rschuetz // Modified: 19-02-2008 SharedCache.com, rschuetz : Creation // ************************************************************************* using System; using MergeSystem.Indexus.WinServiceCommon.SharpZipLib.Zip.Compression.Streams; namespace MergeSystem.Indexus.WinServiceCommon.SharpZipLib.Zip.Compression { /// <summary> /// Huffman tree used for inflation /// </summary> public class InflaterHuffmanTree { #region Constants const int MAX_BITLEN = 15; #endregion #region Instance Fields short[] tree; #endregion /// <summary> /// Literal length tree /// </summary> public static InflaterHuffmanTree defLitLenTree; /// <summary> /// Distance tree /// </summary> public static InflaterHuffmanTree defDistTree; static InflaterHuffmanTree() { try { byte[] codeLengths = new byte[288]; int i = 0; while (i < 144) { codeLengths[i++] = 8; } while (i < 256) { codeLengths[i++] = 9; } while (i < 280) { codeLengths[i++] = 7; } while (i < 288) { codeLengths[i++] = 8; } defLitLenTree = new InflaterHuffmanTree(codeLengths); codeLengths = new byte[32]; i = 0; while (i < 32) { codeLengths[i++] = 5; } defDistTree = new InflaterHuffmanTree(codeLengths); } catch (Exception) { throw new SharpZipBaseException("InflaterHuffmanTree: static tree length illegal"); } } #region Constructors /// <summary> /// Constructs a Huffman tree from the array of code lengths. /// </summary> /// <param name = "codeLengths"> /// the array of code lengths /// </param> public InflaterHuffmanTree(byte[] codeLengths) { BuildTree(codeLengths); } #endregion void BuildTree(byte[] codeLengths) { int[] blCount = new int[MAX_BITLEN + 1]; int[] nextCode = new int[MAX_BITLEN + 1]; for (int i = 0; i < codeLengths.Length; i++) { int bits = codeLengths[i]; if (bits > 0) { blCount[bits]++; } } int code = 0; int treeSize = 512; for (int bits = 1; bits <= MAX_BITLEN; bits++) { nextCode[bits] = code; code += blCount[bits] << (16 - bits); if (bits >= 10) { /* We need an extra table for bit lengths >= 10. */ int start = nextCode[bits] & 0x1ff80; int end = code & 0x1ff80; treeSize += (end - start) >> (16 - bits); } } /* -jr comment this out! doesnt work for dynamic trees and pkzip 2.04g if (code != 65536) { throw new SharpZipBaseException("Code lengths don't add up properly."); } */ /* Now create and fill the extra tables from longest to shortest * bit len. This way the sub trees will be aligned. */ tree = new short[treeSize]; int treePtr = 512; for (int bits = MAX_BITLEN; bits >= 10; bits--) { int end = code & 0x1ff80; code -= blCount[bits] << (16 - bits); int start = code & 0x1ff80; for (int i = start; i < end; i += 1 << 7) { tree[DeflaterHuffman.BitReverse(i)] = (short)((-treePtr << 4) | bits); treePtr += 1 << (bits - 9); } } for (int i = 0; i < codeLengths.Length; i++) { int bits = codeLengths[i]; if (bits == 0) { continue; } code = nextCode[bits]; int revcode = DeflaterHuffman.BitReverse(code); if (bits <= 9) { do { tree[revcode] = (short)((i << 4) | bits); revcode += 1 << bits; } while (revcode < 512); } else { int subTree = tree[revcode & 511]; int treeLen = 1 << (subTree & 15); subTree = -(subTree >> 4); do { tree[subTree | (revcode >> 9)] = (short)((i << 4) | bits); revcode += 1 << bits; } while (revcode < treeLen); } nextCode[bits] = code + (1 << (16 - bits)); } } /// <summary> /// Reads the next symbol from input. The symbol is encoded using the /// huffman tree. /// </summary> /// <param name="input"> /// input the input source. /// </param> /// <returns> /// the next symbol, or -1 if not enough input is available. /// </returns> public int GetSymbol(StreamManipulator input) { int lookahead, symbol; if ((lookahead = input.PeekBits(9)) >= 0) { if ((symbol = tree[lookahead]) >= 0) { input.DropBits(symbol & 15); return symbol >> 4; } int subtree = -(symbol >> 4); int bitlen = symbol & 15; if ((lookahead = input.PeekBits(bitlen)) >= 0) { symbol = tree[subtree | (lookahead >> 9)]; input.DropBits(symbol & 15); return symbol >> 4; } else { int bits = input.AvailableBits; lookahead = input.PeekBits(bits); symbol = tree[subtree | (lookahead >> 9)]; if ((symbol & 15) <= bits) { input.DropBits(symbol & 15); return symbol >> 4; } else { return -1; } } } else { int bits = input.AvailableBits; lookahead = input.PeekBits(bits); symbol = tree[lookahead]; if (symbol >= 0 && (symbol & 15) <= bits) { input.DropBits(symbol & 15); return symbol >> 4; } else { return -1; } } } } }
/* * Original author: Nicholas Shulman <nicksh .at. u.washington.edu>, * MacCoss Lab, Department of Genome Sciences, UW * * Copyright 2011 University of Washington - Seattle, WA * * 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.Linq; using System.Windows.Forms; using pwiz.Common.Collections; using pwiz.Common.Controls; using pwiz.Common.DataBinding.Documentation; using pwiz.Common.Properties; namespace pwiz.Common.DataBinding.Controls.Editor { /// <summary> /// User interface for choosing which columns should go in a view, and setting the filter and sort. /// </summary> public partial class ViewEditor : CommonFormEx, IViewEditor, IMultipleViewProvider { private bool _inChangeView; private bool _showHiddenFields; // ReSharper disable PrivateFieldCanBeConvertedToLocalVariable private readonly ChooseColumnsTab _chooseColumnsTab; private readonly FilterTab _filterTab; private readonly SourceTab _sourceTab; private readonly List<ViewEditorWidget> _editorWidgets = new List<ViewEditorWidget>(); // ReSharper restore PrivateFieldCanBeConvertedToLocalVariable private readonly List<KeyValuePair<ViewInfo, IList<PropertyPath>>> _undoStack; private int _undoIndex; private IList<PropertyPath> _selectedPaths = ImmutableList.Empty<PropertyPath>(); public TabPage TabPageSource { get { return tabPageSource; } set { tabPageSource = value; } } public class ChooseColumnsView : IFormView {} public class FilterView : IFormView {} // public class SourceView : IFormView {} inaccessible private static readonly IFormView[] TAB_PAGES = { new ChooseColumnsView(), new FilterView(), // new SourceView() innaccessible }; public ViewEditor(IViewContext viewContext, ViewInfo viewInfo) { InitializeComponent(); ViewContext = viewContext; ViewInfo = OriginalViewInfo = viewInfo; _undoIndex = 0; _undoStack = new List<KeyValuePair<ViewInfo, IList<PropertyPath>>>(); SetViewInfo(ViewInfo, new PropertyPath[0]); tbxViewName.Text = ViewSpec.Name; Icon = ViewContext.ApplicationIcon; _chooseColumnsTab = new ChooseColumnsTab {Dock = DockStyle.Fill}; tabPageColumns.Controls.Add(_chooseColumnsTab); _filterTab = new FilterTab { Dock = DockStyle.Fill }; tabPageFilter.Controls.Add(_filterTab); _sourceTab = new SourceTab{Dock = DockStyle.Fill}; tabPageSource.Controls.Add(_sourceTab); _editorWidgets.AddRange(new ViewEditorWidget[] { _chooseColumnsTab, _filterTab, _sourceTab }); foreach (var tab in _editorWidgets) { tab.SetViewEditor(this); } toolButtonShowAdvanced.Checked = ShowHiddenFields; if (!ShowHiddenFields) { tabControl1.TabPages.Remove(tabPageSource); } AddTooltipHandler(_chooseColumnsTab.AvailableFieldsTree); AddTooltipHandler(_filterTab.AvailableFieldsTree); } public ColumnDescriptor ParentColumn { get { return ViewInfo.ParentColumn; } } public IViewContext ViewContext { get; private set; } public ViewInfo OriginalViewInfo { get; private set; } public ViewSpec ViewSpec { get { return ViewInfo.ViewSpec; } } public IEnumerable<PropertyPath> SelectedPaths { get { return _selectedPaths; } set { if (_selectedPaths.SequenceEqual(value)) { return; } _selectedPaths = ImmutableList.ValueOf(value); if (null != ViewChange) { ViewChange(this, new EventArgs()); } } } public string ViewName { get { return tbxViewName.Text; } set { tbxViewName.Text = value; } } public void SetViewInfo(ViewInfo viewInfo, IEnumerable<PropertyPath> selectedPaths) { bool inChangeView = _inChangeView; try { _inChangeView = true; _undoStack.RemoveRange(_undoIndex, _undoStack.Count - _undoIndex); _undoStack.Add(new KeyValuePair<ViewInfo, IList<PropertyPath>>(viewInfo, ImmutableList.ValueOf(selectedPaths ?? _selectedPaths))); ApplyViewInfo(_undoStack[_undoIndex++]); } finally { _inChangeView = inChangeView; } } private void ApplyViewInfo(KeyValuePair<ViewInfo, IList<PropertyPath>> undoEntry) { ViewInfo = undoEntry.Key; _selectedPaths = undoEntry.Value; toolButtonUndo.Enabled = _undoIndex > 1; toolButtonRedo.Enabled = _undoIndex < _undoStack.Count; if (ViewChange != null) { ViewChange(this, new EventArgs()); } } public ViewSpec GetViewSpecToPersist() { return ViewSpec; } public IViewTransformer ViewTransformer { get; private set; } public void SetViewTransformer(IViewTransformer viewTransformer) { ViewTransformer = viewTransformer; if (null != ViewChange) { ViewChange(this, new EventArgs()); } } public event EventHandler ViewChange; private void OnLoad(object sender, EventArgs e) { // If you set this in the Designer, DataGridView has a defect that causes it to throw an // exception if the the cursor is positioned over the record selector column during loading. } public ViewInfo ViewInfo { get; private set; } public bool ShowHiddenFields { get { return _showHiddenFields; } set { if (ShowHiddenFields == value) { return; } _showHiddenFields = value; toolButtonShowAdvanced.Checked = ShowHiddenFields; if (ShowHiddenFields) { if (tabPageSource.Parent == null) { tabControl1.TabPages.Add(tabPageSource); } } else { if (tabPageSource.Parent == tabControl1) { tabControl1.TabPages.Remove(tabPageSource); } } if (null != ViewChange) { ViewChange(this, new EventArgs()); } } } public bool ShowSourceTab { get { return tabPageSource.Visible; } set { tabPageSource.Visible = value; } } public IFormView ShowingFormView { get { int selectedIndex = 0; Invoke(new Action(() => selectedIndex = tabControl1.SelectedIndex)); return TAB_PAGES[selectedIndex]; } } protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); if (e.Cancel || DialogResult == DialogResult.Cancel) { return; } ValidateViewName(e); } protected void ValidateViewName(FormClosingEventArgs formClosingEventArgs) { if (formClosingEventArgs.Cancel) { return; } var name = tbxViewName.Text; string errorMessage = null; if (string.IsNullOrEmpty(name)) { errorMessage = Resources.CustomizeViewForm_ValidateViewName_View_name_cannot_be_blank_; } else { if (name != OriginalViewInfo.Name) { if (ViewContext.GetViewSpecList(OriginalViewInfo.ViewGroup.Id).ViewSpecs.Any(viewSpec=>viewSpec.Name == name)) { errorMessage = string.Format(Resources.ViewEditor_ValidateViewName_There_is_already_a_view_named___0___, name); } } } if (errorMessage != null) { ViewContext.ShowMessageBox(this, errorMessage, MessageBoxButtons.OK); formClosingEventArgs.Cancel = true; } if (formClosingEventArgs.Cancel) { tbxViewName.Focus(); } } public static bool IsCanonical(DisplayColumn displayColumn) { if (displayColumn.ColumnSpec.Hidden && null != displayColumn.ColumnSpec.SortDirection) { return false; } return true; } private void toolButtonUndo_Click(object sender, EventArgs e) { if (_inChangeView || _undoIndex <= 1) { return; } try { _inChangeView = true; _undoIndex--; ApplyViewInfo(_undoStack[_undoIndex - 1]); } finally { _inChangeView = false; } } private void toolButtonRedo_Click(object sender, EventArgs e) { if (_inChangeView || _undoIndex >= _undoStack.Count) { return; } try { _inChangeView = true; ApplyViewInfo(_undoStack[_undoIndex++]); } finally { _inChangeView = false; } } private void toolButtonShowAdvanced_Click(object sender, EventArgs e) { ShowHiddenFields = !ShowHiddenFields; } public void AddViewEditorWidget(ViewEditorWidget viewEditorWidget) { _editorWidgets.Add(viewEditorWidget); viewEditorWidget.SetViewEditor(this); panelButtons.Controls.Add(viewEditorWidget); } public IEnumerable<ViewEditorWidget> ViewEditorWidgets { get { return _editorWidgets.AsEnumerable(); } } public ChooseColumnsTab ChooseColumnsTab { get { return _chooseColumnsTab; } } public FilterTab FilterTab { get { return _filterTab; } } public bool PreviewButtonVisible { get { return btnPreview.Visible; } set { btnPreview.Visible = value; } } private void btnPreview_Click(object sender, EventArgs e) { ShowPreview(); } public void ShowPreview() { Debug.Assert(PreviewButtonVisible); var viewInfo = new ViewInfo(ViewInfo.ParentColumn, ViewSpec.SetName(ViewName)); ViewContext.Preview(this, viewInfo); } public TabControl TabControl { get { return tabControl1; }} public AvailableFieldsTree ActiveAvailableFieldsTree { get { switch (TabControl.SelectedIndex) { case 0: return ChooseColumnsTab.AvailableFieldsTree; case 1: return FilterTab.AvailableFieldsTree; } return null; } } public void OkDialog() { DialogResult = btnOK.DialogResult; } public void ActivatePropertyPath(PropertyPath propertyPath) { if (null != PropertyPathActivated) { PropertyPathActivated(this, new PropertyPathEventArgs(propertyPath)); } } public event EventHandler<PropertyPathEventArgs> PropertyPathActivated; private void toolButtonFind_Click(object sender, EventArgs e) { ShowFindDialog(); } public FindColumnDlg GetFindColumnDlg() { return OwnedForms.OfType<FindColumnDlg>().FirstOrDefault(); } public void ShowFindDialog() { FindColumnDlg findColumnDlg = GetFindColumnDlg(); if (findColumnDlg != null) { findColumnDlg.Activate(); } else { findColumnDlg = new FindColumnDlg {ViewEditor = this}; findColumnDlg.Show(this); } } private void ViewEditor_KeyDown(object sender, KeyEventArgs e) { if (!e.Handled) { if (e.Modifiers == Keys.Control && e.KeyCode == Keys.F) { e.Handled = true; ShowFindDialog(); } } } private void helpToolStripButton_Click(object sender, EventArgs e) { ShowColumnDocumentation(); } public void ShowColumnDocumentation() { var documentationGenerator = new DocumentationGenerator(ChooseColumnsTab.ViewInfo.ParentColumn); DocumentationViewer documentationViewer = new DocumentationViewer(); documentationViewer.DocumentationHtml = documentationGenerator.GetDocumentationHtmlPage(); documentationViewer.Show(this); } private void AddTooltipHandler(TreeView treeView) { treeView.ShowNodeToolTips = false; treeView.NodeMouseHover += (sender, args) => { if (!string.IsNullOrEmpty(args.Node.ToolTipText)) { toolTip1.Show(args.Node.ToolTipText, treeView); } }; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.IO; using System.Drawing.Printing; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Output; using ESRI.ArcGIS; namespace PrintPreview { public class Form1 : System.Windows.Forms.Form { private System.ComponentModel.Container components = null; //buttons for open file, print preview, print dialog, page setup private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.ComboBox comboBox1; //declare the dialogs for print preview, print dialog, page setup internal PrintPreviewDialog printPreviewDialog1; internal PrintDialog printDialog1; internal PageSetupDialog pageSetupDialog1; //declare a PrintDocument object named document, to be displayed in the print preview private System.Drawing.Printing.PrintDocument document = new System.Drawing.Printing.PrintDocument(); //cancel tracker which is passed to the output function when printing to the print preview private ITrackCancel m_TrackCancel = new CancelTrackerClass(); private ESRI.ArcGIS.Controls.AxPageLayoutControl axPageLayoutControl1; private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1; //the page that is currently printed to the print preview private short m_CurrentPrintPage; public Form1() { InitializeComponent(); } protected override void Dispose( bool disposing ) { //Release COM objects ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown(); if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.axPageLayoutControl1 = new ESRI.ArcGIS.Controls.AxPageLayoutControl(); this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl(); ((System.ComponentModel.ISupportInitialize)(this.axPageLayoutControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(8, 8); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(88, 24); this.button1.TabIndex = 1; this.button1.Text = "Open File"; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(112, 8); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(88, 24); this.button2.TabIndex = 4; this.button2.Text = "Page Setup"; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.Location = new System.Drawing.Point(216, 8); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(88, 24); this.button3.TabIndex = 5; this.button3.Text = "Print Preview"; this.button3.Click += new System.EventHandler(this.button3_Click); // // button4 // this.button4.Location = new System.Drawing.Point(320, 8); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(88, 24); this.button4.TabIndex = 6; this.button4.Text = "Print"; this.button4.Click += new System.EventHandler(this.button4_Click); // // comboBox1 // this.comboBox1.Location = new System.Drawing.Point(424, 8); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(144, 21); this.comboBox1.TabIndex = 8; // // axPageLayoutControl1 // this.axPageLayoutControl1.Location = new System.Drawing.Point(0, 48); this.axPageLayoutControl1.Name = "axPageLayoutControl1"; this.axPageLayoutControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axPageLayoutControl1.OcxState"))); this.axPageLayoutControl1.Size = new System.Drawing.Size(680, 520); this.axPageLayoutControl1.TabIndex = 9; // // axLicenseControl1 // this.axLicenseControl1.Enabled = true; this.axLicenseControl1.Location = new System.Drawing.Point(512, 88); this.axLicenseControl1.Name = "axLicenseControl1"; this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState"))); this.axLicenseControl1.Size = new System.Drawing.Size(32, 32); this.axLicenseControl1.TabIndex = 10; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(680, 566); this.Controls.Add(this.axLicenseControl1); this.Controls.Add(this.axPageLayoutControl1); this.Controls.Add(this.comboBox1); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Print Preview / Print dialog Sample"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.axPageLayoutControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit(); this.ResumeLayout(false); } #endregion [STAThread] static void Main() { if (!RuntimeManager.Bind(ProductCode.Engine)) { if (!RuntimeManager.Bind(ProductCode.Desktop)) { MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down."); return; } } Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { InitializePrintPreviewDialog(); //initialize the print preview dialog printDialog1 = new PrintDialog(); //create a print dialog object InitializePageSetupDialog(); //initialize the page setup dialog comboBox1.Items.Add("esriPageMappingTile"); comboBox1.Items.Add("esriPageMappingCrop"); comboBox1.Items.Add("esriPageMappingScale"); comboBox1.SelectedIndex= 0; } private void InitializePrintPreviewDialog() { // create a new PrintPreviewDialog using constructor printPreviewDialog1 = new PrintPreviewDialog(); //set the size, location, name and the minimum size the dialog can be resized to printPreviewDialog1.ClientSize = new System.Drawing.Size(800, 600); printPreviewDialog1.Location = new System.Drawing.Point(29, 29); printPreviewDialog1.Name = "PrintPreviewDialog1"; printPreviewDialog1.MinimumSize = new System.Drawing.Size(375, 250); //set UseAntiAlias to true to allow the operating system to smooth fonts printPreviewDialog1.UseAntiAlias = true; //associate the event-handling method with the document's PrintPage event this.document.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(document_PrintPage); } private void InitializePageSetupDialog() { //create a new PageSetupDialog using constructor pageSetupDialog1 = new PageSetupDialog(); //initialize the dialog's PrinterSettings property to hold user defined printer settings pageSetupDialog1.PageSettings = new System.Drawing.Printing.PageSettings(); //initialize dialog's PrinterSettings property to hold user set printer settings pageSetupDialog1.PrinterSettings = new System.Drawing.Printing.PrinterSettings(); //do not show the network in the printer dialog pageSetupDialog1.ShowNetwork = false; } private void button1_Click(object sender, System.EventArgs e) { Stream myStream; //create an open file dialog OpenFileDialog openFileDialog1 = new OpenFileDialog(); //set the file extension filter, filter index and restore directory flag openFileDialog1.Filter = "template files (*.mxt)|*.mxt|mxd files (*.mxd)|*.mxd" ; openFileDialog1.FilterIndex = 2 ; openFileDialog1.RestoreDirectory = true ; //display open file dialog and check if user clicked ok button if(openFileDialog1.ShowDialog() == DialogResult.OK) { //check if a file was selected if((myStream = openFileDialog1.OpenFile())!= null) { //get the selected filename and path string fileName = openFileDialog1.FileName; //check if selected file is mxd file if (axPageLayoutControl1.CheckMxFile(fileName)) { //load the mxd file into PageLayout control axPageLayoutControl1.LoadMxFile(fileName, ""); } myStream.Close(); } } } private void button2_Click(object sender, System.EventArgs e) { //Show the page setup dialog storing the result. DialogResult result = pageSetupDialog1.ShowDialog(); //set the printer settings of the preview document to the selected printer settings document.PrinterSettings = pageSetupDialog1.PrinterSettings; //set the page settings of the preview document to the selected page settings document.DefaultPageSettings = pageSetupDialog1.PageSettings; //due to a bug in PageSetupDialog the PaperSize has to be set explicitly by iterating through the //available PaperSizes in the PageSetupDialog finding the selected PaperSize int i; IEnumerator paperSizes = pageSetupDialog1.PrinterSettings.PaperSizes.GetEnumerator(); paperSizes.Reset(); for(i = 0; i<pageSetupDialog1.PrinterSettings.PaperSizes.Count; ++i) { paperSizes.MoveNext(); if(((PaperSize)paperSizes.Current).Kind == document.DefaultPageSettings.PaperSize.Kind) { document.DefaultPageSettings.PaperSize = ((PaperSize)paperSizes.Current); } } ///////////////////////////////////////////////////////////// ///initialize the current printer from the printer settings selected ///in the page setup dialog ///////////////////////////////////////////////////////////// IPaper paper; paper = new PaperClass(); //create a paper object IPrinter printer; printer = new EmfPrinterClass(); //create a printer object //in this case an EMF printer, alternatively a PS printer could be used //initialize the paper with the DEVMODE and DEVNAMES structures from the windows GDI //these structures specify information about the initialization and environment of a printer as well as //driver, device, and output port names for a printer paper.Attach(pageSetupDialog1.PrinterSettings.GetHdevmode(pageSetupDialog1.PageSettings).ToInt32(), pageSetupDialog1.PrinterSettings.GetHdevnames().ToInt32()); //pass the paper to the emf printer printer.Paper = paper; //set the page layout control's printer to the currently selected printer axPageLayoutControl1.Printer = printer; } private void button3_Click(object sender, System.EventArgs e) { //initialize the currently printed page number m_CurrentPrintPage = 0; //check if a document is loaded into PageLayout control if(axPageLayoutControl1.DocumentFilename==null) return; //set the name of the print preview document to the name of the mxd doc document.DocumentName = axPageLayoutControl1.DocumentFilename; //set the PrintPreviewDialog.Document property to the PrintDocument object selected by the user printPreviewDialog1.Document = document; //show the dialog - this triggers the document's PrintPage event printPreviewDialog1.ShowDialog(); } private void button4_Click(object sender, System.EventArgs e) { //allow the user to choose the page range to be printed printDialog1.AllowSomePages = true; //show the help button. printDialog1.ShowHelp = true; //set the Document property to the PrintDocument for which the PrintPage Event //has been handled. To display the dialog, either this property or the //PrinterSettings property must be set printDialog1.Document = document; //show the print dialog and wait for user input DialogResult result = printDialog1.ShowDialog(); // If the result is OK then print the document. if (result==DialogResult.OK) document.Print(); } private void document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { //this code will be called when the PrintPreviewDialog.Show method is called //set the PageToPrinterMapping property of the Page. This specifies how the page //is mapped onto the printer page. By default the page will be tiled //get the selected mapping option string sPageToPrinterMapping = (string)this.comboBox1.SelectedItem; if(sPageToPrinterMapping == null) //if no selection has been made the default is tiling axPageLayoutControl1.Page.PageToPrinterMapping = esriPageToPrinterMapping.esriPageMappingTile; else if (sPageToPrinterMapping.Equals("esriPageMappingTile")) axPageLayoutControl1.Page.PageToPrinterMapping = esriPageToPrinterMapping.esriPageMappingTile; else if(sPageToPrinterMapping.Equals("esriPageMappingCrop")) axPageLayoutControl1.Page.PageToPrinterMapping = esriPageToPrinterMapping.esriPageMappingCrop; else if(sPageToPrinterMapping.Equals("esriPageMappingScale")) axPageLayoutControl1.Page.PageToPrinterMapping = esriPageToPrinterMapping.esriPageMappingScale; else axPageLayoutControl1.Page.PageToPrinterMapping = esriPageToPrinterMapping.esriPageMappingTile; //get the resolution of the graphics device used by the print preview (including the graphics device) short dpi = (short)e.Graphics.DpiX; //envelope for the device boundaries IEnvelope devBounds = new EnvelopeClass(); //get page IPage page = axPageLayoutControl1.Page; //the number of printer pages the page will be printed on short printPageCount; printPageCount = axPageLayoutControl1.get_PrinterPageCount(0); m_CurrentPrintPage++; //the currently selected printer IPrinter printer = axPageLayoutControl1.Printer; //get the device bounds of the currently selected printer page.GetDeviceBounds(printer, m_CurrentPrintPage, 0, dpi, devBounds); //structure for the device boundaries tagRECT deviceRect; //Returns the coordinates of lower, left and upper, right corners double xmin,ymin,xmax,ymax; devBounds.QueryCoords(out xmin, out ymin, out xmax, out ymax); //initialize the structure for the device boundaries deviceRect.bottom = (int) ymax; deviceRect.left = (int) xmin; deviceRect.top = (int) ymin; deviceRect.right = (int) xmax; //determine the visible bounds of the currently printed page IEnvelope visBounds = new EnvelopeClass(); page.GetPageBounds(printer, m_CurrentPrintPage, 0, visBounds); //get a handle to the graphics device that the print preview will be drawn to IntPtr hdc = e.Graphics.GetHdc(); //print the page to the graphics device using the specified boundaries axPageLayoutControl1.ActiveView.Output(hdc.ToInt32(), dpi, ref deviceRect, visBounds, m_TrackCancel); //release the graphics device handle e.Graphics.ReleaseHdc(hdc); //check if further pages have to be printed if( m_CurrentPrintPage < printPageCount) e.HasMorePages = true; //document_PrintPage event will be called again else e.HasMorePages = false; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; 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 api.Areas.HelpPage.ModelDescriptions; using api.Areas.HelpPage.Models; namespace api.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; } if (complexTypeDescription != null) { 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 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); } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// This data type is used as a response element in the <a>DescribeReservedDBInstances</a> /// and <a>PurchaseReservedDBInstancesOffering</a> actions. /// </summary> public partial class ReservedDBInstance { private string _currencyCode; private string _dbInstanceClass; private int? _dbInstanceCount; private int? _duration; private double? _fixedPrice; private bool? _multiAZ; private string _offeringType; private string _productDescription; private List<RecurringCharge> _recurringCharges = new List<RecurringCharge>(); private string _reservedDBInstanceId; private string _reservedDBInstancesOfferingId; private DateTime? _startTime; private string _state; private double? _usagePrice; /// <summary> /// Gets and sets the property CurrencyCode. /// <para> /// The currency code for the reserved DB instance. /// </para> /// </summary> public string CurrencyCode { get { return this._currencyCode; } set { this._currencyCode = value; } } // Check to see if CurrencyCode property is set internal bool IsSetCurrencyCode() { return this._currencyCode != null; } /// <summary> /// Gets and sets the property DBInstanceClass. /// <para> /// The DB instance class for the reserved DB instance. /// </para> /// </summary> public string DBInstanceClass { get { return this._dbInstanceClass; } set { this._dbInstanceClass = value; } } // Check to see if DBInstanceClass property is set internal bool IsSetDBInstanceClass() { return this._dbInstanceClass != null; } /// <summary> /// Gets and sets the property DBInstanceCount. /// <para> /// The number of reserved DB instances. /// </para> /// </summary> public int DBInstanceCount { get { return this._dbInstanceCount.GetValueOrDefault(); } set { this._dbInstanceCount = value; } } // Check to see if DBInstanceCount property is set internal bool IsSetDBInstanceCount() { return this._dbInstanceCount.HasValue; } /// <summary> /// Gets and sets the property Duration. /// <para> /// The duration of the reservation in seconds. /// </para> /// </summary> public int Duration { get { return this._duration.GetValueOrDefault(); } set { this._duration = value; } } // Check to see if Duration property is set internal bool IsSetDuration() { return this._duration.HasValue; } /// <summary> /// Gets and sets the property FixedPrice. /// <para> /// The fixed price charged for this reserved DB instance. /// </para> /// </summary> public double FixedPrice { get { return this._fixedPrice.GetValueOrDefault(); } set { this._fixedPrice = value; } } // Check to see if FixedPrice property is set internal bool IsSetFixedPrice() { return this._fixedPrice.HasValue; } /// <summary> /// Gets and sets the property MultiAZ. /// <para> /// Indicates if the reservation applies to Multi-AZ deployments. /// </para> /// </summary> public bool MultiAZ { get { return this._multiAZ.GetValueOrDefault(); } set { this._multiAZ = value; } } // Check to see if MultiAZ property is set internal bool IsSetMultiAZ() { return this._multiAZ.HasValue; } /// <summary> /// Gets and sets the property OfferingType. /// <para> /// The offering type of this reserved DB instance. /// </para> /// </summary> public string OfferingType { get { return this._offeringType; } set { this._offeringType = value; } } // Check to see if OfferingType property is set internal bool IsSetOfferingType() { return this._offeringType != null; } /// <summary> /// Gets and sets the property ProductDescription. /// <para> /// The description of the reserved DB instance. /// </para> /// </summary> public string ProductDescription { get { return this._productDescription; } set { this._productDescription = value; } } // Check to see if ProductDescription property is set internal bool IsSetProductDescription() { return this._productDescription != null; } /// <summary> /// Gets and sets the property RecurringCharges. /// <para> /// The recurring price charged to run this reserved DB instance. /// </para> /// </summary> public List<RecurringCharge> RecurringCharges { get { return this._recurringCharges; } set { this._recurringCharges = value; } } // Check to see if RecurringCharges property is set internal bool IsSetRecurringCharges() { return this._recurringCharges != null && this._recurringCharges.Count > 0; } /// <summary> /// Gets and sets the property ReservedDBInstanceId. /// <para> /// The unique identifier for the reservation. /// </para> /// </summary> public string ReservedDBInstanceId { get { return this._reservedDBInstanceId; } set { this._reservedDBInstanceId = value; } } // Check to see if ReservedDBInstanceId property is set internal bool IsSetReservedDBInstanceId() { return this._reservedDBInstanceId != null; } /// <summary> /// Gets and sets the property ReservedDBInstancesOfferingId. /// <para> /// The offering identifier. /// </para> /// </summary> public string ReservedDBInstancesOfferingId { get { return this._reservedDBInstancesOfferingId; } set { this._reservedDBInstancesOfferingId = value; } } // Check to see if ReservedDBInstancesOfferingId property is set internal bool IsSetReservedDBInstancesOfferingId() { return this._reservedDBInstancesOfferingId != null; } /// <summary> /// Gets and sets the property StartTime. /// <para> /// The time the reservation started. /// </para> /// </summary> public DateTime StartTime { get { return this._startTime.GetValueOrDefault(); } set { this._startTime = value; } } // Check to see if StartTime property is set internal bool IsSetStartTime() { return this._startTime.HasValue; } /// <summary> /// Gets and sets the property State. /// <para> /// The state of the reserved DB instance. /// </para> /// </summary> public string State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property UsagePrice. /// <para> /// The hourly price charged for this reserved DB instance. /// </para> /// </summary> public double UsagePrice { get { return this._usagePrice.GetValueOrDefault(); } set { this._usagePrice = value; } } // Check to see if UsagePrice property is set internal bool IsSetUsagePrice() { return this._usagePrice.HasValue; } } }
/***************************************************************************** * Skeleton Utility created by Mitch Thompson * Full irrevocable rights and permissions granted to Esoteric Software *****************************************************************************/ using UnityEngine; using UnityEditor; #if UNITY_4_3 //nothing #else using UnityEditor.AnimatedValues; #endif using System.Collections; using System.Collections.Generic; using Spine; using System.Reflection; [CustomEditor(typeof(SkeletonUtility))] public class SkeletonUtilityInspector : Editor { public static void AttachIcon (SkeletonUtilityBone utilityBone) { Skeleton skeleton = utilityBone.skeletonUtility.skeletonRenderer.skeleton; Texture2D icon; if (utilityBone.bone.Data.Length == 0) icon = SpineEditorUtilities.Icons.nullBone; else icon = SpineEditorUtilities.Icons.boneNib; foreach (IkConstraint c in skeleton.IkConstraints) { if (c.Target == utilityBone.bone) { icon = SpineEditorUtilities.Icons.constraintNib; break; } } typeof(EditorGUIUtility).InvokeMember("SetIconForObject", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic, null, null, new object[2] { utilityBone.gameObject, icon }); } static void AttachIconsToChildren (Transform root) { if (root != null) { var utilityBones = root.GetComponentsInChildren<SkeletonUtilityBone>(); foreach (var utilBone in utilityBones) { AttachIcon(utilBone); } } } static SkeletonUtilityInspector () { #if UNITY_4_3 showSlots = false; #else showSlots = new AnimBool(false); #endif } SkeletonUtility skeletonUtility; Skeleton skeleton; SkeletonRenderer skeletonRenderer; Transform transform; bool isPrefab; Dictionary<Slot, List<Attachment>> attachmentTable = new Dictionary<Slot, List<Attachment>>(); //GUI stuff #if UNITY_4_3 static bool showSlots; #else static AnimBool showSlots; #endif void OnEnable () { skeletonUtility = (SkeletonUtility)target; skeletonRenderer = skeletonUtility.GetComponent<SkeletonRenderer>(); skeleton = skeletonRenderer.skeleton; transform = skeletonRenderer.transform; if (skeleton == null) { skeletonRenderer.Initialize(false); skeletonRenderer.LateUpdate(); skeleton = skeletonRenderer.skeleton; } UpdateAttachments(); if (PrefabUtility.GetPrefabType(this.target) == PrefabType.Prefab) isPrefab = true; } void OnDestroy () { } void OnSceneGUI () { if (skeleton == null) { OnEnable(); return; } float flipRotation = skeleton.FlipX ? -1 : 1; foreach (Bone b in skeleton.Bones) { Vector3 vec = transform.TransformPoint(new Vector3(b.WorldX, b.WorldY, 0)); Quaternion rot = Quaternion.Euler(0, 0, b.WorldRotationX * flipRotation); Vector3 forward = transform.TransformDirection(rot * Vector3.right); forward *= flipRotation; SpineEditorUtilities.Icons.boneMaterial.SetPass(0); Graphics.DrawMeshNow(SpineEditorUtilities.Icons.boneMesh, Matrix4x4.TRS(vec, Quaternion.LookRotation(transform.forward, forward), Vector3.one * b.Data.Length * b.WorldScaleX)); } } void UpdateAttachments () { attachmentTable = new Dictionary<Slot, List<Attachment>>(); Skin skin = skeleton.Skin; if (skin == null) { skin = skeletonRenderer.skeletonDataAsset.GetSkeletonData(true).DefaultSkin; } for (int i = skeleton.Slots.Count-1; i >= 0; i--) { List<Attachment> attachments = new List<Attachment>(); skin.FindAttachmentsForSlot(i, attachments); attachmentTable.Add(skeleton.Slots.Items[i], attachments); } } void SpawnHierarchyButton (string label, string tooltip, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca, params GUILayoutOption[] options) { GUIContent content = new GUIContent(label, tooltip); if (GUILayout.Button(content, options)) { if (skeletonUtility.skeletonRenderer == null) skeletonUtility.skeletonRenderer = skeletonUtility.GetComponent<SkeletonRenderer>(); if (skeletonUtility.boneRoot != null) { return; } skeletonUtility.SpawnHierarchy(mode, pos, rot, sca); SkeletonUtilityBone[] boneComps = skeletonUtility.GetComponentsInChildren<SkeletonUtilityBone>(); foreach (SkeletonUtilityBone b in boneComps) AttachIcon(b); } } public override void OnInspectorGUI () { if (isPrefab) { GUILayout.Label(new GUIContent("Cannot edit Prefabs", SpineEditorUtilities.Icons.warning)); return; } skeletonUtility.boneRoot = (Transform)EditorGUILayout.ObjectField("Bone Root", skeletonUtility.boneRoot, typeof(Transform), true); GUILayout.BeginHorizontal(); EditorGUI.BeginDisabledGroup(skeletonUtility.boneRoot != null); { if (GUILayout.Button(new GUIContent("Spawn Hierarchy", SpineEditorUtilities.Icons.skeleton), GUILayout.Width(150), GUILayout.Height(24))) SpawnHierarchyContextMenu(); } EditorGUI.EndDisabledGroup(); if (GUILayout.Button(new GUIContent("Spawn Submeshes", SpineEditorUtilities.Icons.subMeshRenderer), GUILayout.Width(150), GUILayout.Height(24))) skeletonUtility.SpawnSubRenderers(true); GUILayout.EndHorizontal(); EditorGUI.BeginChangeCheck(); skeleton.FlipX = EditorGUILayout.ToggleLeft("Flip X", skeleton.FlipX); skeleton.FlipY = EditorGUILayout.ToggleLeft("Flip Y", skeleton.FlipY); if (EditorGUI.EndChangeCheck()) { skeletonRenderer.LateUpdate(); SceneView.RepaintAll(); } #if UNITY_4_3 showSlots = EditorGUILayout.Foldout(showSlots, "Slots"); #else showSlots.target = EditorGUILayout.Foldout(showSlots.target, "Slots"); if (EditorGUILayout.BeginFadeGroup(showSlots.faded)) { #endif foreach (KeyValuePair<Slot, List<Attachment>> pair in attachmentTable) { Slot slot = pair.Key; EditorGUILayout.BeginHorizontal(); EditorGUI.indentLevel = 1; EditorGUILayout.LabelField(new GUIContent(slot.Data.Name, SpineEditorUtilities.Icons.slot), GUILayout.ExpandWidth(false)); EditorGUI.BeginChangeCheck(); Color c = EditorGUILayout.ColorField(new Color(slot.R, slot.G, slot.B, slot.A), GUILayout.Width(60)); if (EditorGUI.EndChangeCheck()) { slot.SetColor(c); skeletonRenderer.LateUpdate(); } EditorGUILayout.EndHorizontal(); foreach (Attachment attachment in pair.Value) { if (slot.Attachment == attachment) { GUI.contentColor = Color.white; } else { GUI.contentColor = Color.grey; } EditorGUI.indentLevel = 2; bool isAttached = attachment == slot.Attachment; Texture2D icon = null; if (attachment is MeshAttachment || attachment is WeightedMeshAttachment) icon = SpineEditorUtilities.Icons.mesh; else icon = SpineEditorUtilities.Icons.image; bool swap = EditorGUILayout.ToggleLeft(new GUIContent(attachment.Name, icon), attachment == slot.Attachment); if (!isAttached && swap) { slot.Attachment = attachment; skeletonRenderer.LateUpdate(); } else if (isAttached && !swap) { slot.Attachment = null; skeletonRenderer.LateUpdate(); } GUI.contentColor = Color.white; } } #if UNITY_4_3 #else } EditorGUILayout.EndFadeGroup(); if (showSlots.isAnimating) Repaint(); #endif } void SpawnHierarchyContextMenu () { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Follow"), false, SpawnFollowHierarchy); menu.AddItem(new GUIContent("Follow (Root Only)"), false, SpawnFollowHierarchyRootOnly); menu.AddSeparator(""); menu.AddItem(new GUIContent("Override"), false, SpawnOverrideHierarchy); menu.AddItem(new GUIContent("Override (Root Only)"), false, SpawnOverrideHierarchyRootOnly); menu.ShowAsContext(); } void SpawnFollowHierarchy () { Selection.activeGameObject = skeletonUtility.SpawnHierarchy(SkeletonUtilityBone.Mode.Follow, true, true, true); AttachIconsToChildren(skeletonUtility.boneRoot); } void SpawnFollowHierarchyRootOnly () { Selection.activeGameObject = skeletonUtility.SpawnRoot(SkeletonUtilityBone.Mode.Follow, true, true, true); AttachIconsToChildren(skeletonUtility.boneRoot); } void SpawnOverrideHierarchy () { Selection.activeGameObject = skeletonUtility.SpawnHierarchy(SkeletonUtilityBone.Mode.Override, true, true, true); AttachIconsToChildren(skeletonUtility.boneRoot); } void SpawnOverrideHierarchyRootOnly () { Selection.activeGameObject = skeletonUtility.SpawnRoot(SkeletonUtilityBone.Mode.Override, true, true, true); AttachIconsToChildren(skeletonUtility.boneRoot); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Security.Cryptography; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal static class PkcsFormatReader { internal static bool TryReadPkcs7Der(byte[] rawData, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Der(rawData, true, out certPal, out ignored); } internal static bool TryReadPkcs7Der(SafeBioHandle bio, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Der(bio, true, out certPal, out ignored); } internal static bool TryReadPkcs7Der(byte[] rawData, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Der(rawData, false, out ignored, out certPals); } internal static bool TryReadPkcs7Der(SafeBioHandle bio, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Der(bio, false, out ignored, out certPals); } private static bool TryReadPkcs7Der( byte[] rawData, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { using (SafePkcs7Handle pkcs7 = Interop.Crypto.DecodePkcs7(rawData, rawData.Length)) { if (pkcs7.IsInvalid) { certPal = null; certPals = null; return false; } return TryReadPkcs7(pkcs7, single, out certPal, out certPals); } } private static bool TryReadPkcs7Der( SafeBioHandle bio, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { using (SafePkcs7Handle pkcs7 = Interop.Crypto.D2IPkcs7Bio(bio)) { if (pkcs7.IsInvalid) { certPal = null; certPals = null; return false; } return TryReadPkcs7(pkcs7, single, out certPal, out certPals); } } internal static bool TryReadPkcs7Pem(byte[] rawData, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Pem(rawData, true, out certPal, out ignored); } internal static bool TryReadPkcs7Pem(SafeBioHandle bio, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Pem(bio, true, out certPal, out ignored); } internal static bool TryReadPkcs7Pem(byte[] rawData, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Pem(rawData, false, out ignored, out certPals); } internal static bool TryReadPkcs7Pem(SafeBioHandle bio, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Pem(bio, false, out ignored, out certPals); } private static bool TryReadPkcs7Pem( byte[] rawData, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { using (SafeBioHandle bio = Interop.Crypto.CreateMemoryBio()) { Interop.Crypto.CheckValidOpenSslHandle(bio); Interop.Crypto.BioWrite(bio, rawData, rawData.Length); return TryReadPkcs7Pem(bio, single, out certPal, out certPals); } } private static bool TryReadPkcs7Pem( SafeBioHandle bio, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { using (SafePkcs7Handle pkcs7 = Interop.Crypto.PemReadBioPkcs7(bio)) { if (pkcs7.IsInvalid) { certPal = null; certPals = null; return false; } return TryReadPkcs7(pkcs7, single, out certPal, out certPals); } } private static bool TryReadPkcs7( SafePkcs7Handle pkcs7, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { List<ICertificatePal> readPals = single ? null : new List<ICertificatePal>(); using (SafeSharedX509StackHandle certs = Interop.Crypto.GetPkcs7Certificates(pkcs7)) { int count = Interop.Crypto.GetX509StackFieldCount(certs); if (single) { // In single mode for a PKCS#7 signed or signed-and-enveloped file we're supposed to return // the certificate which signed the PKCS#7 file. // // X509Certificate2Collection::Export(X509ContentType.Pkcs7) claims to be a signed PKCS#7, // but doesn't emit a signature block. So this is hard to test. // // TODO(2910): Figure out how to extract the signing certificate, when it's present. throw new CryptographicException(SR.Cryptography_X509_PKCS7_NoSigner); } for (int i = 0; i < count; i++) { // Use FromHandle to duplicate the handle since it would otherwise be freed when the PKCS7 // is Disposed. IntPtr certHandle = Interop.Crypto.GetX509StackField(certs, i); ICertificatePal pal = CertificatePal.FromHandle(certHandle); readPals.Add(pal); } } certPal = null; certPals = readPals; return true; } internal static bool TryReadPkcs12(byte[] rawData, string password, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs12(rawData, password, true, out certPal, out ignored); } internal static bool TryReadPkcs12(SafeBioHandle bio, string password, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs12(bio, password, true, out certPal, out ignored); } internal static bool TryReadPkcs12(byte[] rawData, string password, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs12(rawData, password, false, out ignored, out certPals); } internal static bool TryReadPkcs12(SafeBioHandle bio, string password, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs12(bio, password, false, out ignored, out certPals); } private static bool TryReadPkcs12( byte[] rawData, string password, bool single, out ICertificatePal readPal, out List<ICertificatePal> readCerts) { // DER-PKCS12 OpenSslPkcs12Reader pfx; if (!OpenSslPkcs12Reader.TryRead(rawData, out pfx)) { readPal = null; readCerts = null; return false; } using (pfx) { return TryReadPkcs12(pfx, password, single, out readPal, out readCerts); } } private static bool TryReadPkcs12( SafeBioHandle bio, string password, bool single, out ICertificatePal readPal, out List<ICertificatePal> readCerts) { // DER-PKCS12 OpenSslPkcs12Reader pfx; if (!OpenSslPkcs12Reader.TryRead(bio, out pfx)) { readPal = null; readCerts = null; return false; } using (pfx) { return TryReadPkcs12(pfx, password, single, out readPal, out readCerts); } } private static bool TryReadPkcs12( OpenSslPkcs12Reader pfx, string password, bool single, out ICertificatePal readPal, out List<ICertificatePal> readCerts) { pfx.Decrypt(password); ICertificatePal first = null; List<ICertificatePal> certs = null; if (!single) { certs = new List<ICertificatePal>(); } foreach (OpenSslX509CertificateReader certPal in pfx.ReadCertificates()) { if (single) { // When requesting an X509Certificate2 from a PFX only the first entry is // returned. Other entries should be disposed. if (first == null) { first = certPal; } else { certPal.Dispose(); } } else { certs.Add(certPal); } } readPal = first; readCerts = certs; return true; } } }
/* Copyright (c) 2006-2008 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. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ #define USE_TRACING #define DEBUG using System; using System.IO; using System.Xml; using System.Collections; using System.Configuration; using System.Collections.Generic; using System.Net; using NUnit.Framework; using Google.GData.Client; using Google.GData.Client.UnitTests; using Google.GData.Extensions; using Google.GData.YouTube; using Google.GData.Extensions.Location; using Google.GData.Extensions.MediaRss; using Google.YouTube; namespace Google.GData.Client.LiveTests { [TestFixture] [Category("LiveTest")] public class YouTubeTestSuite : BaseLiveTestClass { private string ytDevKey; private string ytUser; private string ytPwd; public YouTubeTestSuite() { } public override string ServiceName { get { return ServiceNames.YouTube; } } protected override void ReadConfigFile() { base.ReadConfigFile(); if (unitTestConfiguration.Contains("youTubeDevKey")) { this.ytDevKey = (string)unitTestConfiguration["youTubeDevKey"]; } if (unitTestConfiguration.Contains("youTubeUser")) { this.ytUser = (string)unitTestConfiguration["youTubeUser"]; } if (unitTestConfiguration.Contains("youTubePwd")) { this.ytPwd = (string)unitTestConfiguration["youTubePwd"]; } } [Test] public void YouTubeQueryTest() { Tracing.TraceMsg("Entering YouTubeQueryTest"); YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri); query.Formats.Add(YouTubeQuery.VideoFormat.RTSP); query.Formats.Add(YouTubeQuery.VideoFormat.Mobile); query.Time = YouTubeQuery.UploadTime.ThisWeek; Assert.AreEqual(query.Uri.AbsoluteUri, YouTubeQuery.DefaultVideoUri + "?format=1%2C6&time=this_week", "Video query should be identical"); query = new YouTubeQuery(); query.Uri = new Uri("https://www.youtube.com/feeds?format=1&time=this_week&racy=included"); Assert.AreEqual(query.Time, YouTubeQuery.UploadTime.ThisWeek, "Should be this week"); Assert.AreEqual(query.Formats[0], YouTubeQuery.VideoFormat.RTSP, "Should be RTSP"); } [Test] public void YouTubeQueryPrivateTest() { Tracing.TraceMsg("Entering YouTubeQueryPrivateTest"); YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri); YouTubeService service = new YouTubeService("NETUnittests", this.ytDevKey); query.Query = "Education expertvillage"; query.NumberToRetrieve = 50; if (this.userName != null) { service.Credentials = new GDataCredentials(this.ytUser, this.ytPwd); } YouTubeFeed feed = service.Query(query); int counter = 0; foreach (YouTubeEntry e in feed.Entries) { Assert.IsTrue(e.Media.Title.Value != null, "There should be a title"); if (e.Private) { counter++; } } Assert.IsTrue(counter == 0, "counter was " + counter); } [Test] public void YouTubeFeedTest() { Tracing.TraceMsg("Entering YouTubeFeedTest"); YouTubeQuery query = new YouTubeQuery(YouTubeQuery.TopRatedVideo); YouTubeService service = new YouTubeService("NETUnittests", this.ytDevKey); if (this.userName != null) { service.Credentials = new GDataCredentials(this.ytUser, this.ytPwd); } query.Formats.Add(YouTubeQuery.VideoFormat.RTSP); query.Time = YouTubeQuery.UploadTime.ThisWeek; YouTubeFeed feed = service.Query(query); foreach (YouTubeEntry e in feed.Entries) { Assert.IsTrue(e.Media.Title.Value != null, "There should be a title"); } } [Test] public void YouTubeReadOnlyTest() { Tracing.TraceMsg("Entering YouTubeReadOnlyTest"); YouTubeQuery query = new YouTubeQuery(YouTubeQuery.TopRatedVideo); YouTubeService service = new YouTubeService("NETUnittests"); query.Formats.Add(YouTubeQuery.VideoFormat.RTSP); query.Time = YouTubeQuery.UploadTime.ThisWeek; YouTubeFeed feed = service.Query(query); foreach (YouTubeEntry e in feed.Entries) { Assert.IsTrue(e.Media.Title.Value != null, "There should be a title"); } } [Test] public void YouTubeInsertTest() { Tracing.TraceMsg("Entering YouTubeInsertTest"); YouTubeService service = new YouTubeService("NETUnittests", this.ytDevKey); if (!string.IsNullOrEmpty(this.ytUser)) { service.Credentials = new GDataCredentials(this.ytUser, this.ytPwd); } GDataRequestFactory factory = service.RequestFactory as GDataRequestFactory; factory.Timeout = 1000000; YouTubeEntry entry = new YouTubeEntry(); entry.MediaSource = new MediaFileSource(Path.Combine(this.resourcePath, "test_movie.mov"), "video/quicktime"); entry.Media = new YouTube.MediaGroup(); entry.Media.Description = new MediaDescription("This is a test with and & in it"); entry.Media.Title = new MediaTitle("Sample upload"); entry.Media.Keywords = new MediaKeywords("math"); // entry.Media.Categories MediaCategory category = new MediaCategory("Nonprofit"); category.Attributes["scheme"] = YouTubeService.DefaultCategory; entry.Media.Categories.Add(category); YouTubeEntry newEntry = service.Upload(this.ytUser, entry); Assert.AreEqual(newEntry.Media.Description.Value, entry.Media.Description.Value, "Description should be equal"); Assert.AreEqual(newEntry.Media.Keywords.Value, entry.Media.Keywords.Value, "Keywords should be equal"); // now change the entry newEntry.Title.Text = "This test upload will soon be deleted"; YouTubeEntry anotherEntry = newEntry.Update() as YouTubeEntry; // bugbug in YouTube server. Returns empty category that the service DOES not like on reuse. so remove ExtensionList a = ExtensionList.NotVersionAware(); foreach (MediaCategory m in anotherEntry.Media.Categories) { if (String.IsNullOrEmpty(m.Value)) { a.Add(m); } } foreach (MediaCategory m in a) { anotherEntry.Media.Categories.Remove(m); } Assert.AreEqual(newEntry.Media.Description.Value, anotherEntry.Media.Description.Value, "Description should be equal"); Assert.AreEqual(newEntry.Media.Keywords.Value, anotherEntry.Media.Keywords.Value, "Keywords should be equal"); // now update the video anotherEntry.MediaSource = new MediaFileSource(Path.Combine(this.resourcePath, "test.mp4"), "video/mp4"); anotherEntry.Update(); // now delete the guy again newEntry.Delete(); } [Test] public void YouTubeRatingsTest() { Tracing.TraceMsg("Entering YouTubeRatingsTest"); string videoOwner = "GoogleDevelopers"; YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); // GetVideoFeed gets you a users video feed Feed<Video> feed = f.GetVideoFeed(videoOwner); // this will get you just the first 25 videos. foreach (Video v in feed.Entries) { Rating rating = new Rating(); rating.Value = 1; v.YouTubeEntry.Rating = rating; YouTubeEntry ratedEntry = f.Service.Insert(new Uri(v.YouTubeEntry.RatingsLink.ToString()), v.YouTubeEntry); Assert.AreEqual(1, ratedEntry.Rating.Value, "Rating should be equal to 1"); break; // we can stop after one } } [Test] public void YouTubeYtRatingsLikeTest() { Tracing.TraceMsg("Entering YouTubeYtRatingsLikeTest"); string videoOwner = "GoogleDevelopers"; YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); // GetVideoFeed gets you a users video feed Feed<Video> feed = f.GetVideoFeed(videoOwner); // this will get you just the first 25 videos. foreach (Video v in feed.Entries) { YtRating rating = new YtRating(YtRating.Like); v.YouTubeEntry.YtRating = rating; YouTubeEntry ratedEntry = f.Service.Insert(new Uri(v.YouTubeEntry.RatingsLink.ToString()), v.YouTubeEntry); Assert.AreEqual(YtRating.Like, ratedEntry.YtRating.RatingValue, "YtRating should be equal to like"); break; // we can stop after one } } [Test] public void YouTubeYtRatingsDislikeTest() { Tracing.TraceMsg("Entering YouTubeYtRatingsDislikeTest"); string videoOwner = "GoogleDevelopers"; YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); // GetVideoFeed gets you a users video feed Feed<Video> feed = f.GetVideoFeed(videoOwner); // this will get you just the first 25 videos. foreach (Video v in feed.Entries) { YtRating rating = new YtRating(YtRating.Dislike); v.YouTubeEntry.YtRating = rating; YouTubeEntry ratedEntry = f.Service.Insert(new Uri(v.YouTubeEntry.RatingsLink.ToString()), v.YouTubeEntry); Assert.AreEqual(YtRating.Dislike, ratedEntry.YtRating.RatingValue, "YtRating should be equal to dislike"); break; // we can stop after one } } [Test] public void YouTubeUploaderTest() { Tracing.TraceMsg("Entering YouTubeUploaderTest"); YouTubeQuery query = new YouTubeQuery(); query.Uri = new Uri(CreateUri(Path.Combine(this.resourcePath, "uploaderyt.xml"))); YouTubeService service = new YouTubeService("NETUnittests", this.ytDevKey); if (!string.IsNullOrEmpty(this.ytUser)) { service.Credentials = new GDataCredentials(this.ytUser, this.ytPwd); } YouTubeFeed feed = service.Query(query); YouTubeEntry entry = feed.Entries[0] as YouTubeEntry; YouTube.MediaCredit uploader = entry.Uploader; Assert.IsTrue(uploader != null); Assert.IsTrue(uploader.Role == "uploader"); Assert.IsTrue(uploader.Scheme == "urn:youtube"); Assert.IsTrue(uploader.Value == "GoogleDevelopers"); } ///////////////////////// START OF REQUEST TESTS [Test] public void YouTubeRequestTest() { Tracing.TraceMsg("Entering YouTubeRequestTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); // GetVideoFeed gets you a users video feed Feed<Video> feed = f.GetVideoFeed(null); // this will get you just the first 25 videos. foreach (Video v in feed.Entries) { Assert.IsTrue(v.AtomEntry != null, "There should be an atomentry"); Assert.IsTrue(v.Title != null, "There should be a title"); Assert.IsTrue(v.VideoId != null, "There should be a videoID"); } Feed<Video> sfeed = f.GetStandardFeed(YouTubeQuery.MostPopular); int iCountOne = 0; // this loop gets you all videos in the mostpopular video feeed foreach (Video v in sfeed.Entries) { Assert.IsTrue(v.AtomEntry != null, "There should be an atomentry"); Assert.IsTrue(v.Title != null, "There should be a title"); Assert.IsTrue(v.VideoId != null, "There should be a videoID"); iCountOne++; } int iCountTwo = 0; sfeed.AutoPaging = true; sfeed.Maximum = 50; foreach (Video v in sfeed.Entries) { Assert.IsTrue(v.AtomEntry != null, "There should be an atomentry"); Assert.IsTrue(v.Title != null, "There should be a title"); Assert.IsTrue(v.VideoId != null, "There should be a videoID"); iCountTwo++; } Assert.IsTrue(iCountTwo > iCountOne); } [Test] public void YouTubePlaylistRequestTest() { Tracing.TraceMsg("Entering YouTubePlaylistRequestTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); // GetVideoFeed gets you a users video feed Feed<Playlist> feed = f.GetPlaylistsFeed(null); // this will get you just the first 25 videos. foreach (Playlist p in feed.Entries) { Assert.IsTrue(p.AtomEntry != null); Assert.IsTrue(p.Title != null); Feed<PlayListMember> list = f.GetPlaylist(p); foreach (PlayListMember v in list.Entries) { Assert.IsTrue(v.AtomEntry != null, "There should be an atomentry"); Assert.IsTrue(v.Title != null, "There should be a title"); Assert.IsTrue(v.VideoId != null, "There should be a videoID"); // there might be no watchpage (not published yet) // Assert.IsTrue(v.WatchPage != null, "There should be a watchpage"); } } } [Ignore("not ready yet")] [Test] public void YouTubePlaylistBatchTest() { Tracing.TraceMsg("Entering YouTubePlaylistBatchTest"); string playlistOwner = "GoogleDevelopers"; YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); // GetVideoFeed gets you a users video feed Feed<Playlist> feed = f.GetPlaylistsFeed(playlistOwner); // this will get you just the first 25 playlists. List<Playlist> list = new List<Playlist>(); foreach (Playlist p in feed.Entries) { list.Add(p); } Feed<PlayListMember> videos = f.GetPlaylist(list[0]); List<PlayListMember> lvideo = new List<PlayListMember>(); foreach (PlayListMember v in videos.Entries) { lvideo.Add(v); } List<PlayListMember> batch = new List<PlayListMember>(); PlayListMember toBatch = new PlayListMember(); toBatch.Id = lvideo[0].Id; toBatch.VideoId = lvideo[0].VideoId; toBatch.BatchData = new GDataBatchEntryData(); toBatch.BatchData.Id = "NEWGUY"; toBatch.BatchData.Type = GDataBatchOperationType.insert; batch.Add(toBatch); toBatch = lvideo[0]; toBatch.BatchData = new GDataBatchEntryData(); toBatch.BatchData.Id = "DELETEGUY"; toBatch.BatchData.Type = GDataBatchOperationType.delete; batch.Add(toBatch); Feed<PlayListMember> updatedVideos = f.Batch(batch, videos); foreach (Video v in updatedVideos.Entries) { Assert.IsTrue(v.BatchData.Status.Code < 300, "one batch operation failed: " + v.BatchData.Status.Reason); } } [Test] public void YouTubeCommentRequestTest() { Tracing.TraceMsg("Entering YouTubeCommentRequestTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); Feed<Video> feed = f.GetStandardFeed(YouTubeQuery.MostPopular); // this will get you the first 25 videos, let's retrieve comments for the first one only foreach (Video v in feed.Entries) { Feed<Comment> list = f.GetComments(v); foreach (Comment c in list.Entries) { Assert.IsTrue(c.AtomEntry != null); Assert.IsTrue(c.Title != null); } break; } } [Test] public void YouTubeMaximumTest() { Tracing.TraceMsg("Entering YouTubeMaximumTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); settings.Maximum = 15; YouTubeRequest f = new YouTubeRequest(settings); Feed<Video> feed = f.GetStandardFeed(YouTubeQuery.MostPopular); int iCount = 0; // this will get you just the first 15 videos. foreach (Video v in feed.Entries) { iCount++; } Assert.AreEqual(iCount, 15); } [Test] public void YouTubeUnAuthenticatedRequestTest() { Tracing.TraceMsg("Entering YouTubeUnAuthenticatedRequestTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey); settings.AutoPaging = true; settings.Maximum = 50; YouTubeRequest f = new YouTubeRequest(settings); Feed<Video> feed = f.GetStandardFeed(YouTubeQuery.MostPopular); // this will get you the first 25 videos, let's retrieve comments for the first one only foreach (Video v in feed.Entries) { Feed<Comment> list = f.GetComments(v); foreach (Comment c in list.Entries) { Assert.IsTrue(c.AtomEntry != null); Assert.IsTrue(c.Title != null); } break; } } [Test] public void YouTubeRequestInsertTest() { Tracing.TraceMsg("Entering YouTubeRequestInsertTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); Video v = new Video(); v.Title = "Sample upload"; v.Description = "This is a test with and & in it"; MediaCategory category = new MediaCategory("Nonprofit"); category.Attributes["scheme"] = YouTubeService.DefaultCategory; v.Tags.Add(category); v.Keywords = "math"; v.YouTubeEntry.MediaSource = new MediaFileSource(Path.Combine(this.resourcePath, "test_movie.mov"), "video/quicktime"); Video newVideo = f.Upload(this.ytUser, v); newVideo.Title = "This test upload will soon be deleted"; Video updatedVideo = f.Update(newVideo); Assert.AreEqual(updatedVideo.Description, newVideo.Description, "Description should be equal"); Assert.AreEqual(updatedVideo.Keywords, newVideo.Keywords, "Keywords should be equal"); newVideo.YouTubeEntry.MediaSource = new MediaFileSource(Path.Combine(this.resourcePath, "test.mp4"), "video/mp4"); Video last = f.Update(updatedVideo); f.Delete(last); } [Test] public void YouTubePageSizeTest() { Tracing.TraceMsg("Entering YouTubePageSizeTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); settings.PageSize = 15; YouTubeRequest f = new YouTubeRequest(settings); Feed<Video> feed = f.GetStandardFeed(YouTubeQuery.MostPopular); int iCount = 0; // this will get you just the first 15 videos. foreach (Video v in feed.Entries) { iCount++; f.Settings.PageSize = 5; Feed<Comment> list = f.GetComments(v); int i = 0; foreach (Comment c in list.Entries) { i++; } Assert.IsTrue(i <= 5, "the count should be smaller/equal 5"); Assert.IsTrue(list.PageSize == -1 || list.PageSize == 5, "the returned pagesize should be 5 or -1 as well"); } Assert.AreEqual(iCount, 15, "the outer feed should count 15"); Assert.AreEqual(feed.PageSize, 15, "outer feed pagesize should be 15"); } [Test] public void YouTubePagingTest() { Tracing.TraceMsg("Entering YouTubePagingTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); settings.PageSize = 15; YouTubeRequest f = new YouTubeRequest(settings); Feed<Video> feed = f.GetStandardFeed(YouTubeQuery.MostPopular); Feed<Video> prev = f.Get<Video>(feed, FeedRequestType.Prev); Assert.IsTrue(prev == null, "the first chunk should not have a prev"); Feed<Video> next = f.Get<Video>(feed, FeedRequestType.Next); Assert.IsTrue(next != null, "the next chunk should exist"); prev = f.Get<Video>(next, FeedRequestType.Prev); Assert.IsTrue(prev != null, "the prev chunk should exist now"); } [Test] public void YouTubeGetTest() { Tracing.TraceMsg("Entering YouTubeGetTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); settings.PageSize = 15; YouTubeRequest f = new YouTubeRequest(settings); Feed<Video> feed = f.GetStandardFeed(YouTubeQuery.MostPopular); foreach (Video v in feed.Entries) { // remove the etag to force a refresh v.YouTubeEntry.Etag = null; Video refresh = f.Retrieve(v); Assert.AreEqual(refresh.VideoId, v.VideoId, "The ID values should be equal"); } } [Test] public void YouTubePrivateTest() { Tracing.TraceMsg("Entering YouTubePrivateTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); settings.PageSize = 15; settings.AutoPaging = true; YouTubeRequest f = new YouTubeRequest(settings); Feed<Video> feed = f.GetVideoFeed(null); Video privateVideo = null; foreach (Video v in feed.Entries) { if (v.IsDraft == false) { v.YouTubeEntry.Private = true; privateVideo = f.Update(v); } else { // there should be a state as well State s = v.YouTubeEntry.State; Assert.IsNotNull(s, "state should not be null"); Assert.IsNotNull(s.Reason, "State.Reason should not be null"); } } Assert.IsTrue(privateVideo != null, "we should have one private video"); Assert.IsTrue(privateVideo.YouTubeEntry.Private, "that video should be private"); privateVideo.YouTubeEntry.Private = false; Video ret = f.Update(privateVideo); Assert.IsTrue(ret != null, "we should have one private video"); Assert.IsTrue(!ret.YouTubeEntry.Private, "that video should be not private"); } [Test] public void YouTubeGetCategoriesTest() { Tracing.TraceMsg("Entering YouTubeGetCategoriesTest"); AtomCategoryCollection collection = YouTubeQuery.GetYouTubeCategories(); foreach (YouTubeCategory cat in collection) { Assert.IsTrue(cat.Term != null); Assert.IsTrue(cat.Assignable || cat.Deprecated || cat.Browsable != null); if (cat.Assignable) { Assert.IsTrue(cat.Browsable != null, "Assumption, if its assignable, it's browsable"); } } } [Test] public void YouTubeGetActivitiesTest() { ActivitiesQuery query = new ActivitiesQuery(); query.ModifiedSince = new DateTime(1980, 12, 1); YouTubeService service = new YouTubeService("NETUnittests", this.ytDevKey); if (!string.IsNullOrEmpty(this.ytUser)) { service.Credentials = new GDataCredentials(this.ytUser, this.ytPwd); } ActivitiesFeed feed = service.Query(query) as ActivitiesFeed; foreach (ActivityEntry e in feed.Entries) { Assert.IsTrue(e.VideoId != null, "There should be a videoid"); } service = null; } [Test] public void YouTubeRequestActivitiesTest() { Tracing.TraceMsg("Entering YouTubeRequestActivitiesTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); // this returns the server default answer Feed<Activity> feed = f.GetActivities(); foreach (Activity a in feed.Entries) { Assert.IsTrue(a.VideoId != null, "There should be a VideoId"); } // now let's find all that happened in the last 24 hours DateTime t = DateTime.Now.AddDays(-1); // this returns the all activities for the last 24 hours try { Feed<Activity> yesterday = f.GetActivities(t); foreach (Activity a in yesterday.Entries) { Assert.IsTrue(a.VideoId != null, "There should be a VideoId"); } } catch (GDataNotModifiedException e) { Assert.IsTrue(e != null); } t = DateTime.Now.AddMinutes(-1); // this returns the all activities for the last 1 minute, should be empty or throw a not modified try { Feed<Activity> lastmin = f.GetActivities(t); int iCount = 0; foreach (Activity a in lastmin.Entries) { iCount++; } Assert.IsTrue(iCount == 0, "There should be no activity for the last minute"); } catch (GDataNotModifiedException e) { Assert.IsTrue(e != null); } } [Test] public void YouTubeSubscriptionsTest() { Tracing.TraceMsg("Entering YouTubeSubscriptionsTest"); string channelUsername = "GoogleDevelopers"; YouTubeRequestSettings settings = new YouTubeRequestSettings(this.ApplicationName, this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); // this returns the server default answer Feed<Subscription> feed = f.GetSubscriptionsFeed(null); foreach (Subscription s in feed.Entries) { if (!string.IsNullOrEmpty(s.UserName) && s.UserName == channelUsername) { f.Delete(s); } } Subscription sub = new Subscription(); sub.Type = SubscriptionEntry.SubscriptionType.channel; sub.UserName = "GoogleDevelopers"; f.Insert(feed, sub); // this returns the server default answer feed = f.GetSubscriptionsFeed(null); List<Subscription> list = new List<Subscription>(); foreach (Subscription s in feed.Entries) { if (!string.IsNullOrEmpty(s.UserName) && s.UserName == channelUsername) { list.Add(s); } } Assert.IsTrue(list.Count > 0, "There should be one subscription matching"); foreach (Subscription s in list) { f.Delete(s); } feed = f.GetSubscriptionsFeed(null); int iCount = 0; foreach (Subscription s in feed.Entries) { iCount++; } Assert.IsTrue(iCount == 0, "There should be no subscriptions in the feed"); } [Test] public void YouTubeUserActivitiesTest() { Tracing.TraceMsg("Entering YouTubeUserActivitiesTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey); YouTubeRequest f = new YouTubeRequest(settings); List<string> users = new List<string>(); users.Add("whiskeytonsils"); users.Add("joelandberry"); // this returns the server default answer Feed<Activity> feed = f.GetActivities(users); foreach (Activity a in feed.Entries) { VerifyActivity(a); } // now let's find all that happened in the last 24 hours DateTime t = DateTime.Now.AddDays(-1); // this returns the all activities for the last 24 hours try { Feed<Activity> yesterday = f.GetActivities(users, t); foreach (Activity a in yesterday.Entries) { VerifyActivity(a); } } catch (GDataNotModifiedException e) { Assert.IsTrue(e != null); } t = DateTime.Now.AddMinutes(-1); // this returns all activities for the last 1 minute, should be empty or throw a not modified try { Feed<Activity> lastmin = f.GetActivities(users, t); int iCount = 0; foreach (Activity a in lastmin.Entries) { iCount++; } Assert.IsTrue(iCount == 0, "There should be no activity for the last minute"); } catch (GDataNotModifiedException e) { Assert.IsTrue(e != null); } } [Test] public void YouTubeAccessControlTest() { Tracing.TraceMsg("Entering YouTubeAccessControlTest"); YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest f = new YouTubeRequest(settings); Video v = new Video(); v.Title = "Sample upload"; v.Description = "This is a test with different access control values"; MediaCategory category = new MediaCategory("Nonprofit"); category.Attributes["scheme"] = YouTubeService.DefaultCategory; v.Tags.Add(category); v.Keywords = "math"; v.YouTubeEntry.MediaSource = new MediaFileSource(Path.Combine(this.resourcePath, "test_movie.mov"), "video/quicktime"); v.YouTubeEntry.AccessControls.Add(new YtAccessControl(YtAccessControl.RateAction, YtAccessControl.DeniedPermission)); v.YouTubeEntry.AccessControls.Add(new YtAccessControl(YtAccessControl.CommentAction, YtAccessControl.ModeratedPermission)); Video newVideo = f.Upload(this.ytUser, v); ExtensionCollection<YtAccessControl> acl = newVideo.YouTubeEntry.AccessControls; for (int i = 0; i < acl.Count; i++) { YtAccessControl ac = acl[i]; switch (ac.Action) { case YtAccessControl.RateAction: Assert.AreEqual(ac.Permission, YtAccessControl.DeniedPermission, "Rating should be denied"); break; case YtAccessControl.CommentAction: Assert.AreEqual(ac.Permission, YtAccessControl.ModeratedPermission, "Comments should be moderated"); break; case YtAccessControl.CommentVoteAction: Assert.AreEqual(ac.Permission, YtAccessControl.AllowedPermission, "Comment rating should be allowed"); break; case YtAccessControl.VideoRespondAction: Assert.AreEqual(ac.Permission, YtAccessControl.ModeratedPermission, "Video responses should be moderated"); break; case YtAccessControl.ListAction: Assert.AreEqual(ac.Permission, YtAccessControl.AllowedPermission, "Video listing should be allowed"); break; case YtAccessControl.EmbedAction: Assert.AreEqual(ac.Permission, YtAccessControl.AllowedPermission, "Video embed should be allowed"); break; case YtAccessControl.SyndicateAction: Assert.AreEqual(ac.Permission, YtAccessControl.AllowedPermission, "Video syndicate should be allowed"); break; } } f.Delete(newVideo); } private void VerifyActivity(Activity a) { switch (a.Type) { case ActivityType.Favorited: case ActivityType.Rated: case ActivityType.Shared: case ActivityType.Commented: case ActivityType.Uploaded: Assert.IsTrue(a.VideoId != null, "There should be a VideoId"); break; case ActivityType.FriendAdded: case ActivityType.SubscriptionAdded: Assert.IsTrue(a.Username != null, "There should be a username"); break; } } static void printVideoEntry(Video video) { Console.WriteLine("Title: " + video.Title); Console.WriteLine(video.Description); Console.WriteLine("Keywords: " + video.Keywords); Console.WriteLine("Uploaded by: " + video.Uploader); if (video.YouTubeEntry.Location != null) { Console.WriteLine("Latitude: " + video.YouTubeEntry.Location.Latitude); Console.WriteLine("Longitude: " + video.YouTubeEntry.Location.Longitude); } if (video.Media != null && video.Media.Rating != null) { Console.WriteLine("Restricted in: " + video.Media.Rating.Country); } if (video.IsDraft) { Console.WriteLine("Video is not live."); string stateName = video.Status.Name; if (stateName == "processing") { Console.WriteLine("Video is still being processed."); } else if (stateName == "rejected") { Console.Write("Video has been rejected because: "); Console.WriteLine(video.Status.Value); Console.Write("For help visit: "); Console.WriteLine(video.Status.Help); } else if (stateName == "failed") { Console.Write("Video failed uploading because:"); Console.WriteLine(video.Status.Value); Console.Write("For help visit: "); Console.WriteLine(video.Status.Help); } } if (video.AtomEntry.EditUri != null) { Console.WriteLine("Video is editable by the current user."); } if (video.Rating != -1) { Console.WriteLine("Average rating: " + video.Rating); } if (video.ViewCount != -1) { Console.WriteLine("View count: " + video.ViewCount); } Console.WriteLine("Thumbnails:"); foreach (MediaThumbnail thumbnail in video.Thumbnails) { Console.WriteLine("\tThumbnail URL: " + thumbnail.Url); Console.WriteLine("\tThumbnail time index: " + thumbnail.Time); } Console.WriteLine("Media:"); foreach (Google.GData.YouTube.MediaContent mediaContent in video.Contents) { Console.WriteLine("\tMedia Location: " + mediaContent.Url); Console.WriteLine("\tMedia Type: " + mediaContent.Format); Console.WriteLine("\tDuration: " + mediaContent.Duration); } } } [TestFixture] [Category("LiveTest")] public class YouTubeVerticalTestSuite : BaseLiveTestClass { private string ytClient; private string ytDevKey; private string ytUser; private string ytPwd; public YouTubeVerticalTestSuite() { } public override string ServiceName { get { return ServiceNames.YouTube; } } protected override void ReadConfigFile() { base.ReadConfigFile(); if (unitTestConfiguration.Contains("youTubeClientID")) { this.ytClient = (string)unitTestConfiguration["youTubeClientID"]; } if (unitTestConfiguration.Contains("youTubeDevKey")) { this.ytDevKey = (string)unitTestConfiguration["youTubeDevKey"]; } if (unitTestConfiguration.Contains("youTubeUser")) { this.ytUser = (string)unitTestConfiguration["youTubeUser"]; } if (unitTestConfiguration.Contains("youTubePwd")) { this.ytPwd = (string)unitTestConfiguration["youTubePwd"]; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Globalization; using System.Net.Security; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Text; using System.Xml; namespace System.ServiceModel.Channels { public abstract class SecurityBindingElement : BindingElement { internal const bool defaultIncludeTimestamp = true; internal const bool defaultAllowInsecureTransport = false; internal const bool defaultRequireSignatureConfirmation = false; internal const bool defaultEnableUnsecuredResponse = false; internal const bool defaultProtectTokens = false; private SupportingTokenParameters _endpointSupportingTokenParameters; private bool _includeTimestamp; private LocalClientSecuritySettings _localClientSettings; private MessageSecurityVersion _messageSecurityVersion; private SecurityHeaderLayout _securityHeaderLayout; private bool _protectTokens = defaultProtectTokens; internal SecurityBindingElement() : base() { _messageSecurityVersion = MessageSecurityVersion.Default; _includeTimestamp = defaultIncludeTimestamp; _localClientSettings = new LocalClientSecuritySettings(); _endpointSupportingTokenParameters = new SupportingTokenParameters(); _securityHeaderLayout = SecurityProtocolFactory.defaultSecurityHeaderLayout; throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement is not supported"); } internal SecurityBindingElement(SecurityBindingElement elementToBeCloned) : base(elementToBeCloned) { if (elementToBeCloned == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("elementToBeCloned"); _includeTimestamp = elementToBeCloned._includeTimestamp; _messageSecurityVersion = elementToBeCloned._messageSecurityVersion; _securityHeaderLayout = elementToBeCloned._securityHeaderLayout; _endpointSupportingTokenParameters = elementToBeCloned._endpointSupportingTokenParameters.Clone(); _localClientSettings = elementToBeCloned._localClientSettings.Clone(); throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement cloning not supported."); } public SupportingTokenParameters EndpointSupportingTokenParameters { get { return _endpointSupportingTokenParameters; } } public SecurityHeaderLayout SecurityHeaderLayout { get { return _securityHeaderLayout; } set { if (!SecurityHeaderLayoutHelper.IsDefined(value)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); _securityHeaderLayout = value; } } public MessageSecurityVersion MessageSecurityVersion { get { return _messageSecurityVersion; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); _messageSecurityVersion = value; } } public bool IncludeTimestamp { get { return _includeTimestamp; } set { _includeTimestamp = value; } } public LocalClientSecuritySettings LocalClientSettings { get { return _localClientSettings; } } internal virtual bool SessionMode { get { return false; } } internal virtual bool SupportsDuplex { get { return false; } } internal virtual bool SupportsRequestReply { get { return false; } } private void GetSupportingTokensCapabilities(ICollection<SecurityTokenParameters> parameters, out bool supportsClientAuth, out bool supportsWindowsIdentity) { supportsClientAuth = false; supportsWindowsIdentity = false; foreach (SecurityTokenParameters p in parameters) { if (p.SupportsClientAuthentication) supportsClientAuth = true; if (p.SupportsClientWindowsIdentity) supportsWindowsIdentity = true; } } private void GetSupportingTokensCapabilities(SupportingTokenParameters requirements, out bool supportsClientAuth, out bool supportsWindowsIdentity) { supportsClientAuth = false; supportsWindowsIdentity = false; bool tmpSupportsClientAuth; bool tmpSupportsWindowsIdentity; this.GetSupportingTokensCapabilities(requirements.Endorsing, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity); supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth; supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity; this.GetSupportingTokensCapabilities(requirements.SignedEndorsing, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity); supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth; supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity; this.GetSupportingTokensCapabilities(requirements.SignedEncrypted, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity); supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth; supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity; } internal void GetSupportingTokensCapabilities(out bool supportsClientAuth, out bool supportsWindowsIdentity) { this.GetSupportingTokensCapabilities(this.EndpointSupportingTokenParameters, out supportsClientAuth, out supportsWindowsIdentity); } protected static void SetIssuerBindingContextIfRequired(SecurityTokenParameters parameters, BindingContext issuerBindingContext) { throw ExceptionHelper.PlatformNotSupported("SetIssuerBindingContextIfRequired is not supported."); } internal bool RequiresChannelDemuxer(SecurityTokenParameters parameters) { throw ExceptionHelper.PlatformNotSupported("RequiresChannelDemuxer is not supported."); } internal virtual bool RequiresChannelDemuxer() { foreach (SecurityTokenParameters parameters in EndpointSupportingTokenParameters.Endorsing) { if (RequiresChannelDemuxer(parameters)) { return true; } } foreach (SecurityTokenParameters parameters in EndpointSupportingTokenParameters.SignedEndorsing) { if (RequiresChannelDemuxer(parameters)) { return true; } } return false; } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { if (context == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.BuildChannelFactory is not supported."); } protected abstract IChannelFactory<TChannel> BuildChannelFactoryCore<TChannel>(BindingContext context); public override bool CanBuildChannelFactory<TChannel>(BindingContext context) { if (context == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.CanBuildChannelFactory is not supported."); } private bool CanBuildSessionChannelFactory<TChannel>(BindingContext context) { if (!(context.CanBuildInnerChannelFactory<IRequestChannel>() || context.CanBuildInnerChannelFactory<IRequestSessionChannel>() || context.CanBuildInnerChannelFactory<IDuplexChannel>() || context.CanBuildInnerChannelFactory<IDuplexSessionChannel>())) { return false; } if (typeof(TChannel) == typeof(IRequestSessionChannel)) { return (context.CanBuildInnerChannelFactory<IRequestChannel>() || context.CanBuildInnerChannelFactory<IRequestSessionChannel>()); } else if (typeof(TChannel) == typeof(IDuplexSessionChannel)) { return (context.CanBuildInnerChannelFactory<IDuplexChannel>() || context.CanBuildInnerChannelFactory<IDuplexSessionChannel>()); } else { return false; } } public virtual void SetKeyDerivation(bool requireDerivedKeys) { throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.SetKeyDerivation is not supported."); } internal virtual bool IsSetKeyDerivation(bool requireDerivedKeys) { if (!this.EndpointSupportingTokenParameters.IsSetKeyDerivation(requireDerivedKeys)) return false; return true; } public override T GetProperty<T>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } if (typeof(T) == typeof(ISecurityCapabilities)) { return (T)(object)GetSecurityCapabilities(context); } else if (typeof(T) == typeof(IdentityVerifier)) { return (T)(object)_localClientSettings.IdentityVerifier; } else { return context.GetInnerProperty<T>(); } } internal abstract ISecurityCapabilities GetIndividualISecurityCapabilities(); private ISecurityCapabilities GetSecurityCapabilities(BindingContext context) { ISecurityCapabilities thisSecurityCapability = this.GetIndividualISecurityCapabilities(); ISecurityCapabilities lowerSecurityCapability = context.GetInnerProperty<ISecurityCapabilities>(); if (lowerSecurityCapability == null) { return thisSecurityCapability; } else { bool supportsClientAuth = thisSecurityCapability.SupportsClientAuthentication; bool supportsClientWindowsIdentity = thisSecurityCapability.SupportsClientWindowsIdentity; bool supportsServerAuth = thisSecurityCapability.SupportsServerAuthentication || lowerSecurityCapability.SupportsServerAuthentication; ProtectionLevel requestProtectionLevel = ProtectionLevelHelper.Max(thisSecurityCapability.SupportedRequestProtectionLevel, lowerSecurityCapability.SupportedRequestProtectionLevel); ProtectionLevel responseProtectionLevel = ProtectionLevelHelper.Max(thisSecurityCapability.SupportedResponseProtectionLevel, lowerSecurityCapability.SupportedResponseProtectionLevel); return new SecurityCapabilities(supportsClientAuth, supportsServerAuth, supportsClientWindowsIdentity, requestProtectionLevel, responseProtectionLevel); } } // If any changes are made to this method, please make sure that they are // reflected in the corresponding IsMutualCertificateBinding() method. static public SecurityBindingElement CreateMutualCertificateBindingElement() { return CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11); } // this method reverses CreateMutualCertificateBindingElement() logic internal static bool IsMutualCertificateBinding(SecurityBindingElement sbe) { return IsMutualCertificateBinding(sbe, false); } // If any changes are made to this method, please make sure that they are // reflected in the corresponding IsMutualCertificateBinding() method. static public SecurityBindingElement CreateMutualCertificateBindingElement(MessageSecurityVersion version) { return CreateMutualCertificateBindingElement(version, false); } // If any changes are made to this method, please make sure that they are // reflected in the corresponding IsMutualCertificateBinding() method. static public SecurityBindingElement CreateMutualCertificateBindingElement(MessageSecurityVersion version, bool allowSerializedSigningTokenOnReply) { if (version == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version"); } throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.CreateMutualCertificateBindingElement is not supported."); } // this method reverses CreateMutualCertificateBindingElement() logic internal static bool IsMutualCertificateBinding(SecurityBindingElement sbe, bool allowSerializedSigningTokenOnReply) { throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.IsMutualCertificateBinding is not supported."); } // If any changes are made to this method, please make sure that they are // reflected in the corresponding IsUserNameOverTransportBinding() method. static public TransportSecurityBindingElement CreateUserNameOverTransportBindingElement() { TransportSecurityBindingElement result = new TransportSecurityBindingElement(); result.EndpointSupportingTokenParameters.SignedEncrypted.Add( new UserNameSecurityTokenParameters()); result.IncludeTimestamp = true; return result; } // this method reverses CreateMutualCertificateBindingElement() logic internal static bool IsUserNameOverTransportBinding(SecurityBindingElement sbe) { // do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings if (!sbe.IncludeTimestamp) return false; if (!(sbe is TransportSecurityBindingElement)) return false; SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters; if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 1 || parameters.Endorsing.Count != 0 || parameters.SignedEndorsing.Count != 0) return false; UserNameSecurityTokenParameters userNameParameters = parameters.SignedEncrypted[0] as UserNameSecurityTokenParameters; if (userNameParameters == null) return false; return true; } // If any changes are made to this method, please make sure that they are // reflected in the corresponding IsCertificateOverTransportBinding() method. static public TransportSecurityBindingElement CreateCertificateOverTransportBindingElement(MessageSecurityVersion version) { if (version == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version"); } throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.CreateCertificateOverTransportBindingElement is not supported."); } // this method reverses CreateMutualCertificateBindingElement() logic internal static bool IsCertificateOverTransportBinding(SecurityBindingElement sbe) { // do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings if (!sbe.IncludeTimestamp) return false; if (!(sbe is TransportSecurityBindingElement)) return false; SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters; if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 0 || parameters.Endorsing.Count != 1 || parameters.SignedEndorsing.Count != 0) return false; throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.IsCertificateOverTransportBinding is not supported."); } // If any changes are made to this method, please make sure that they are // reflected in the corresponding IsSecureConversationBinding() method. static public SecurityBindingElement CreateSecureConversationBindingElement(SecurityBindingElement bootstrapSecurity) { throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.CreateSecureConversatationBindingElement is not supported."); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "{0}:", this.GetType().ToString())); sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "IncludeTimestamp: {0}", _includeTimestamp.ToString())); sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "MessageSecurityVersion: {0}", this.MessageSecurityVersion.ToString())); sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "SecurityHeaderLayout: {0}", _securityHeaderLayout.ToString())); sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "ProtectTokens: {0}", _protectTokens.ToString())); sb.AppendLine("EndpointSupportingTokenParameters:"); sb.AppendLine(" " + this.EndpointSupportingTokenParameters.ToString().Trim().Replace("\n", "\n ")); return sb.ToString().Trim(); } } }
using System; // //Module : AAPHYSICALMOON.CPP //Purpose: Implementation for the algorithms which obtain the physical parameters of the Moon //Created: PJN / 17-01-2004 //History: PJN / 19-02-2004 1. The optical libration in longitude is now returned in the range -180 - 180 degrees // //Copyright (c) 2004 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) // //All rights reserved. // //Copyright / Usage Details: // //You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) //when your product is released in binary form. You are allowed to modify the source code in any way you want //except you cannot modify the copyright details at the top of each module. If you want to distribute source //code with your application, then you are only allowed to distribute versions released by the author. This is //to maintain a single distribution point for the source code. // // ///////////////////////////////// Includes //////////////////////////////////// /////////////////////// Includes ////////////////////////////////////////////// /////////////////////// Classes /////////////////////////////////////////////// public class CAAPhysicalMoonDetails { //Constructors / Destructors public CAAPhysicalMoonDetails() { ldash = 0; bdash = 0; ldash2 = 0; bdash2 = 0; l = 0; b = 0; P = 0; } //Member variables public double ldash; public double bdash; public double ldash2; public double bdash2; public double l; public double b; public double P; } public class CAASelenographicMoonDetails { //Constructors / Destructors public CAASelenographicMoonDetails() { l0 = 0; b0 = 0; c0 = 0; } //Member variables public double l0; public double b0; public double c0; } public class CAAPhysicalMoon { //Static methods public static CAAPhysicalMoonDetails CalculateGeocentric(double JD) { double Lambda=0; double Beta=0; double epsilon=0; CAA2DCoordinate Equatorial = new CAA2DCoordinate(); return CalculateHelper(JD, ref Lambda, ref Beta, ref epsilon, ref Equatorial); } public static CAAPhysicalMoonDetails CalculateTopocentric(double JD, double Longitude, double Latitude) { //First convert to radians Longitude = CAACoordinateTransformation.DegreesToRadians(Longitude); Latitude = CAACoordinateTransformation.DegreesToRadians(Latitude); double Lambda=0; double Beta=0; double epsilon=0; CAA2DCoordinate Equatorial = new CAA2DCoordinate(); CAAPhysicalMoonDetails details = CalculateHelper(JD, ref Lambda, ref Beta, ref epsilon, ref Equatorial); double R = CAAMoon.RadiusVector(JD); double pi = CAAMoon.RadiusVectorToHorizontalParallax(R); double Alpha = CAACoordinateTransformation.HoursToRadians(Equatorial.X); double Delta = CAACoordinateTransformation.DegreesToRadians(Equatorial.Y); double AST = CAASidereal.ApparentGreenwichSiderealTime(JD); double H = CAACoordinateTransformation.HoursToRadians(AST) - Longitude - Alpha; double Q = Math.Atan2(Math.Cos(Latitude)*Math.Sin(H), Math.Cos(Delta)*Math.Sin(Latitude) - Math.Sin(Delta)*Math.Cos(Latitude)*Math.Cos(H)); double Z = Math.Acos(Math.Sin(Delta)*Math.Sin(Latitude) + Math.Cos(Delta)*Math.Cos(Latitude)*Math.Cos(H)); double pidash = pi*(Math.Sin(Z) + 0.0084 *Math.Sin(2 *Z)); double Prad = CAACoordinateTransformation.DegreesToRadians(details.P); double DeltaL = -pidash *Math.Sin(Q - Prad)/Math.Cos(CAACoordinateTransformation.DegreesToRadians(details.b)); details.l += DeltaL; double DeltaB = pidash *Math.Cos(Q - Prad); details.b += DeltaB; details.P += DeltaL *Math.Sin(CAACoordinateTransformation.DegreesToRadians(details.b)) - pidash *Math.Sin(Q)*Math.Tan(Delta); return details; } public static CAASelenographicMoonDetails CalculateSelenographicPositionOfSun(double JD) { double R = CAAEarth.RadiusVector(JD)*149597970; double Delta = CAAMoon.RadiusVector(JD); double lambda0 = CAASun.ApparentEclipticLongitude(JD); double lambda = CAAMoon.EclipticLongitude(JD); double beta = CAAMoon.EclipticLatitude(JD); double lambdah = CAACoordinateTransformation.MapTo0To360Range(lambda0 + 180 + Delta/R *57.296 *Math.Cos(CAACoordinateTransformation.DegreesToRadians(beta))*Math.Sin(CAACoordinateTransformation.DegreesToRadians(lambda0 - lambda))); double betah = Delta/R *beta; //What will be the return value CAASelenographicMoonDetails details = new CAASelenographicMoonDetails(); //Calculate the optical libration double omega=0; double DeltaU = 0; double sigma = 0; double I = 0; double rho = 0; double ldash0 = 0; double bdash0 = 0; double ldash20 = 0; double bdash20 = 0; double epsilon = 0; CalculateOpticalLibration(JD, lambdah, betah, ref ldash0, ref bdash0, ref ldash20, ref bdash20, ref epsilon, ref omega, ref DeltaU, ref sigma, ref I, ref rho); details.l0 = ldash0 + ldash20; details.b0 = bdash0 + bdash20; details.c0 = CAACoordinateTransformation.MapTo0To360Range(450 - details.l0); return details; } public static double AltitudeOfSun(double JD, double Longitude, double Latitude) { //Calculate the selenographic details CAASelenographicMoonDetails selenographicDetails = CalculateSelenographicPositionOfSun(JD); //convert to radians Latitude = CAACoordinateTransformation.DegreesToRadians(Latitude); Longitude = CAACoordinateTransformation.DegreesToRadians(Longitude); selenographicDetails.b0 = CAACoordinateTransformation.DegreesToRadians(selenographicDetails.b0); selenographicDetails.c0 = CAACoordinateTransformation.DegreesToRadians(selenographicDetails.c0); return CAACoordinateTransformation.RadiansToDegrees(Math.Asin(Math.Sin(selenographicDetails.b0)*Math.Sin(Latitude) + Math.Cos(selenographicDetails.b0)*Math.Cos(Latitude)*Math.Sin(selenographicDetails.c0 + Longitude))); } public static double TimeOfSunrise(double JD, double Longitude, double Latitude) { return SunriseSunsetHelper(JD, Longitude, Latitude, true); } public static double TimeOfSunset(double JD, double Longitude, double Latitude) { return SunriseSunsetHelper(JD, Longitude, Latitude, false); } protected static double SunriseSunsetHelper(double JD, double Longitude, double Latitude, bool bSunrise) { double JDResult = JD; double Latituderad = CAACoordinateTransformation.DegreesToRadians(Latitude); double h; do { h = AltitudeOfSun(JDResult, Longitude, Latitude); double DeltaJD = h/(12.19075 *Math.Cos(Latituderad)); if (bSunrise) JDResult -= DeltaJD; else JDResult += DeltaJD; } while (Math.Abs(h) > 0.001); return JDResult; } protected static CAAPhysicalMoonDetails CalculateHelper(double JD, ref double Lambda, ref double Beta, ref double epsilon, ref CAA2DCoordinate Equatorial) { //What will be the return value CAAPhysicalMoonDetails details = new CAAPhysicalMoonDetails(); //Calculate the initial quantities Lambda = CAAMoon.EclipticLongitude(JD); Beta = CAAMoon.EclipticLatitude(JD); //Calculate the optical libration double omega=0; double DeltaU=0; double sigma=0; double I=0; double rho=0; CalculateOpticalLibration(JD, Lambda, Beta, ref details.ldash, ref details.bdash, ref details.ldash2, ref details.bdash2, ref epsilon, ref omega, ref DeltaU, ref sigma, ref I, ref rho); double epsilonrad = CAACoordinateTransformation.DegreesToRadians(epsilon); //Calculate the total libration details.l = details.ldash + details.ldash2; details.b = details.bdash + details.bdash2; double b = CAACoordinateTransformation.DegreesToRadians(details.b); //Calculate the position angle double V = omega + DeltaU + CAACoordinateTransformation.DegreesToRadians(sigma)/Math.Sin(I); double I_rho = I + CAACoordinateTransformation.DegreesToRadians(rho); double X = Math.Sin(I_rho)*Math.Sin(V); double Y = Math.Sin(I_rho)*Math.Cos(V)*Math.Cos(epsilonrad) - Math.Cos(I_rho)*Math.Sin(epsilonrad); double w = Math.Atan2(X, Y); Equatorial = CAACoordinateTransformation.Ecliptic2Equatorial(Lambda, Beta, epsilon); double Alpha = CAACoordinateTransformation.HoursToRadians(Equatorial.X); details.P = CAACoordinateTransformation.RadiansToDegrees(Math.Asin(Math.Sqrt(X *X + Y *Y)*Math.Cos(Alpha - w)/(Math.Cos(b)))); return details; } //////////////////////////////// Implementation /////////////////////////////// protected static void CalculateOpticalLibration(double JD, double Lambda, double Beta, ref double ldash, ref double bdash, ref double ldash2, ref double bdash2, ref double epsilon, ref double omega, ref double DeltaU, ref double sigma, ref double I, ref double rho) { //Calculate the initial quantities double Lambdarad = CAACoordinateTransformation.DegreesToRadians(Lambda); double Betarad = CAACoordinateTransformation.DegreesToRadians(Beta); I = CAACoordinateTransformation.DegreesToRadians(1.54242); DeltaU = CAACoordinateTransformation.DegreesToRadians(CAANutation.NutationInLongitude(JD)/3600); double F = CAACoordinateTransformation.DegreesToRadians(CAAMoon.ArgumentOfLatitude(JD)); omega = CAACoordinateTransformation.DegreesToRadians(CAAMoon.MeanLongitudeAscendingNode(JD)); epsilon = CAANutation.MeanObliquityOfEcliptic(JD) + CAANutation.NutationInObliquity(JD)/3600; //Calculate the optical librations double W = Lambdarad - DeltaU/3600 - omega; double A = Math.Atan2(Math.Sin(W)*Math.Cos(Betarad)*Math.Cos(I) - Math.Sin(Betarad)*Math.Sin(I), Math.Cos(W)*Math.Cos(Betarad)); ldash = CAACoordinateTransformation.MapTo0To360Range(CAACoordinateTransformation.RadiansToDegrees(A) - CAACoordinateTransformation.RadiansToDegrees(F)); if (ldash > 180) ldash -= 360; bdash = Math.Asin(-Math.Sin(W)*Math.Cos(Betarad)*Math.Sin(I) - Math.Sin(Betarad)*Math.Cos(I)); //Calculate the physical librations double T = (JD - 2451545.0)/36525; double K1 = 119.75 + 131.849 *T; K1 = CAACoordinateTransformation.DegreesToRadians(K1); double K2 = 72.56 + 20.186 *T; K2 = CAACoordinateTransformation.DegreesToRadians(K2); double M = CAAEarth.SunMeanAnomaly(JD); M = CAACoordinateTransformation.DegreesToRadians(M); double Mdash = CAAMoon.MeanAnomaly(JD); Mdash = CAACoordinateTransformation.DegreesToRadians(Mdash); double D = CAAMoon.MeanElongation(JD); D = CAACoordinateTransformation.DegreesToRadians(D); double E = CAAEarth.Eccentricity(JD); rho = -0.02752 *Math.Cos(Mdash) + -0.02245 *Math.Sin(F) + 0.00684 *Math.Cos(Mdash - 2 *F) + -0.00293 *Math.Cos(2 *F) + -0.00085 *Math.Cos(2 *F - 2 *D) + -0.00054 *Math.Cos(Mdash - 2 *D) + -0.00020 *Math.Sin(Mdash + F) + -0.00020 *Math.Cos(Mdash + 2 *F) + -0.00020 *Math.Cos(Mdash - F) + 0.00014 *Math.Cos(Mdash + 2 *F - 2 *D); sigma = -0.02816 *Math.Sin(Mdash) + 0.02244 *Math.Cos(F) + -0.00682 *Math.Sin(Mdash - 2 *F) + -0.00279 *Math.Sin(2 *F) + -0.00083 *Math.Sin(2 *F - 2 *D) + 0.00069 *Math.Sin(Mdash - 2 *D) + 0.00040 *Math.Cos(Mdash + F) + -0.00025 *Math.Sin(2 *Mdash) + -0.00023 *Math.Sin(Mdash + 2 *F) + 0.00020 *Math.Cos(Mdash - F) + 0.00019 *Math.Sin(Mdash - F) + 0.00013 *Math.Sin(Mdash + 2 *F - 2 *D) + -0.00010 *Math.Cos(Mdash - 3 *F); double tau = 0.02520 *E *Math.Sin(M) + 0.00473 *Math.Sin(2 *Mdash - 2 *F) + -0.00467 *Math.Sin(Mdash) + 0.00396 *Math.Sin(K1) + 0.00276 *Math.Sin(2 *Mdash - 2 *D) + 0.00196 *Math.Sin(omega) + -0.00183 *Math.Cos(Mdash - F) + 0.00115 *Math.Sin(Mdash - 2 *D) + -0.00096 *Math.Sin(Mdash - D) + 0.00046 *Math.Sin(2 *F - 2 *D) + -0.00039 *Math.Sin(Mdash - F) + -0.00032 *Math.Sin(Mdash - M - D) + 0.00027 *Math.Sin(2 *Mdash - M - 2 *D) + 0.00023 *Math.Sin(K2) + -0.00014 *Math.Sin(2 *D) + 0.00014 *Math.Cos(2 *Mdash - 2 *F) + -0.00012 *Math.Sin(Mdash - 2 *F) + -0.00012 *Math.Sin(2 *Mdash) + 0.00011 *Math.Sin(2 *Mdash - 2 *M - 2 *D); ldash2 = -tau + (rho *Math.Cos(A) + sigma *Math.Sin(A))*Math.Tan(bdash); bdash = CAACoordinateTransformation.RadiansToDegrees(bdash); bdash2 = sigma *Math.Cos(A) - rho *Math.Sin(A); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Globalization { /*=================================TaiwanCalendar========================== ** ** Taiwan calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar. ** That is, ** Taiwan year = Gregorian year - 1911. So 1912/01/01 A.D. is Taiwan 1/01/01 ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1912/01/01 9999/12/31 ** Taiwan 01/01/01 8088/12/31 ============================================================================*/ public class TaiwanCalendar : Calendar { // // The era value for the current era. // // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 //m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911); // Initialize our era info. internal static EraInfo[] taiwanEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; internal static volatile Calendar s_defaultInstance; internal GregorianCalendarHelper helper; /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of TaiwanCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new TaiwanCalendar(); } return (s_defaultInstance); } internal static readonly DateTime calendarMinValue = new DateTime(1912, 1, 1); public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } // Return the type of the Taiwan calendar. // public TaiwanCalendar() { try { new CultureInfo("zh-TW"); } catch (ArgumentException e) { throw new TypeInitializationException(this.GetType().ToString(), e); } helper = new GregorianCalendarHelper(this, taiwanEraInfo); } internal override CalendarId ID { get { return CalendarId.TAIWAN; } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } public override int[] Eras { get { return (helper.Eras); } } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, helper.MaxYear)); } twoDigitYearMax = value; } } // For Taiwan calendar, four digit year is not used. // Therefore, for any two digit number, we just return the original number. public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedPosNum); } Contract.EndContractBlock(); if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, helper.MaxYear)); } return (year); } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Autodesk.Revit.DB; namespace Revit.SDK.Samples.PlaceFamilyInstanceByFace.CS { /// <summary> /// The main UI for creating family instance by face /// </summary> public partial class PlaceFamilyInstanceForm : System.Windows.Forms.Form { // the creator private FamilyInstanceCreator m_creator = null; // the base type private BasedType m_baseType = BasedType.Point; /// <summary> /// Constructor /// </summary> /// <param name="creator">the family instance creator</param> /// <param name="type">based-type</param> public PlaceFamilyInstanceForm(FamilyInstanceCreator creator, BasedType type) { m_creator = creator; m_creator.CheckFamilySymbol(type); m_baseType = type; InitializeComponent(); // set the face name list and the default value foreach (String name in creator.FaceNameList) { comboBoxFace.Items.Add(name); } if (comboBoxFace.Items.Count > 0) { SetFaceIndex(0); } // set the family name list and the default value foreach (String symbolName in m_creator.FamilySymbolNameList) { comboBoxFamily.Items.Add(symbolName); } if (m_creator.DefaultFamilySymbolIndex < 0) { comboBoxFamily.SelectedItem = m_creator.FamilySymbolNameList[0]; } else { comboBoxFamily.SelectedItem = m_creator.FamilySymbolNameList[m_creator.DefaultFamilySymbolIndex]; } // set UI display according to baseType switch (m_baseType) { case BasedType.Point: this.Text = "Place Point-Based Family Instance"; labelFirst.Text = "Location :"; labelSecond.Text = "Direction :"; break; case BasedType.Line: comboBoxFamily.SelectedItem = "Line-based"; this.Text = "Place Line-Based Family Instance"; labelFirst.Text = "Start Point :"; labelSecond.Text = "End Point :"; break; default: break; } AdjustComboBoxDropDownListWidth(comboBoxFace); AdjustComboBoxDropDownListWidth(comboBoxFamily); } /// <summary> /// Get face information when the selected face is changed /// </summary> /// <param name="index">the index of the new selected face</param> private void SetFaceIndex(int index) { comboBoxFace.SelectedItem = m_creator.FaceNameList[index]; BoundingBoxXYZ boundingBox = m_creator.GetFaceBoundingBox(index); Autodesk.Revit.DB.XYZ totle = boundingBox.Min + boundingBox.Max; switch (m_baseType) { case BasedType.Point: PointControlFirst.SetPointData(totle / 2.0f); PointControlSecond.SetPointData(new Autodesk.Revit.DB.XYZ (1.0f, 0f, 0f)); break; case BasedType.Line: PointControlFirst.SetPointData(boundingBox.Min); PointControlSecond.SetPointData(boundingBox.Max); break; default: break; } } /// <summary> /// Create a family instance according the selected options by user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonCreate_Click(object sender, EventArgs e) { bool retBool = false; try { Transaction transaction = new Transaction(m_creator.RevitDoc.Document, "CreateFamilyInstance"); transaction.Start(); switch (m_baseType) { case BasedType.Point: retBool = m_creator.CreatePointFamilyInstance(PointControlFirst.GetPointData() , PointControlSecond.GetPointData() , comboBoxFace.SelectedIndex , comboBoxFamily.SelectedIndex); break; case BasedType.Line: retBool = m_creator.CreateLineFamilyInstance(PointControlFirst.GetPointData() , PointControlSecond.GetPointData() , comboBoxFace.SelectedIndex , comboBoxFamily.SelectedIndex); break; default: break; } transaction.Commit(); } catch(ApplicationException) { MessageBox.Show("Failed in creating family instance, maybe because the family symbol is wrong type, please check and choose again."); return; } catch(Exception ee) { MessageBox.Show(ee.Message); return; } if (retBool) { this.Close(); this.DialogResult = DialogResult.OK; } else { MessageBox.Show("The line is perpendicular to this face, please input the position again."); } } /// <summary> /// Process the SelectedIndexChanged event of comboBoxFace /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void comboBoxFace_SelectedIndexChanged(object sender, EventArgs e) { SetFaceIndex(comboBoxFace.SelectedIndex); } /// <summary> /// Adjust the comboBox dropDownList width /// </summary> /// <param name="senderComboBox">the comboBox</param> private void AdjustComboBoxDropDownListWidth(ComboBox senderComboBox) { Graphics g = null; Font font = null; try { int width = senderComboBox.Width; g = senderComboBox.CreateGraphics(); font = senderComboBox.Font; // checks if a scrollbar will be displayed. // if yes, then get its width to adjust the size of the drop down list. int vertScrollBarWidth = (senderComboBox.Items.Count > senderComboBox.MaxDropDownItems) ? SystemInformation.VerticalScrollBarWidth : 0; int newWidth; foreach (object s in senderComboBox.Items) //Loop through list items and check size of each items. { if (s != null) { newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width + vertScrollBarWidth; if (width < newWidth) { width = newWidth; //set the width of the drop down list to the width of the largest item. } } } senderComboBox.DropDownWidth = width; } catch { } finally { if (g != null) { g.Dispose(); } } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Accounts Payable Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class CRDataSet : EduHubDataSet<CR> { /// <inheritdoc /> public override string Name { get { return "CR"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal CRDataSet(EduHubContext Context) : base(Context) { Index_BSB = new Lazy<NullDictionary<string, IReadOnlyList<CR>>>(() => this.ToGroupedNullDictionary(i => i.BSB)); Index_CRKEY = new Lazy<Dictionary<string, CR>>(() => this.ToDictionary(i => i.CRKEY)); Index_PPDKEY = new Lazy<NullDictionary<string, IReadOnlyList<CR>>>(() => this.ToGroupedNullDictionary(i => i.PPDKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="CR" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="CR" /> fields for each CSV column header</returns> internal override Action<CR, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<CR, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "CRKEY": mapper[i] = (e, v) => e.CRKEY = v; break; case "TITLE": mapper[i] = (e, v) => e.TITLE = v; break; case "ALLOCAMT": mapper[i] = (e, v) => e.ALLOCAMT = v == null ? (decimal?)null : decimal.Parse(v); break; case "MTDPURCH": mapper[i] = (e, v) => e.MTDPURCH = v == null ? (decimal?)null : decimal.Parse(v); break; case "YTDPURCH": mapper[i] = (e, v) => e.YTDPURCH = v == null ? (decimal?)null : decimal.Parse(v); break; case "AGED01": mapper[i] = (e, v) => e.AGED01 = v == null ? (decimal?)null : decimal.Parse(v); break; case "AGED02": mapper[i] = (e, v) => e.AGED02 = v == null ? (decimal?)null : decimal.Parse(v); break; case "AGED03": mapper[i] = (e, v) => e.AGED03 = v == null ? (decimal?)null : decimal.Parse(v); break; case "AGED04": mapper[i] = (e, v) => e.AGED04 = v == null ? (decimal?)null : decimal.Parse(v); break; case "AGED05": mapper[i] = (e, v) => e.AGED05 = v == null ? (decimal?)null : decimal.Parse(v); break; case "OPBAL": mapper[i] = (e, v) => e.OPBAL = v == null ? (decimal?)null : decimal.Parse(v); break; case "CRLIMIT": mapper[i] = (e, v) => e.CRLIMIT = v == null ? (decimal?)null : decimal.Parse(v); break; case "LASTPAYDATE": mapper[i] = (e, v) => e.LASTPAYDATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LASTPAY": mapper[i] = (e, v) => e.LASTPAY = v == null ? (decimal?)null : decimal.Parse(v); break; case "ACCTYPE": mapper[i] = (e, v) => e.ACCTYPE = v == null ? (short?)null : short.Parse(v); break; case "TERMS": mapper[i] = (e, v) => e.TERMS = v == null ? (short?)null : short.Parse(v); break; case "DISCOUNT": mapper[i] = (e, v) => e.DISCOUNT = v == null ? (double?)null : double.Parse(v); break; case "CONTACT": mapper[i] = (e, v) => e.CONTACT = v; break; case "ADDRESS01": mapper[i] = (e, v) => e.ADDRESS01 = v; break; case "ADDRESS02": mapper[i] = (e, v) => e.ADDRESS02 = v; break; case "ADDRESS03": mapper[i] = (e, v) => e.ADDRESS03 = v; break; case "STATE": mapper[i] = (e, v) => e.STATE = v; break; case "POSTCODE": mapper[i] = (e, v) => e.POSTCODE = v; break; case "TELEPHONE": mapper[i] = (e, v) => e.TELEPHONE = v; break; case "FAX": mapper[i] = (e, v) => e.FAX = v; break; case "CR_EMAIL": mapper[i] = (e, v) => e.CR_EMAIL = v; break; case "EMAIL_FOR_PAYMENTS": mapper[i] = (e, v) => e.EMAIL_FOR_PAYMENTS = v; break; case "MOBILE": mapper[i] = (e, v) => e.MOBILE = v; break; case "COMMITMENT": mapper[i] = (e, v) => e.COMMITMENT = v == null ? (decimal?)null : decimal.Parse(v); break; case "STOP_FLAG": mapper[i] = (e, v) => e.STOP_FLAG = v; break; case "ABN": mapper[i] = (e, v) => e.ABN = v; break; case "PAYG_RATE": mapper[i] = (e, v) => e.PAYG_RATE = v == null ? (double?)null : double.Parse(v); break; case "BSB": mapper[i] = (e, v) => e.BSB = v; break; case "ACCOUNT_NO": mapper[i] = (e, v) => e.ACCOUNT_NO = v; break; case "ACCOUNT_NAME": mapper[i] = (e, v) => e.ACCOUNT_NAME = v; break; case "LODGE_REF": mapper[i] = (e, v) => e.LODGE_REF = v; break; case "BILLER_CODE": mapper[i] = (e, v) => e.BILLER_CODE = v; break; case "BPAY_REFERENCE": mapper[i] = (e, v) => e.BPAY_REFERENCE = v; break; case "TRADE_INFO01": mapper[i] = (e, v) => e.TRADE_INFO01 = v; break; case "TRADE_INFO02": mapper[i] = (e, v) => e.TRADE_INFO02 = v; break; case "TRADE_INFO03": mapper[i] = (e, v) => e.TRADE_INFO03 = v; break; case "TRADE_INFO04": mapper[i] = (e, v) => e.TRADE_INFO04 = v; break; case "TRADE_INFO05": mapper[i] = (e, v) => e.TRADE_INFO05 = v; break; case "TRADE_INFO06": mapper[i] = (e, v) => e.TRADE_INFO06 = v; break; case "TRADE_INFO07": mapper[i] = (e, v) => e.TRADE_INFO07 = v; break; case "TRADE_INFO08": mapper[i] = (e, v) => e.TRADE_INFO08 = v; break; case "TRADE_INFO09": mapper[i] = (e, v) => e.TRADE_INFO09 = v; break; case "TRADE_INFO10": mapper[i] = (e, v) => e.TRADE_INFO10 = v; break; case "SURNAME": mapper[i] = (e, v) => e.SURNAME = v; break; case "FIRST_NAME": mapper[i] = (e, v) => e.FIRST_NAME = v; break; case "SECOND_NAME": mapper[i] = (e, v) => e.SECOND_NAME = v; break; case "PAYG_BIRTHDATE": mapper[i] = (e, v) => e.PAYG_BIRTHDATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "PAYG_STARTDATE": mapper[i] = (e, v) => e.PAYG_STARTDATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "PAYG_TERMDATE": mapper[i] = (e, v) => e.PAYG_TERMDATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "PAYG_ADDRESS01": mapper[i] = (e, v) => e.PAYG_ADDRESS01 = v; break; case "PAYG_ADDRESS02": mapper[i] = (e, v) => e.PAYG_ADDRESS02 = v; break; case "PAYG_SUBURB": mapper[i] = (e, v) => e.PAYG_SUBURB = v; break; case "PAYG_STATE": mapper[i] = (e, v) => e.PAYG_STATE = v; break; case "PAYG_POST": mapper[i] = (e, v) => e.PAYG_POST = v; break; case "PAYG_COUNTRY": mapper[i] = (e, v) => e.PAYG_COUNTRY = v; break; case "PPDKEY": mapper[i] = (e, v) => e.PPDKEY = v; break; case "PR_APPROVE": mapper[i] = (e, v) => e.PR_APPROVE = v; break; case "PRMS_FLAG": mapper[i] = (e, v) => e.PRMS_FLAG = v; break; case "LW_PRMSINFO_DATE": mapper[i] = (e, v) => e.LW_PRMSINFO_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "ARN": mapper[i] = (e, v) => e.ARN = v; break; case "KNOTE_FLAG": mapper[i] = (e, v) => e.KNOTE_FLAG = v; break; case "AIMSKEY": mapper[i] = (e, v) => e.AIMSKEY = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="CR" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="CR" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="CR" /> entities</param> /// <returns>A merged <see cref="IEnumerable{CR}"/> of entities</returns> internal override IEnumerable<CR> ApplyDeltaEntities(IEnumerable<CR> Entities, List<CR> DeltaEntities) { HashSet<string> Index_CRKEY = new HashSet<string>(DeltaEntities.Select(i => i.CRKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.CRKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_CRKEY.Remove(entity.CRKEY); if (entity.CRKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<CR>>> Index_BSB; private Lazy<Dictionary<string, CR>> Index_CRKEY; private Lazy<NullDictionary<string, IReadOnlyList<CR>>> Index_PPDKEY; #endregion #region Index Methods /// <summary> /// Find CR by BSB field /// </summary> /// <param name="BSB">BSB value used to find CR</param> /// <returns>List of related CR entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<CR> FindByBSB(string BSB) { return Index_BSB.Value[BSB]; } /// <summary> /// Attempt to find CR by BSB field /// </summary> /// <param name="BSB">BSB value used to find CR</param> /// <param name="Value">List of related CR entities</param> /// <returns>True if the list of related CR entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByBSB(string BSB, out IReadOnlyList<CR> Value) { return Index_BSB.Value.TryGetValue(BSB, out Value); } /// <summary> /// Attempt to find CR by BSB field /// </summary> /// <param name="BSB">BSB value used to find CR</param> /// <returns>List of related CR entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<CR> TryFindByBSB(string BSB) { IReadOnlyList<CR> value; if (Index_BSB.Value.TryGetValue(BSB, out value)) { return value; } else { return null; } } /// <summary> /// Find CR by CRKEY field /// </summary> /// <param name="CRKEY">CRKEY value used to find CR</param> /// <returns>Related CR entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public CR FindByCRKEY(string CRKEY) { return Index_CRKEY.Value[CRKEY]; } /// <summary> /// Attempt to find CR by CRKEY field /// </summary> /// <param name="CRKEY">CRKEY value used to find CR</param> /// <param name="Value">Related CR entity</param> /// <returns>True if the related CR entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCRKEY(string CRKEY, out CR Value) { return Index_CRKEY.Value.TryGetValue(CRKEY, out Value); } /// <summary> /// Attempt to find CR by CRKEY field /// </summary> /// <param name="CRKEY">CRKEY value used to find CR</param> /// <returns>Related CR entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public CR TryFindByCRKEY(string CRKEY) { CR value; if (Index_CRKEY.Value.TryGetValue(CRKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find CR by PPDKEY field /// </summary> /// <param name="PPDKEY">PPDKEY value used to find CR</param> /// <returns>List of related CR entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<CR> FindByPPDKEY(string PPDKEY) { return Index_PPDKEY.Value[PPDKEY]; } /// <summary> /// Attempt to find CR by PPDKEY field /// </summary> /// <param name="PPDKEY">PPDKEY value used to find CR</param> /// <param name="Value">List of related CR entities</param> /// <returns>True if the list of related CR entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByPPDKEY(string PPDKEY, out IReadOnlyList<CR> Value) { return Index_PPDKEY.Value.TryGetValue(PPDKEY, out Value); } /// <summary> /// Attempt to find CR by PPDKEY field /// </summary> /// <param name="PPDKEY">PPDKEY value used to find CR</param> /// <returns>List of related CR entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<CR> TryFindByPPDKEY(string PPDKEY) { IReadOnlyList<CR> value; if (Index_PPDKEY.Value.TryGetValue(PPDKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a CR table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CR]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[CR]( [CRKEY] varchar(10) NOT NULL, [TITLE] varchar(40) NULL, [ALLOCAMT] money NULL, [MTDPURCH] money NULL, [YTDPURCH] money NULL, [AGED01] money NULL, [AGED02] money NULL, [AGED03] money NULL, [AGED04] money NULL, [AGED05] money NULL, [OPBAL] money NULL, [CRLIMIT] money NULL, [LASTPAYDATE] datetime NULL, [LASTPAY] money NULL, [ACCTYPE] smallint NULL, [TERMS] smallint NULL, [DISCOUNT] float NULL, [CONTACT] varchar(30) NULL, [ADDRESS01] varchar(40) NULL, [ADDRESS02] varchar(40) NULL, [ADDRESS03] varchar(40) NULL, [STATE] varchar(4) NULL, [POSTCODE] varchar(4) NULL, [TELEPHONE] varchar(20) NULL, [FAX] varchar(20) NULL, [CR_EMAIL] varchar(60) NULL, [EMAIL_FOR_PAYMENTS] varchar(60) NULL, [MOBILE] varchar(20) NULL, [COMMITMENT] money NULL, [STOP_FLAG] varchar(1) NULL, [ABN] varchar(15) NULL, [PAYG_RATE] float NULL, [BSB] varchar(6) NULL, [ACCOUNT_NO] varchar(15) NULL, [ACCOUNT_NAME] varchar(60) NULL, [LODGE_REF] varchar(18) NULL, [BILLER_CODE] varchar(10) NULL, [BPAY_REFERENCE] varchar(20) NULL, [TRADE_INFO01] varchar(50) NULL, [TRADE_INFO02] varchar(50) NULL, [TRADE_INFO03] varchar(50) NULL, [TRADE_INFO04] varchar(50) NULL, [TRADE_INFO05] varchar(50) NULL, [TRADE_INFO06] varchar(50) NULL, [TRADE_INFO07] varchar(50) NULL, [TRADE_INFO08] varchar(50) NULL, [TRADE_INFO09] varchar(50) NULL, [TRADE_INFO10] varchar(50) NULL, [SURNAME] varchar(30) NULL, [FIRST_NAME] varchar(15) NULL, [SECOND_NAME] varchar(15) NULL, [PAYG_BIRTHDATE] datetime NULL, [PAYG_STARTDATE] datetime NULL, [PAYG_TERMDATE] datetime NULL, [PAYG_ADDRESS01] varchar(38) NULL, [PAYG_ADDRESS02] varchar(38) NULL, [PAYG_SUBURB] varchar(20) NULL, [PAYG_STATE] varchar(3) NULL, [PAYG_POST] varchar(4) NULL, [PAYG_COUNTRY] varchar(20) NULL, [PPDKEY] varchar(10) NULL, [PR_APPROVE] varchar(1) NULL, [PRMS_FLAG] varchar(1) NULL, [LW_PRMSINFO_DATE] datetime NULL, [ARN] varchar(15) NULL, [KNOTE_FLAG] varchar(1) NULL, [AIMSKEY] varchar(20) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [CR_Index_CRKEY] PRIMARY KEY CLUSTERED ( [CRKEY] ASC ) ); CREATE NONCLUSTERED INDEX [CR_Index_BSB] ON [dbo].[CR] ( [BSB] ASC ); CREATE NONCLUSTERED INDEX [CR_Index_PPDKEY] ON [dbo].[CR] ( [PPDKEY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CR]') AND name = N'CR_Index_BSB') ALTER INDEX [CR_Index_BSB] ON [dbo].[CR] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CR]') AND name = N'CR_Index_PPDKEY') ALTER INDEX [CR_Index_PPDKEY] ON [dbo].[CR] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CR]') AND name = N'CR_Index_BSB') ALTER INDEX [CR_Index_BSB] ON [dbo].[CR] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CR]') AND name = N'CR_Index_PPDKEY') ALTER INDEX [CR_Index_PPDKEY] ON [dbo].[CR] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="CR"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="CR"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<CR> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_CRKEY = new List<string>(); foreach (var entity in Entities) { Index_CRKEY.Add(entity.CRKEY); } builder.AppendLine("DELETE [dbo].[CR] WHERE"); // Index_CRKEY builder.Append("[CRKEY] IN ("); for (int index = 0; index < Index_CRKEY.Count; index++) { if (index != 0) builder.Append(", "); // CRKEY var parameterCRKEY = $"@p{parameterIndex++}"; builder.Append(parameterCRKEY); command.Parameters.Add(parameterCRKEY, SqlDbType.VarChar, 10).Value = Index_CRKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the CR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the CR data set</returns> public override EduHubDataSetDataReader<CR> GetDataSetDataReader() { return new CRDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the CR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the CR data set</returns> public override EduHubDataSetDataReader<CR> GetDataSetDataReader(List<CR> Entities) { return new CRDataReader(new EduHubDataSetLoadedReader<CR>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class CRDataReader : EduHubDataSetDataReader<CR> { public CRDataReader(IEduHubDataSetReader<CR> Reader) : base (Reader) { } public override int FieldCount { get { return 70; } } public override object GetValue(int i) { switch (i) { case 0: // CRKEY return Current.CRKEY; case 1: // TITLE return Current.TITLE; case 2: // ALLOCAMT return Current.ALLOCAMT; case 3: // MTDPURCH return Current.MTDPURCH; case 4: // YTDPURCH return Current.YTDPURCH; case 5: // AGED01 return Current.AGED01; case 6: // AGED02 return Current.AGED02; case 7: // AGED03 return Current.AGED03; case 8: // AGED04 return Current.AGED04; case 9: // AGED05 return Current.AGED05; case 10: // OPBAL return Current.OPBAL; case 11: // CRLIMIT return Current.CRLIMIT; case 12: // LASTPAYDATE return Current.LASTPAYDATE; case 13: // LASTPAY return Current.LASTPAY; case 14: // ACCTYPE return Current.ACCTYPE; case 15: // TERMS return Current.TERMS; case 16: // DISCOUNT return Current.DISCOUNT; case 17: // CONTACT return Current.CONTACT; case 18: // ADDRESS01 return Current.ADDRESS01; case 19: // ADDRESS02 return Current.ADDRESS02; case 20: // ADDRESS03 return Current.ADDRESS03; case 21: // STATE return Current.STATE; case 22: // POSTCODE return Current.POSTCODE; case 23: // TELEPHONE return Current.TELEPHONE; case 24: // FAX return Current.FAX; case 25: // CR_EMAIL return Current.CR_EMAIL; case 26: // EMAIL_FOR_PAYMENTS return Current.EMAIL_FOR_PAYMENTS; case 27: // MOBILE return Current.MOBILE; case 28: // COMMITMENT return Current.COMMITMENT; case 29: // STOP_FLAG return Current.STOP_FLAG; case 30: // ABN return Current.ABN; case 31: // PAYG_RATE return Current.PAYG_RATE; case 32: // BSB return Current.BSB; case 33: // ACCOUNT_NO return Current.ACCOUNT_NO; case 34: // ACCOUNT_NAME return Current.ACCOUNT_NAME; case 35: // LODGE_REF return Current.LODGE_REF; case 36: // BILLER_CODE return Current.BILLER_CODE; case 37: // BPAY_REFERENCE return Current.BPAY_REFERENCE; case 38: // TRADE_INFO01 return Current.TRADE_INFO01; case 39: // TRADE_INFO02 return Current.TRADE_INFO02; case 40: // TRADE_INFO03 return Current.TRADE_INFO03; case 41: // TRADE_INFO04 return Current.TRADE_INFO04; case 42: // TRADE_INFO05 return Current.TRADE_INFO05; case 43: // TRADE_INFO06 return Current.TRADE_INFO06; case 44: // TRADE_INFO07 return Current.TRADE_INFO07; case 45: // TRADE_INFO08 return Current.TRADE_INFO08; case 46: // TRADE_INFO09 return Current.TRADE_INFO09; case 47: // TRADE_INFO10 return Current.TRADE_INFO10; case 48: // SURNAME return Current.SURNAME; case 49: // FIRST_NAME return Current.FIRST_NAME; case 50: // SECOND_NAME return Current.SECOND_NAME; case 51: // PAYG_BIRTHDATE return Current.PAYG_BIRTHDATE; case 52: // PAYG_STARTDATE return Current.PAYG_STARTDATE; case 53: // PAYG_TERMDATE return Current.PAYG_TERMDATE; case 54: // PAYG_ADDRESS01 return Current.PAYG_ADDRESS01; case 55: // PAYG_ADDRESS02 return Current.PAYG_ADDRESS02; case 56: // PAYG_SUBURB return Current.PAYG_SUBURB; case 57: // PAYG_STATE return Current.PAYG_STATE; case 58: // PAYG_POST return Current.PAYG_POST; case 59: // PAYG_COUNTRY return Current.PAYG_COUNTRY; case 60: // PPDKEY return Current.PPDKEY; case 61: // PR_APPROVE return Current.PR_APPROVE; case 62: // PRMS_FLAG return Current.PRMS_FLAG; case 63: // LW_PRMSINFO_DATE return Current.LW_PRMSINFO_DATE; case 64: // ARN return Current.ARN; case 65: // KNOTE_FLAG return Current.KNOTE_FLAG; case 66: // AIMSKEY return Current.AIMSKEY; case 67: // LW_DATE return Current.LW_DATE; case 68: // LW_TIME return Current.LW_TIME; case 69: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // TITLE return Current.TITLE == null; case 2: // ALLOCAMT return Current.ALLOCAMT == null; case 3: // MTDPURCH return Current.MTDPURCH == null; case 4: // YTDPURCH return Current.YTDPURCH == null; case 5: // AGED01 return Current.AGED01 == null; case 6: // AGED02 return Current.AGED02 == null; case 7: // AGED03 return Current.AGED03 == null; case 8: // AGED04 return Current.AGED04 == null; case 9: // AGED05 return Current.AGED05 == null; case 10: // OPBAL return Current.OPBAL == null; case 11: // CRLIMIT return Current.CRLIMIT == null; case 12: // LASTPAYDATE return Current.LASTPAYDATE == null; case 13: // LASTPAY return Current.LASTPAY == null; case 14: // ACCTYPE return Current.ACCTYPE == null; case 15: // TERMS return Current.TERMS == null; case 16: // DISCOUNT return Current.DISCOUNT == null; case 17: // CONTACT return Current.CONTACT == null; case 18: // ADDRESS01 return Current.ADDRESS01 == null; case 19: // ADDRESS02 return Current.ADDRESS02 == null; case 20: // ADDRESS03 return Current.ADDRESS03 == null; case 21: // STATE return Current.STATE == null; case 22: // POSTCODE return Current.POSTCODE == null; case 23: // TELEPHONE return Current.TELEPHONE == null; case 24: // FAX return Current.FAX == null; case 25: // CR_EMAIL return Current.CR_EMAIL == null; case 26: // EMAIL_FOR_PAYMENTS return Current.EMAIL_FOR_PAYMENTS == null; case 27: // MOBILE return Current.MOBILE == null; case 28: // COMMITMENT return Current.COMMITMENT == null; case 29: // STOP_FLAG return Current.STOP_FLAG == null; case 30: // ABN return Current.ABN == null; case 31: // PAYG_RATE return Current.PAYG_RATE == null; case 32: // BSB return Current.BSB == null; case 33: // ACCOUNT_NO return Current.ACCOUNT_NO == null; case 34: // ACCOUNT_NAME return Current.ACCOUNT_NAME == null; case 35: // LODGE_REF return Current.LODGE_REF == null; case 36: // BILLER_CODE return Current.BILLER_CODE == null; case 37: // BPAY_REFERENCE return Current.BPAY_REFERENCE == null; case 38: // TRADE_INFO01 return Current.TRADE_INFO01 == null; case 39: // TRADE_INFO02 return Current.TRADE_INFO02 == null; case 40: // TRADE_INFO03 return Current.TRADE_INFO03 == null; case 41: // TRADE_INFO04 return Current.TRADE_INFO04 == null; case 42: // TRADE_INFO05 return Current.TRADE_INFO05 == null; case 43: // TRADE_INFO06 return Current.TRADE_INFO06 == null; case 44: // TRADE_INFO07 return Current.TRADE_INFO07 == null; case 45: // TRADE_INFO08 return Current.TRADE_INFO08 == null; case 46: // TRADE_INFO09 return Current.TRADE_INFO09 == null; case 47: // TRADE_INFO10 return Current.TRADE_INFO10 == null; case 48: // SURNAME return Current.SURNAME == null; case 49: // FIRST_NAME return Current.FIRST_NAME == null; case 50: // SECOND_NAME return Current.SECOND_NAME == null; case 51: // PAYG_BIRTHDATE return Current.PAYG_BIRTHDATE == null; case 52: // PAYG_STARTDATE return Current.PAYG_STARTDATE == null; case 53: // PAYG_TERMDATE return Current.PAYG_TERMDATE == null; case 54: // PAYG_ADDRESS01 return Current.PAYG_ADDRESS01 == null; case 55: // PAYG_ADDRESS02 return Current.PAYG_ADDRESS02 == null; case 56: // PAYG_SUBURB return Current.PAYG_SUBURB == null; case 57: // PAYG_STATE return Current.PAYG_STATE == null; case 58: // PAYG_POST return Current.PAYG_POST == null; case 59: // PAYG_COUNTRY return Current.PAYG_COUNTRY == null; case 60: // PPDKEY return Current.PPDKEY == null; case 61: // PR_APPROVE return Current.PR_APPROVE == null; case 62: // PRMS_FLAG return Current.PRMS_FLAG == null; case 63: // LW_PRMSINFO_DATE return Current.LW_PRMSINFO_DATE == null; case 64: // ARN return Current.ARN == null; case 65: // KNOTE_FLAG return Current.KNOTE_FLAG == null; case 66: // AIMSKEY return Current.AIMSKEY == null; case 67: // LW_DATE return Current.LW_DATE == null; case 68: // LW_TIME return Current.LW_TIME == null; case 69: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // CRKEY return "CRKEY"; case 1: // TITLE return "TITLE"; case 2: // ALLOCAMT return "ALLOCAMT"; case 3: // MTDPURCH return "MTDPURCH"; case 4: // YTDPURCH return "YTDPURCH"; case 5: // AGED01 return "AGED01"; case 6: // AGED02 return "AGED02"; case 7: // AGED03 return "AGED03"; case 8: // AGED04 return "AGED04"; case 9: // AGED05 return "AGED05"; case 10: // OPBAL return "OPBAL"; case 11: // CRLIMIT return "CRLIMIT"; case 12: // LASTPAYDATE return "LASTPAYDATE"; case 13: // LASTPAY return "LASTPAY"; case 14: // ACCTYPE return "ACCTYPE"; case 15: // TERMS return "TERMS"; case 16: // DISCOUNT return "DISCOUNT"; case 17: // CONTACT return "CONTACT"; case 18: // ADDRESS01 return "ADDRESS01"; case 19: // ADDRESS02 return "ADDRESS02"; case 20: // ADDRESS03 return "ADDRESS03"; case 21: // STATE return "STATE"; case 22: // POSTCODE return "POSTCODE"; case 23: // TELEPHONE return "TELEPHONE"; case 24: // FAX return "FAX"; case 25: // CR_EMAIL return "CR_EMAIL"; case 26: // EMAIL_FOR_PAYMENTS return "EMAIL_FOR_PAYMENTS"; case 27: // MOBILE return "MOBILE"; case 28: // COMMITMENT return "COMMITMENT"; case 29: // STOP_FLAG return "STOP_FLAG"; case 30: // ABN return "ABN"; case 31: // PAYG_RATE return "PAYG_RATE"; case 32: // BSB return "BSB"; case 33: // ACCOUNT_NO return "ACCOUNT_NO"; case 34: // ACCOUNT_NAME return "ACCOUNT_NAME"; case 35: // LODGE_REF return "LODGE_REF"; case 36: // BILLER_CODE return "BILLER_CODE"; case 37: // BPAY_REFERENCE return "BPAY_REFERENCE"; case 38: // TRADE_INFO01 return "TRADE_INFO01"; case 39: // TRADE_INFO02 return "TRADE_INFO02"; case 40: // TRADE_INFO03 return "TRADE_INFO03"; case 41: // TRADE_INFO04 return "TRADE_INFO04"; case 42: // TRADE_INFO05 return "TRADE_INFO05"; case 43: // TRADE_INFO06 return "TRADE_INFO06"; case 44: // TRADE_INFO07 return "TRADE_INFO07"; case 45: // TRADE_INFO08 return "TRADE_INFO08"; case 46: // TRADE_INFO09 return "TRADE_INFO09"; case 47: // TRADE_INFO10 return "TRADE_INFO10"; case 48: // SURNAME return "SURNAME"; case 49: // FIRST_NAME return "FIRST_NAME"; case 50: // SECOND_NAME return "SECOND_NAME"; case 51: // PAYG_BIRTHDATE return "PAYG_BIRTHDATE"; case 52: // PAYG_STARTDATE return "PAYG_STARTDATE"; case 53: // PAYG_TERMDATE return "PAYG_TERMDATE"; case 54: // PAYG_ADDRESS01 return "PAYG_ADDRESS01"; case 55: // PAYG_ADDRESS02 return "PAYG_ADDRESS02"; case 56: // PAYG_SUBURB return "PAYG_SUBURB"; case 57: // PAYG_STATE return "PAYG_STATE"; case 58: // PAYG_POST return "PAYG_POST"; case 59: // PAYG_COUNTRY return "PAYG_COUNTRY"; case 60: // PPDKEY return "PPDKEY"; case 61: // PR_APPROVE return "PR_APPROVE"; case 62: // PRMS_FLAG return "PRMS_FLAG"; case 63: // LW_PRMSINFO_DATE return "LW_PRMSINFO_DATE"; case 64: // ARN return "ARN"; case 65: // KNOTE_FLAG return "KNOTE_FLAG"; case 66: // AIMSKEY return "AIMSKEY"; case 67: // LW_DATE return "LW_DATE"; case 68: // LW_TIME return "LW_TIME"; case 69: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "CRKEY": return 0; case "TITLE": return 1; case "ALLOCAMT": return 2; case "MTDPURCH": return 3; case "YTDPURCH": return 4; case "AGED01": return 5; case "AGED02": return 6; case "AGED03": return 7; case "AGED04": return 8; case "AGED05": return 9; case "OPBAL": return 10; case "CRLIMIT": return 11; case "LASTPAYDATE": return 12; case "LASTPAY": return 13; case "ACCTYPE": return 14; case "TERMS": return 15; case "DISCOUNT": return 16; case "CONTACT": return 17; case "ADDRESS01": return 18; case "ADDRESS02": return 19; case "ADDRESS03": return 20; case "STATE": return 21; case "POSTCODE": return 22; case "TELEPHONE": return 23; case "FAX": return 24; case "CR_EMAIL": return 25; case "EMAIL_FOR_PAYMENTS": return 26; case "MOBILE": return 27; case "COMMITMENT": return 28; case "STOP_FLAG": return 29; case "ABN": return 30; case "PAYG_RATE": return 31; case "BSB": return 32; case "ACCOUNT_NO": return 33; case "ACCOUNT_NAME": return 34; case "LODGE_REF": return 35; case "BILLER_CODE": return 36; case "BPAY_REFERENCE": return 37; case "TRADE_INFO01": return 38; case "TRADE_INFO02": return 39; case "TRADE_INFO03": return 40; case "TRADE_INFO04": return 41; case "TRADE_INFO05": return 42; case "TRADE_INFO06": return 43; case "TRADE_INFO07": return 44; case "TRADE_INFO08": return 45; case "TRADE_INFO09": return 46; case "TRADE_INFO10": return 47; case "SURNAME": return 48; case "FIRST_NAME": return 49; case "SECOND_NAME": return 50; case "PAYG_BIRTHDATE": return 51; case "PAYG_STARTDATE": return 52; case "PAYG_TERMDATE": return 53; case "PAYG_ADDRESS01": return 54; case "PAYG_ADDRESS02": return 55; case "PAYG_SUBURB": return 56; case "PAYG_STATE": return 57; case "PAYG_POST": return 58; case "PAYG_COUNTRY": return 59; case "PPDKEY": return 60; case "PR_APPROVE": return 61; case "PRMS_FLAG": return 62; case "LW_PRMSINFO_DATE": return 63; case "ARN": return 64; case "KNOTE_FLAG": return 65; case "AIMSKEY": return 66; case "LW_DATE": return 67; case "LW_TIME": return 68; case "LW_USER": return 69; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using System.Xml.Serialization; using log4net; using Nwc.XmlRpc; using ProtoBuf; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Clients; using OpenSim.Framework.Communications.Messages; namespace OpenSim.Region.Communications.OGS1 { public class OGS1UserDataPlugin : IUserDataPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected CommunicationsManager m_commsManager; //private UserDataBase m_userDb; public OGS1UserDataPlugin(CommunicationsManager commsManager, ConfigSettings settings) { m_log.DebugFormat("[OGS1 USER SERVICES]: {0} initialized", Name); m_commsManager = commsManager; //we short circuit some OGS calls to the user server due to numerous problems with user //profile data causing issues with data transfer via XML //TODO: This sucks, all of this should be stripped out to remove the reliance on the //user server. There is no reason to have yet another point of failure between the sim //and the database //m_userDb = } public string Version { get { return "0.1"; } } public string Name { get { return "Open Grid Services 1 (OGS1) User Data Plugin"; } } public void Initialize() {} public void Initialize(string connect) {} public void Dispose() {} // Arguably the presence of these means that IUserDataPlugin could be fissioned public UserAgentData GetUserAgent(string name) { return null; } public UserAgentData GetAgentByName(string name) { return null; } public UserAgentData GetAgentByName(string fname, string lname) { return null; } public void StoreWebLoginKey(UUID agentID, UUID webLoginKey) {} public void AddNewUserProfile(UserProfileData user) {} public void AddNewUserAgent(UserAgentData agent) {} public bool MoneyTransferRequest(UUID from, UUID to, uint amount) { return false; } public bool InventoryTransferRequest(UUID from, UUID to, UUID inventory) { return false; } public void ResetAttachments(UUID userID) {} public void LogoutUsers(UUID regionID) {} public UserProfileData GetUserByUri(Uri uri) { WebRequest request = WebRequest.Create(uri); WebResponse webResponse = request.GetResponse(); XmlSerializer deserializer = new XmlSerializer(typeof(XmlRpcResponse)); XmlRpcResponse xmlRpcResponse = (XmlRpcResponse)deserializer.Deserialize(webResponse.GetResponseStream()); Hashtable respData = (Hashtable)xmlRpcResponse.Value; return ConvertXMLRPCDataToUserProfile(respData); } public virtual UserAgentData GetAgentByUUID(UUID userId) { try { Hashtable param = new Hashtable(); param["avatar_uuid"] = userId.ToString(); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "get_agent_by_uuid"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(GetUserServerURL(userId), methodName), 6000); Hashtable respData = (Hashtable)resp.Value; if (respData.Contains("error_type")) { //m_log.Warn("[GRID]: " + // "Error sent by user server when trying to get agent: (" + // (string) respData["error_type"] + // "): " + (string)respData["error_desc"]); return null; } UUID sessionid = UUID.Zero; UserAgentData userAgent = new UserAgentData(); userAgent.Handle = Convert.ToUInt64((string)respData["handle"]); UUID.TryParse((string)respData["sessionid"], out sessionid); userAgent.SessionID = sessionid; if ((string)respData["agent_online"] == "TRUE") { userAgent.AgentOnline = true; } else { userAgent.AgentOnline = false; } return userAgent; } catch (Exception e) { m_log.ErrorFormat( "[OGS1 USER SERVICES]: Error when trying to fetch agent data by uuid from remote user server: {0}", e); } return null; } public virtual UserProfileData GetUserByName(string firstName, string lastName) { return GetUserProfile(firstName + " " + lastName); } public virtual List<AvatarPickerAvatar> GeneratePickerResults(UUID queryID, string query) { List<AvatarPickerAvatar> pickerlist = new List<AvatarPickerAvatar>(); Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9 ]"); try { Hashtable param = new Hashtable(); param["queryid"] = (string)queryID.ToString(); param["avquery"] = objAlphaNumericPattern.Replace(query, String.Empty); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "get_avatar_picker_avatar"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_commsManager.NetworkServersInfo.UserURL, methodName), 3000); Hashtable respData = (Hashtable)resp.Value; pickerlist = ConvertXMLRPCDataToAvatarPickerList(queryID, respData); } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to fetch Avatar Picker Response: " + e.Message); // Return Empty picker list (no results) } return pickerlist; } /// <summary> /// Get a user profile from the user server /// </summary> /// <param name="avatarID"></param> /// <returns>null if the request fails</returns> protected virtual UserProfileData GetUserProfile(string name) { try { Hashtable param = new Hashtable(); param["avatar_name"] = name; IList parameters = new ArrayList(); parameters.Add(param); string methodName = "get_user_by_name"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_commsManager.NetworkServersInfo.UserURL, methodName), 45000); Hashtable respData = (Hashtable)resp.Value; return ConvertXMLRPCDataToUserProfile(respData); } catch (WebException e) { m_log.ErrorFormat( "[OGS1 USER SERVICES]: Error when trying to fetch profile data by name from remote user server: {0}", e); } return null; } /// <summary> /// Get a user profile from the user server /// </summary> /// <param name="avatarID"></param> /// <returns>null if the request fails</returns> public virtual UserProfileData GetUserByUUID(UUID avatarID) { try { Hashtable param = new Hashtable(); param["avatar_uuid"] = avatarID.ToString(); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "get_user_by_uuid"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_commsManager.NetworkServersInfo.UserURL, methodName), 45000); Hashtable respData = (Hashtable)resp.Value; return ConvertXMLRPCDataToUserProfile(respData); } catch (Exception e) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(); m_log.ErrorFormat( "[OGS1 USER SERVICES]: Error when trying to fetch profile data by uuid from remote user server: {0} {1}", e.Message, trace); } return null; } public virtual bool UpdateUserProfile(UserProfileData userProfile) { m_log.Debug("[OGS1 USER SERVICES]: Asking UserServer to update profile."); Hashtable param = new Hashtable(); param["avatar_uuid"] = userProfile.ID.ToString(); //param["AllowPublish"] = userProfile.ToString(); param["FLImageID"] = userProfile.FirstLifeImage.ToString(); param["ImageID"] = userProfile.Image.ToString(); //param["MaturePublish"] = MaturePublish.ToString(); param["AboutText"] = userProfile.AboutText; param["FLAboutText"] = userProfile.FirstLifeAboutText; param["webLoginKey"] = userProfile.WebLoginKey.ToString(); param["home_region"] = userProfile.HomeRegion.ToString(); param["home_region_id"] = userProfile.HomeRegionID.ToString(); param["home_pos_x"] = userProfile.HomeLocationX.ToString(); param["home_pos_y"] = userProfile.HomeLocationY.ToString(); param["home_pos_z"] = userProfile.HomeLocationZ.ToString(); param["home_look_x"] = userProfile.HomeLookAtX.ToString(); param["home_look_y"] = userProfile.HomeLookAtY.ToString(); param["home_look_z"] = userProfile.HomeLookAtZ.ToString(); param["user_flags"] = userProfile.UserFlags.ToString(); param["god_level"] = userProfile.GodLevel.ToString(); param["custom_type"] = userProfile.CustomType.ToString(); param["partner"] = userProfile.Partner.ToString(); param["profileURL"] = userProfile.ProfileURL; IList parameters = new ArrayList(); parameters.Add(param); string methodName = "update_user_profile"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(GetUserServerURL(userProfile.ID), methodName), 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if (((string)respData["returnString"]).ToUpper() != "TRUE") { m_log.Warn("[GRID]: Unable to update user profile, User Server Reported an issue"); return false; } } else { m_log.Warn("[GRID]: Unable to update user profile, UserServer didn't understand me!"); return false; } } else { m_log.Warn("[GRID]: Unable to update user profile, UserServer didn't understand me!"); return false; } return true; } /// <summary> /// Adds a new friend to the database for XUser /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being added to</param> /// <param name="friend">The agent that being added to the friends list of the friends list owner</param> /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param> public virtual void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) { try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); param["friendID"] = friend.Guid.ToString(); param["friendPerms"] = perms.ToString(); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "add_new_user_friend"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_commsManager.NetworkServersInfo.UserURL, methodName), 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to add new friend, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to add new friend, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to add new friend, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[GRID]: Error when trying to AddNewUserFriend: " + e.Message); } } /// <summary> /// Delete friend on friendlistowner's friendlist. /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being updated</param> /// <param name="friend">The Ex-friend agent</param> public virtual void RemoveUserFriend(UUID friendlistowner, UUID friend) { try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); param["friendID"] = friend.Guid.ToString(); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "remove_user_friend"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_commsManager.NetworkServersInfo.UserURL,methodName), 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to remove friend, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to remove friend, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to remove friend, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[GRID]: Error when trying to RemoveUserFriend: " + e.Message); } } /// <summary> /// Update permissions for friend on friendlistowner's friendlist. /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being updated</param> /// <param name="friend">The agent that is getting or loosing permissions</param> /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param> public virtual void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) { try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); param["friendID"] = friend.Guid.ToString(); param["friendPerms"] = perms.ToString(); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "update_user_friend_perms"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_commsManager.NetworkServersInfo.UserURL, methodName), 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to update_user_friend_perms, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to update_user_friend_perms, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to update_user_friend_perms, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[GRID]: Error when trying to update_user_friend_perms: " + e.Message); } } /// <summary> /// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner /// </summary> /// <param name="friendlistowner">The agent that we're retreiving the friends Data.</param> private List<FriendListItem> GetUserFriendListOld(UUID friendlistowner) { m_log.Warn("[FRIEND]: Calling OGS1/GetUserFriendListOld for " + friendlistowner.ToString()); List<FriendListItem> buddylist = new List<FriendListItem>(); try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "get_user_friend_list"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_commsManager.NetworkServersInfo.UserURL, methodName), 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null && respData.Contains("avcount")) { buddylist = ConvertXMLRPCDataToFriendListItemList(respData); } } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to fetch Avatar's friends list: " + e.Message); // Return Empty list (no friends) } return buddylist; } /// <summary> /// The response that will be returned from a command /// </summary> public enum GetUserFriendListResult { OK = 0, ERROR = 1, UNAUTHORIZED = 2, INVALID = 3, // NOTIMPLEMENTED means no such URL/operation (older servers return this when new commands are added) NOTIMPLEMENTED = 4 } /// <summary> /// Returns a list of FriendsListItems that describe the friends and permissions in the friend /// relationship for UUID friendslistowner. /// </summary> /// <param name="friendlistowner">The agent that we're retreiving the friends Data for.</param> private GetUserFriendListResult GetUserFriendList2(UUID friendlistowner, out List<FriendListItem> results) { Util.SlowTimeReporter slowCheck = new Util.SlowTimeReporter("[FRIEND]: GetUserFriendList2 for "+friendlistowner.ToString()+" took"); try { List<FriendListItem> EMPTY_RESULTS = new List<FriendListItem>(); string uri = m_commsManager.NetworkServersInfo.UserURL + "/get_user_friend_list2/"; HttpWebRequest friendListRequest = (HttpWebRequest)WebRequest.Create(uri); friendListRequest.Method = "POST"; friendListRequest.ContentType = "application/octet-stream"; friendListRequest.Timeout = FriendsListRequest.TIMEOUT; // Default results are empty results = EMPTY_RESULTS; // m_log.WarnFormat("[FRIEND]: Msg/GetUserFriendList2({0}) using URI '{1}'", friendlistowner, uri); FriendsListRequest request = FriendsListRequest.FromUUID(friendlistowner); try { // send the Post Stream os = friendListRequest.GetRequestStream(); ProtoBuf.Serializer.Serialize(os, request); os.Flush(); os.Close(); // m_log.InfoFormat("[FRIEND]: Posted GetUserFriendList2 request remotely {0}", uri); } catch (Exception e) { m_log.WarnFormat("[FRIEND]: GetUserFriendList2 call failed {0}", e); return GetUserFriendListResult.ERROR; } // Let's wait for the response try { HttpWebResponse webResponse = (HttpWebResponse)friendListRequest.GetResponse(); if (webResponse == null) { m_log.Error("[FRIEND]: Null reply on GetUserFriendList2 put"); return GetUserFriendListResult.ERROR; } //this will happen during the initial rollout and tells us we need to fall back to the old method if (webResponse.StatusCode == HttpStatusCode.NotFound) { m_log.WarnFormat("[FRIEND]: NotFound on reply of GetUserFriendList2"); return GetUserFriendListResult.NOTIMPLEMENTED; } if (webResponse.StatusCode != HttpStatusCode.OK) { m_log.ErrorFormat("[FRIEND]: Error on reply of GetUserFriendList2 {0}", friendlistowner); return GetUserFriendListResult.ERROR; } // Request/response succeeded. results = FriendsListResponse.DeserializeFromStream(webResponse.GetResponseStream()); // m_log.InfoFormat("[FRIEND]: Returning {0} friends for {1}", results.Count, friendlistowner); return GetUserFriendListResult.OK; } catch (WebException ex) { HttpWebResponse webResponse = ex.Response as HttpWebResponse; if (webResponse != null) { //this will happen during the initial rollout and tells us we need to fall back to the //old method if (webResponse.StatusCode == HttpStatusCode.NotFound) { m_log.InfoFormat("[FRIEND]: NotFound exception on reply of GetUserFriendList2"); return GetUserFriendListResult.NOTIMPLEMENTED; } } m_log.ErrorFormat("[FRIEND]: exception on reply of GetUserFriendList2 for {0}", request.FriendListOwner); } return GetUserFriendListResult.ERROR; } finally { slowCheck.Complete(); } } public List<FriendListItem> GetUserFriendList(UUID friendlistowner) { List<FriendListItem> results; GetUserFriendListResult rc = GetUserFriendList2(friendlistowner, out results); if (rc == GetUserFriendListResult.NOTIMPLEMENTED) results = GetUserFriendListOld(friendlistowner); return results; } public virtual Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids) { Dictionary<UUID, FriendRegionInfo> result = new Dictionary<UUID, FriendRegionInfo>(); // ask MessageServer about the current on-/offline status and regions the friends are in ArrayList parameters = new ArrayList(); Hashtable map = new Hashtable(); ArrayList list = new ArrayList(); foreach (UUID uuid in uuids) { list.Add(uuid.ToString()); list.Add(uuid.ToString()); } map["uuids"] = list; map["recv_key"] = m_commsManager.NetworkServersInfo.UserRecvKey; map["send_key"] = m_commsManager.NetworkServersInfo.UserSendKey; parameters.Add(map); try { string methodName = "get_presence_info_bulk"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_commsManager.NetworkServersInfo.MessagingURL, methodName), 8000); Hashtable respData = resp != null ? (Hashtable)resp.Value : null; if (respData == null || respData.ContainsKey("faultMessage")) { m_log.WarnFormat("[OGS1 USER SERVICES]: Contacting MessagingServer about user-regions resulted in error: {0}", respData == null ? "<unknown error>" : respData["faultMessage"]); } else if (!respData.ContainsKey("count")) { m_log.WarnFormat("[OGS1 USER SERVICES]: Wrong format in response for MessagingServer request get_presence_info_bulk: missing 'count' field"); } else { int count = (int)respData["count"]; m_log.DebugFormat("[OGS1 USER SERVICES]: Request returned {0} results.", count); for (int i = 0; i < count; ++i) { if (respData.ContainsKey("uuid_" + i) && respData.ContainsKey("isOnline_" + i) && respData.ContainsKey("regionHandle_" + i)) { UUID uuid; if (UUID.TryParse((string)respData["uuid_" + i], out uuid)) { FriendRegionInfo info = new FriendRegionInfo(); info.isOnline = (bool)respData["isOnline_" + i]; if (info.isOnline) { // TODO remove this after the next protocol update (say, r7800?) info.regionHandle = Convert.ToUInt64(respData["regionHandle_" + i]); // accept missing id if (respData.ContainsKey("regionID_" + i)) UUID.TryParse((string)respData["regionID_" + i], out info.regionID); } result.Add(uuid, info); } } else { m_log.WarnFormat("[OGS1 USER SERVICES]: Response to get_presence_info_bulk contained an error in entry {0}", i); } } } } catch (WebException e) { m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch friend infos: {0}", e.Message); } m_log.DebugFormat("[OGS1 USER SERVICES]: Returning {0} entries", result.Count); return result; } public virtual AvatarAppearance GetUserAppearance(UUID user) { AvatarAppearance appearance = null; try { Hashtable param = new Hashtable(); param["owner"] = user.ToString(); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "get_avatar_appearance"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(GetUserServerURL(user), methodName), 8000); Hashtable respData = (Hashtable)resp.Value; appearance = ConvertXMLRPCDataToAvatarAppearance(respData); } catch (WebException e) { m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch appearance for avatar {0}, {1}", user, e.Message); } return appearance; } public virtual AvatarAppearance GetBotOutfit(UUID user, string outfitName) { AvatarAppearance appearance = null; try { Hashtable param = new Hashtable(); param["owner"] = user.ToString(); param["outfitName"] = outfitName; IList parameters = new ArrayList(); parameters.Add(param); string methodName = "get_bot_outfit"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(GetUserServerURL(user), methodName), 8000); Hashtable respData = (Hashtable)resp.Value; appearance = ConvertXMLRPCDataToAvatarAppearance(respData); } catch (WebException e) { m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch appearance for avatar {0}, {1}", user, e.Message); } return appearance; } public virtual void UpdateUserAppearance(UUID user, AvatarAppearance appearance) { try { Hashtable param = appearance.ToHashTable(); param["owner"] = user.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("update_avatar_appearance", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(user), 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to update_user_appearance, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to update_user_appearance, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to update_user_appearance, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to update Avatar's appearance: " + e.Message); // Return Empty list (no friends) } } public virtual void AddOrUpdateBotOutfit(UUID userID, string outfitName, AvatarAppearance appearance) { try { Hashtable param = appearance.ToHashTable(); param["owner"] = userID.ToString(); param["outfitName"] = outfitName; IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("add_bot_outfit", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(userID), 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to add_bot_outfit, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to add_bot_outfit, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to add_bot_outfit, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to add bot outfit: " + e.Message); // Return Empty list (no friends) } } public virtual void RemoveBotOutfit(UUID userID, string outfitName) { try { Hashtable param = new Hashtable(); param["userID"] = userID.ToString(); param["outfitName"] = outfitName; IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("remove_bot_outfit", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(userID), 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to remove_bot_outfit, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to remove_bot_outfit, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to remove_bot_outfit, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to remove bot outfit: " + e.Message); // Return Empty list (no friends) } } public virtual List<string> GetBotOutfitsByOwner(UUID userID) { List<string> response = new List<string>(); try { Hashtable param = new Hashtable(); param.Add("userID", userID.ToString()); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "get_bot_outfits_by_owner"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(GetUserServerURL(UUID.Zero), methodName), 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { foreach (object key in respData.Keys) if (key.ToString() != "returnString") response.Add(respData[key].ToString()); } else { m_log.Warn("[GRID]: Unable to get_bot_outfits_by_owner, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to get_bot_outfits_by_owner, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to get_bot_outfits_by_owner, UserServer didn't understand me!"); } } catch (WebException e) { m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch bot outfits, {0}", e.Message); } return response; } public virtual void SetCachedBakedTextures(Dictionary<UUID, UUID> bakedTextures) { try { Hashtable param = new Hashtable(); foreach (KeyValuePair<UUID, UUID> bakedTexture in bakedTextures) { param[bakedTexture.Key.ToString()] = bakedTexture.Value.ToString(); } IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("set_cached_baked_textures", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(UUID.Zero), 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] != "TRUE") { m_log.Warn("[GRID]: Unable to set_cached_baked_textures, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to set_cached_baked_textures, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to set_cached_baked_textures, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to set_cached_baked_textures: " + e.Message); // Return Empty list (no friends) } } public virtual List<CachedAgentArgs> GetCachedBakedTextures(List<CachedAgentArgs> request) { List<CachedAgentArgs> response = new List<CachedAgentArgs>(); try { Hashtable param = new Hashtable(); foreach (CachedAgentArgs args in request) param.Add(args.TextureIndex.ToString(), args.ID.ToString()); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "get_cached_baked_textures"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(GetUserServerURL(UUID.Zero), methodName), 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { foreach (object key in respData.Keys) if(key.ToString() != "returnString") response.Add(new CachedAgentArgs() { TextureIndex = byte.Parse(key.ToString()), ID = UUID.Parse(respData[key].ToString()) }); } else { m_log.Warn("[GRID]: Unable to set_cached_baked_textures, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to set_cached_baked_textures, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to set_cached_baked_textures, UserServer didn't understand me!"); } } catch (WebException e) { m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch cached baked textures, {0}", e.Message); } return response; } protected virtual string GetUserServerURL(UUID userID) { return m_commsManager.NetworkServersInfo.UserURL; } /*protected UserInterestsData ConvertXMLRPCDataToUserInterests(Hashtable data) { if (data.Contains("error_type")) { m_log.Warn("[GRID]: " + "Error sent by user server when trying to get user interests: (" + data["error_type"] + "): " + data["error_desc"]); return null; } UserInterestsData userData = new UserInterestsData(); userData.ID = new UUID((string)data["uuid"]); userData.SkillsMask = Convert.ToUInt32(data["skillsMask"]); userData.SkillsText = (string)data["skillsText"]; userData.WantToMask = Convert.ToUInt32(data["wantToMask"]); userData.WantToText = (string)data["wantToText"]; userData.LanguagesText = (string)data["languagesText"]; return userData; }*/ protected UserProfileData ConvertXMLRPCDataToUserProfile(Hashtable data) { if (data.Contains("error_type")) { if ((string)data["error_type"] != "unknown_user") m_log.Warn("[GRID]: " + "Error sent by user server when trying to get user profile: (" + data["error_type"] + "): " + data["error_desc"]); return null; } UserProfileData userData = new UserProfileData(); userData.FirstName = (string)data["firstname"]; userData.SurName = (string)data["lastname"]; userData.ID = new UUID((string)data["uuid"]); userData.Created = Convert.ToInt32(data["profile_created"]); userData.UserInventoryURI = (string)data["server_inventory"]; userData.UserAssetURI = (string)data["server_asset"]; userData.FirstLifeAboutText = (string)data["profile_firstlife_about"]; userData.FirstLifeImage = new UUID((string)data["profile_firstlife_image"]); userData.AboutText = (string)data["profile_about"]; userData.Image = new UUID((string)data["profile_image"]); userData.LastLogin = Convert.ToInt32((string)data["profile_lastlogin"]); userData.HomeRegion = Convert.ToUInt64((string)data["home_region"]); if (data.Contains("home_region_id")) userData.HomeRegionID = new UUID((string)data["home_region_id"]); else userData.HomeRegionID = UUID.Zero; userData.HomeLocation = new Vector3((float)Convert.ToDouble((string)data["home_coordinates_x"]), (float)Convert.ToDouble((string)data["home_coordinates_y"]), (float)Convert.ToDouble((string)data["home_coordinates_z"])); userData.HomeLookAt = new Vector3((float)Convert.ToDouble((string)data["home_look_x"]), (float)Convert.ToDouble((string)data["home_look_y"]), (float)Convert.ToDouble((string)data["home_look_z"])); if (data.Contains("user_flags")) userData.UserFlags = Convert.ToInt32((string)data["user_flags"]); if (data.Contains("god_level")) userData.GodLevel = Convert.ToInt32((string)data["god_level"]); if (data.Contains("custom_type")) userData.CustomType = (string)data["custom_type"]; else userData.CustomType = String.Empty; if (userData.CustomType == null) userData.CustomType = String.Empty; if (data.Contains("partner")) userData.Partner = new UUID((string)data["partner"]); else userData.Partner = UUID.Zero; if (data.Contains("profileURL")) userData.ProfileURL = (string)data["profileURL"]; else userData.ProfileURL = String.Empty; if (userData.ProfileURL == null) userData.ProfileURL = String.Empty; return userData; } protected AvatarAppearance ConvertXMLRPCDataToAvatarAppearance(Hashtable data) { if (data != null) { if (data.Contains("error_type")) { if ((string)data["error_type"] != "unknown_user") m_log.Warn("[GRID]: " + "Error sent by user server when trying to get user appearance: (" + data["error_type"] + "): " + data["error_desc"]); return null; } else { return new AvatarAppearance(data); } } else { m_log.Error("[GRID]: The avatar appearance is null, something bad happenend"); return null; } } protected List<AvatarPickerAvatar> ConvertXMLRPCDataToAvatarPickerList(UUID queryID, Hashtable data) { List<AvatarPickerAvatar> pickerlist = new List<AvatarPickerAvatar>(); int pickercount = Convert.ToInt32((string)data["avcount"]); UUID respqueryID = new UUID((string)data["queryid"]); if (queryID == respqueryID) { for (int i = 0; i < pickercount; i++) { AvatarPickerAvatar apicker = new AvatarPickerAvatar(); UUID avatarID = new UUID((string)data["avatarid" + i.ToString()]); string firstname = (string)data["firstname" + i.ToString()]; string lastname = (string)data["lastname" + i.ToString()]; apicker.AvatarID = avatarID; apicker.firstName = firstname; apicker.lastName = lastname; pickerlist.Add(apicker); } } else { m_log.Warn("[OGS1 USER SERVICES]: Got invalid queryID from userServer"); } return pickerlist; } protected List<FriendListItem> ConvertXMLRPCDataToFriendListItemList(Hashtable data) { List<FriendListItem> buddylist = new List<FriendListItem>(); int buddycount = Convert.ToInt32((string)data["avcount"]); for (int i = 0; i < buddycount; i++) { FriendListItem buddylistitem = new FriendListItem(); buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]); buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]); buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]); buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]); buddylist.Add(buddylistitem); } return buddylist; } #region IUserDataPlugin Members public void SaveUserPreferences(UserPreferencesData userPrefs) { Hashtable param = new Hashtable(); param["userId"] = userPrefs.UserId.ToString(); param["recvIMsViaEmail"] = userPrefs.ReceiveIMsViaEmail ? "1" : "0"; param["listedInDirectory"] = userPrefs.ListedInDirectory ? "1" : "0"; IList parameters = new ArrayList(); parameters.Add(param); string methodName = "save_user_preferences"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_commsManager.NetworkServersInfo.UserURL, methodName), 3000); Hashtable respData = (Hashtable)resp.Value; if (respData == null || !respData.Contains("returnString") || ((string) respData["returnString"] != "OK")) { m_log.Warn("[OGS1 USER SERVICES]: Got invalid response to preference save from user server"); } } public UserPreferencesData RetrieveUserPreferences(UUID userId) { Hashtable param = new Hashtable(); param["userId"] = userId.ToString(); IList parameters = new ArrayList(); parameters.Add(param); string methodName = "get_user_preferences"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_commsManager.NetworkServersInfo.UserURL, methodName), 8000); Hashtable respData = (Hashtable)resp.Value; if (respData.Contains("error_type")) { if ((string)respData["error_type"] != "unknown_user") m_log.Warn("[GRID]: " + "Error sent by user server when trying to get user preferences: (" + respData["error_type"] + "): " + respData["error_desc"]); return null; } else { UserPreferencesData prefs = new UserPreferencesData(userId, ((string)respData["recvIMsViaEmail"]) == "1" ? true : false, ((string)respData["listedInDirectory"]) == "1" ? true : false); return prefs; } } #endregion } }
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System.Runtime; using System.ServiceModel.Diagnostics; sealed class InternalDuplexChannelListener : DelegatingChannelListener<IDuplexChannel> { IChannelFactory<IOutputChannel> innerChannelFactory; bool providesCorrelation; internal InternalDuplexChannelListener(InternalDuplexBindingElement bindingElement, BindingContext context) : base(context.Binding, context.Clone().BuildInnerChannelListener<IInputChannel>()) { this.innerChannelFactory = context.BuildInnerChannelFactory<IOutputChannel>(); this.providesCorrelation = bindingElement.ProvidesCorrelation; } IOutputChannel GetOutputChannel(Uri to, TimeoutHelper timeoutHelper) { IOutputChannel channel = this.innerChannelFactory.CreateChannel(new EndpointAddress(to)); channel.Open(timeoutHelper.RemainingTime()); return channel; } protected override void OnAbort() { try { this.innerChannelFactory.Abort(); } finally { base.OnAbort(); } } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedCloseAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, this.innerChannelFactory); } protected override void OnEndClose(IAsyncResult result) { ChainedCloseAsyncResult.End(result); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.OnClose(timeoutHelper.RemainingTime()); this.innerChannelFactory.Close(timeoutHelper.RemainingTime()); } protected override void OnOpening() { base.OnOpening(); this.Acceptor = (IChannelAcceptor<IDuplexChannel>)(object)new CompositeDuplexChannelAcceptor(this, (IChannelListener<IInputChannel>)this.InnerChannelListener); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedOpenAsyncResult(timeout, callback, state, base.OnBeginOpen, base.OnEndOpen, this.innerChannelFactory); } protected override void OnEndOpen(IAsyncResult result) { ChainedOpenAsyncResult.End(result); } protected override void OnOpen(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.OnOpen(timeoutHelper.RemainingTime()); this.innerChannelFactory.Open(timeoutHelper.RemainingTime()); } public override T GetProperty<T>() { if (typeof(T) == typeof(IChannelFactory)) { return (T)(object)innerChannelFactory; } if (typeof(T) == typeof(ISecurityCapabilities) && !this.providesCorrelation) { return InternalDuplexBindingElement.GetSecurityCapabilities<T>(base.GetProperty<ISecurityCapabilities>()); } T baseProperty = base.GetProperty<T>(); if (baseProperty != null) { return baseProperty; } return this.innerChannelFactory.GetProperty<T>(); } sealed class CompositeDuplexChannelAcceptor : LayeredChannelAcceptor<IDuplexChannel, IInputChannel> { public CompositeDuplexChannelAcceptor(InternalDuplexChannelListener listener, IChannelListener<IInputChannel> innerListener) : base(listener, innerListener) { } protected override IDuplexChannel OnAcceptChannel(IInputChannel innerChannel) { return new ServerCompositeDuplexChannel((InternalDuplexChannelListener)ChannelManager, innerChannel); } } sealed class ServerCompositeDuplexChannel : ChannelBase, IDuplexChannel { IInputChannel innerInputChannel; TimeSpan sendTimeout; public ServerCompositeDuplexChannel(InternalDuplexChannelListener listener, IInputChannel innerInputChannel) : base(listener) { this.innerInputChannel = innerInputChannel; this.sendTimeout = listener.DefaultSendTimeout; } InternalDuplexChannelListener Listener { get { return (InternalDuplexChannelListener)base.Manager; } } public EndpointAddress LocalAddress { get { return this.innerInputChannel.LocalAddress; } } public EndpointAddress RemoteAddress { get { return null; } } public Uri Via { get { return null; } } public Message Receive() { return this.Receive(this.DefaultReceiveTimeout); } public Message Receive(TimeSpan timeout) { return InputChannel.HelpReceive(this, timeout); } public IAsyncResult BeginReceive(AsyncCallback callback, object state) { return this.BeginReceive(this.DefaultReceiveTimeout, callback, state); } public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state) { return InputChannel.HelpBeginReceive(this, timeout, callback, state); } public Message EndReceive(IAsyncResult result) { return InputChannel.HelpEndReceive(result); } public IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state) { return this.innerInputChannel.BeginTryReceive(timeout, callback, state); } public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state) { return this.BeginSend(message, this.DefaultSendTimeout, callback, state); } public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return new SendAsyncResult(this, message, timeout, callback, state); } public bool EndTryReceive(IAsyncResult result, out Message message) { return this.innerInputChannel.EndTryReceive(result, out message); } public void EndSend(IAsyncResult result) { SendAsyncResult.End(result); } protected override void OnAbort() { this.innerInputChannel.Abort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return this.innerInputChannel.BeginClose(timeout, callback, state); } protected override void OnEndClose(IAsyncResult result) { this.innerInputChannel.EndClose(result); } protected override void OnClose(TimeSpan timeout) { if (this.innerInputChannel.State == CommunicationState.Opened) this.innerInputChannel.Close(timeout); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return this.innerInputChannel.BeginOpen(callback, state); } protected override void OnEndOpen(IAsyncResult result) { this.innerInputChannel.EndOpen(result); } protected override void OnOpen(TimeSpan timeout) { this.innerInputChannel.Open(timeout); } public bool TryReceive(TimeSpan timeout, out Message message) { return this.innerInputChannel.TryReceive(timeout, out message); } public void Send(Message message) { this.Send(message, this.DefaultSendTimeout); } public void Send(Message message, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); IOutputChannel outputChannel = ValidateStateAndGetOutputChannel(message, timeoutHelper); try { outputChannel.Send(message, timeoutHelper.RemainingTime()); outputChannel.Close(timeoutHelper.RemainingTime()); } finally { outputChannel.Abort(); } } IOutputChannel ValidateStateAndGetOutputChannel(Message message, TimeoutHelper timeoutHelper) { ThrowIfDisposedOrNotOpen(); if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); } Uri to = message.Properties.Via; if (to == null) { to = message.Headers.To; if (to == null) { throw TraceUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.MessageMustHaveViaOrToSetForSendingOnServerSideCompositeDuplexChannels)), message); } //Check for EndpointAddress.AnonymousUri is just redundant else if (to.Equals(EndpointAddress.AnonymousUri) || to.Equals(message.Version.Addressing.AnonymousUri)) { throw TraceUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.MessageToCannotBeAddressedToAnonymousOnServerSideCompositeDuplexChannels, to)), message); } } //Check for EndpointAddress.AnonymousUri is just redundant else if (to.Equals(EndpointAddress.AnonymousUri) || to.Equals(message.Version.Addressing.AnonymousUri)) { throw TraceUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.MessageViaCannotBeAddressedToAnonymousOnServerSideCompositeDuplexChannels, to)), message); } return this.Listener.GetOutputChannel(to, timeoutHelper); } class SendAsyncResult : AsyncResult { IOutputChannel outputChannel; static AsyncCallback sendCompleteCallback = Fx.ThunkCallback(new AsyncCallback(SendCompleteCallback)); TimeoutHelper timeoutHelper; public SendAsyncResult(ServerCompositeDuplexChannel outer, Message message, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.timeoutHelper = new TimeoutHelper(timeout); this.outputChannel = outer.ValidateStateAndGetOutputChannel(message, timeoutHelper); bool success = false; try { IAsyncResult result = outputChannel.BeginSend(message, timeoutHelper.RemainingTime(), sendCompleteCallback, this); if (result.CompletedSynchronously) { CompleteSend(result); this.Complete(true); } success = true; } finally { if (!success) this.outputChannel.Abort(); } } void CompleteSend(IAsyncResult result) { try { outputChannel.EndSend(result); outputChannel.Close(); } finally { outputChannel.Abort(); } } internal static void End(IAsyncResult result) { AsyncResult.End<SendAsyncResult>(result); } static void SendCompleteCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } SendAsyncResult thisPtr = (SendAsyncResult)result.AsyncState; Exception completionException = null; try { thisPtr.CompleteSend(result); } #pragma warning suppress 56500 // [....], transferring exception to another thread catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; } thisPtr.Complete(false, completionException); } } public bool WaitForMessage(TimeSpan timeout) { return innerInputChannel.WaitForMessage(timeout); } public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state) { return innerInputChannel.BeginWaitForMessage(timeout, callback, state); } public bool EndWaitForMessage(IAsyncResult result) { return innerInputChannel.EndWaitForMessage(result); } } } }
//------------------------------------------------------------------------------ // Symbooglix // // // Copyright 2014-2017 Daniel Liew // // This file is licensed under the MIT license. // See LICENSE.txt for details. //------------------------------------------------------------------------------ using NUnit.Framework; using System; using Symbooglix; using Microsoft.Basetypes; using Microsoft.Boogie; using System.Linq; using System.Collections.Generic; namespace SymbooglixLibTests { [TestFixture()] public class Map : SymbooglixTest { [Test()] public void SimpleMap() { int hits = 0; Expr nestedMapStoreintermediate = null; Expr simpleMapStoreIntermediate = null; p = LoadProgramFrom("programs/SimpleMap.bpl"); e = GetExecutor(p); var builderDuplicator = new BuilderDuplicator( new SimpleExprBuilder(/*immutable=*/ true)); e.BreakPointReached += delegate(object executor, Executor.BreakPointEventArgs data) { if (data.Name == "check_read_map") { var a = e.CurrentState.GetInScopeVariableAndExprByName("a"); // a := symbolic_0[0bv8] Assert.IsInstanceOf<NAryExpr>(a.Value); NAryExpr mapSelect = a.Value as NAryExpr; Assert.IsInstanceOf<MapSelect>(mapSelect.Fun); Assert.AreEqual(2, mapSelect.Args.Count); // [0] should be map Identifier CheckIsSymbolicIdentifier(mapSelect.Args[0], e.CurrentState); // [1] should be offset CheckIsLiteralBVConstWithValue(mapSelect.Args[1], BigNum.FromInt(0)); } else if (data.Name == "check_write_literal") { var m = e.CurrentState.GetInScopeVariableAndExprByName("m"); // m := symbolic_0[3bv8 := 12bv32] simpleMapStoreIntermediate = (Expr) builderDuplicator.Visit(m.Value); // Save a copy of the expression for later. Assert.IsInstanceOf<NAryExpr>(m.Value); NAryExpr mapStore = m.Value as NAryExpr; Assert.IsInstanceOf<MapStore>(mapStore.Fun); Assert.AreEqual(3, mapStore.Args.Count); // [0] should be map Identifier CheckIsSymbolicIdentifier(mapStore.Args[0], e.CurrentState); // [1] should be write offset CheckIsLiteralBVConstWithValue(mapStore.Args[1], BigNum.FromInt(3)); // [2] should be value written to location in Map CheckIsLiteralBVConstWithValue(mapStore.Args[2], BigNum.FromInt(12)); } else if (data.Name == "check_write_from_map") { var m = e.CurrentState.GetInScopeVariableAndExprByName("m"); nestedMapStoreintermediate = (Expr) builderDuplicator.Visit(m.Value); // Save a copy of the expression for later. Assert.IsInstanceOf<NAryExpr>(m.Value); NAryExpr mapStore = m.Value as NAryExpr; Assert.IsInstanceOf<MapStore>(mapStore.Fun); // symbolic_0[3bv8:= 12bv32][1bv8 := symbolic_0[0bv8]] Assert.AreEqual(3, mapStore.Args.Count); // [0] Is Map written to which should we wrote to earlier so should also be MapStore Assert.IsTrue(mapStore.Args[0].Equals(simpleMapStoreIntermediate)); // [1] is write offset CheckIsLiteralBVConstWithValue(mapStore.Args[1], BigNum.FromInt(1)); // 1bv8 // [2] is value to write which is actually a value inside own map Assert.IsInstanceOf<NAryExpr>(mapStore.Args[2]); NAryExpr WrittenValue = mapStore.Args[2] as NAryExpr; // symbolic_0[0bv8] Assert.IsInstanceOf<MapSelect>(WrittenValue.Fun); { // [0] should be map Identifier CheckIsSymbolicIdentifier(WrittenValue.Args[0], e.CurrentState); // [1] should be offset CheckIsLiteralBVConstWithValue(WrittenValue.Args[1], BigNum.FromInt(0)); } } else if (data.Name == "check_write_symbolic_index") { // Expecting m := symbolic_0[3bv8 := 12bv32][1bv8 := symbolic_0[0bv8]][symbolic_2 := 7bv32] var m = e.CurrentState.GetInScopeVariableAndExprByName("m"); Assert.IsInstanceOf<NAryExpr>(m.Value); NAryExpr mapStore = m.Value as NAryExpr; Assert.IsInstanceOf<MapStore>(mapStore.Fun); // symbolic_0[3bv8:= 12bv32][1bv8 := symbolic_0[0bv8]] Assert.AreEqual(3, mapStore.Args.Count); // [0] Should be the map written to which should be equivalent to the expression recorded in "intermediate" Assert.IsNotNull(nestedMapStoreintermediate); Assert.IsTrue(nestedMapStoreintermediate.Equals(mapStore.Args[0])); // [1] Write offset which should be symbolic (symbolic_2) CheckIsSymbolicIdentifier(mapStore.Args[1], e.CurrentState); // [2] Value to write (7bv32) CheckIsLiteralBVConstWithValue(mapStore.Args[2], BigNum.FromInt(7)); } else { Assert.Fail("Unsupported break point"); } ++hits; }; e.Run(GetMain(p)); Assert.AreEqual(4, hits); } [Test()] public void PartialIndexMap() { p = LoadProgramFrom(@" procedure main() { var x:[int][int]bool; var y:[int][int]bool; var symIndex:int; x[0][0] := false; // only partially index into y y[0] := x[0]; assert {:symbooglix_bp ""check_written""} true; } ", "test.bpl"); e = GetExecutor(p); bool check_written = false; var builder = new SimpleExprBuilder(true); var localVarX = p.TopLevelDeclarations.OfType<Implementation>().Where(i => i.Name == "main").First().LocVars.Where(v => v.Name == "x").First(); var localVarY = p.TopLevelDeclarations.OfType<Implementation>().Where(i => i.Name == "main").First().LocVars.Where(v => v.Name == "y").First(); e.BreakPointReached += delegate(object sender, Executor.BreakPointEventArgs eventArgs) { Assert.AreEqual("check_written", eventArgs.Name); check_written = true; // Check we can read x[0][0] directly var x00 = e.CurrentState.ReadMapVariableInScopeAt(localVarX, new List<Expr>() { builder.ConstantInt(0), builder.ConstantInt(0) }); Assert.AreEqual(builder.False, x00); var yExpr = e.CurrentState.GetInScopeVariableExpr(localVarY); Assert.AreEqual("~sb_y_0[0 := ~sb_x_0[0 := ~sb_x_0[0][0 := false]][0]]", yExpr.ToString()); }; e.Run(GetMain(p)); Assert.IsTrue(check_written); } [Test()] public void ConcreteMapAssign() { p = LoadProgramFrom(@" procedure main() { var x:[int][int]bool; var symIndex:int; x[0][0] := true; x[0][1] := false; assert {:symbooglix_bp ""check_written""} true; // write to symbolic location x[0][symIndex] := false; assert {:symbooglix_bp ""check_sym_write""} true; } ", "test.bpl"); e = GetExecutor(p); bool check_written = false; bool check_sym_write = false; var builder = new SimpleExprBuilder(true); var localVarV = p.TopLevelDeclarations.OfType<Implementation>().Where(i => i.Name == "main").First().LocVars.Where(v => v.Name == "x").First(); e.BreakPointReached += delegate(object sender, Executor.BreakPointEventArgs eventArgs) { switch (eventArgs.Name) { case "check_written": check_written = true; // Check we can read x[0][0] directly var x00 = e.CurrentState.ReadMapVariableInScopeAt(localVarV, new List<Expr>() { builder.ConstantInt(0), builder.ConstantInt(0) }); Assert.AreEqual(builder.True, x00); var x01 = e.CurrentState.ReadMapVariableInScopeAt(localVarV, new List<Expr>() { builder.ConstantInt(0), builder.ConstantInt(1) } ); Assert.AreEqual(builder.False, x01); // Check the flushed expression from // Note without the constant folding expr builder the form is // "~sb_x_0[0 := ~sb_x_0[0][0 := true]][0 := ~sb_x_0[0 := ~sb_x_0[0][0 := true]][0][1 := false]]" Assert.AreEqual("~sb_x_0[0 := ~sb_x_0[0][0 := true][1 := false]]", e.CurrentState.GetInScopeVariableExpr(localVarV).ToString()); break; case "check_sym_write": check_sym_write = true; var x00After = e.CurrentState.ReadMapVariableInScopeAt(localVarV, new List<Expr>() { builder.ConstantInt(0), builder.ConstantInt(0) }); Console.WriteLine(x00After.ToString()); // FIXME: I'm unsure if this is correct Console.WriteLine(x00After.ToString()); Assert.AreEqual("~sb_x_0[0][0 := true][1 := false][~sb_symIndex_0 := false][0]", x00After.ToString()); break; default: Assert.Fail("Unexpected breakpoint"); break; } }; e.Run(GetMain(p)); Assert.IsTrue(check_written); Assert.IsTrue(check_sym_write); } [Test()] public void DirectMapCopy() { p = LoadProgramFrom(@" procedure main() { var x:[int]bool; var y:[int]bool; x[0] := true; x[1] := false; assert {:symbooglix_bp ""check_written""} true; // copy the map y := x; assert {:symbooglix_bp ""check_map_copy""} true; } ", "test.bpl"); e = GetExecutor(p); bool check_written = false; bool check_map_copy = false; var builder = new SimpleExprBuilder(true); var localVarX = p.TopLevelDeclarations.OfType<Implementation>().Where(i => i.Name == "main").First().LocVars.Where(v => v.Name == "x").First(); var localVarY = p.TopLevelDeclarations.OfType<Implementation>().Where(i => i.Name == "main").First().LocVars.Where(v => v.Name == "y").First(); e.BreakPointReached += delegate(object sender, Executor.BreakPointEventArgs eventArgs) { switch (eventArgs.Name) { case "check_written": check_written = true; // Check we can read x[0] and x[1] directly var x0 = e.CurrentState.ReadMapVariableInScopeAt(localVarX, new List<Expr>() { builder.ConstantInt(0) }); Assert.AreEqual(builder.True, x0); var x1 = e.CurrentState.ReadMapVariableInScopeAt(localVarX, new List<Expr>() { builder.ConstantInt(1) } ); Assert.AreEqual(builder.False, x1); // Check the full expression form Assert.AreEqual("~sb_x_0[0 := true][1 := false]", e.CurrentState.GetInScopeVariableExpr(localVarX).ToString()); break; case "check_map_copy": check_map_copy = true; // Check we can read y[0] and y[1] directly var y0 = e.CurrentState.ReadMapVariableInScopeAt(localVarY, new List<Expr>() { builder.ConstantInt(0) }); Assert.AreEqual(builder.True, y0); var y1 = e.CurrentState.ReadMapVariableInScopeAt(localVarY, new List<Expr>() { builder.ConstantInt(1) } ); Assert.AreEqual(builder.False, y1); // Check the full expression form Assert.AreEqual("~sb_x_0[0 := true][1 := false]", e.CurrentState.GetInScopeVariableExpr(localVarX).ToString()); Assert.AreEqual("~sb_x_0[0 := true][1 := false]", e.CurrentState.GetInScopeVariableExpr(localVarY).ToString()); break; default: Assert.Fail("Unexpected breakpoint"); break; } }; e.Run(GetMain(p)); Assert.IsTrue(check_written); Assert.IsTrue(check_map_copy); } [Test()] public void AxiomOnMap() { p = LoadProgramFrom(@" const g:[int]bool; // the bound variable here is the index into a map axiom (exists x:int :: (x == 0) && g[x]); procedure main() { assert g[0]; } ", "test.bpl"); e = GetExecutor(p, /*scheduler=*/ new DFSStateScheduler(), /*solver=*/ GetSolver()); var tc = new TerminationCounter(TerminationCounter.CountType.BOTH); tc.Connect(e); e.Run(GetMain(p)); Assert.AreEqual(1, tc.Sucesses); Assert.AreEqual(0, tc.FailingAsserts); } [Test()] public void AxiomOnMap2() { p = LoadProgramFrom(@" const g:[int]bool; // the bound variable here is a map axiom (exists m:[int]bool :: m[0] == g[0]); procedure main() { assert g[0] || !g[0]; } ", "test.bpl"); e = GetExecutor(p, /*scheduler=*/ new DFSStateScheduler(), /*solver=*/ GetSolver()); var tc = new TerminationCounter(TerminationCounter.CountType.BOTH); tc.Connect(e); e.Run(GetMain(p)); Assert.AreEqual(1, tc.Sucesses); Assert.AreEqual(0, tc.FailingAsserts); } [Test(),Ignore()] public void TwoDMap() { p = LoadProgramFrom("programs/2DMap.bpl"); e = GetExecutor(p); e.BreakPointReached += delegate(object executor, Executor.BreakPointEventArgs data) { throw new NotImplementedException(); }; e.Run(GetMain(p)); } [Test()] public void MultiArityMapMixedTypes() { p = LoadProgramFrom(@" procedure main() { var x:[int,bool]bool; x[0,false] := true; assert x[0,false] == true; } ", "test.bpl"); e = GetExecutor(p, /*scheduler=*/ new DFSStateScheduler(), /*solver=*/ GetSolver()); var tc = new TerminationCounter(TerminationCounter.CountType.BOTH); tc.Connect(e); e.Run(GetMain(p)); Assert.AreEqual(1, tc.Sucesses); Assert.AreEqual(0, tc.FailingAsserts); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Net.FtpWebRequest.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Net { sealed public partial class FtpWebRequest : WebRequest { #region Methods and constructors public override void Abort() { } public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, Object state) { return default(IAsyncResult); } public override IAsyncResult BeginGetResponse(AsyncCallback callback, Object state) { return default(IAsyncResult); } public override Stream EndGetRequestStream(IAsyncResult asyncResult) { return default(Stream); } public override WebResponse EndGetResponse(IAsyncResult asyncResult) { return default(WebResponse); } internal FtpWebRequest() { } public override Stream GetRequestStream() { return default(Stream); } public override WebResponse GetResponse() { return default(WebResponse); } #endregion #region Properties and indexers public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { return default(System.Security.Cryptography.X509Certificates.X509CertificateCollection); } set { } } public override string ConnectionGroupName { get { return default(string); } set { } } public override long ContentLength { get { return default(long); } set { } } public long ContentOffset { get { return default(long); } set { } } public override string ContentType { get { return default(string); } set { } } public override ICredentials Credentials { get { return default(ICredentials); } set { } } public static System.Net.Cache.RequestCachePolicy DefaultCachePolicy { get { return default(System.Net.Cache.RequestCachePolicy); } set { } } public bool EnableSsl { get { return default(bool); } set { } } public override WebHeaderCollection Headers { get { return default(WebHeaderCollection); } set { } } public bool KeepAlive { get { return default(bool); } set { } } public override string Method { get { return default(string); } set { } } public override bool PreAuthenticate { get { return default(bool); } set { } } public override IWebProxy Proxy { get { return default(IWebProxy); } set { } } public int ReadWriteTimeout { get { return default(int); } set { } } public string RenameTo { get { return default(string); } set { } } public override Uri RequestUri { get { return default(Uri); } } public ServicePoint ServicePoint { get { return default(ServicePoint); } } public override int Timeout { get { return default(int); } set { } } public bool UseBinary { get { return default(bool); } set { } } public override bool UseDefaultCredentials { get { return default(bool); } set { } } public bool UsePassive { get { return default(bool); } set { } } #endregion } }
using System; using System.Linq; using System.Collections.Generic; using Box.Utils; namespace Box.Parsing { public struct Empty { } public struct ParseBuffer { public int Index; public string Text; public ParseBuffer( string text, int index ) { Text = text; Index = index; } } public class FailData { public readonly int FailIndex; public FailData( int index ) { FailIndex = index; } } public class ParseResult<T> { public readonly bool IsSuccessful; public readonly T Result; public readonly ParseBuffer Buffer; public readonly FailData Failure; public ParseResult( T result, ParseBuffer buffer ) { IsSuccessful = true; Result = result; Buffer = buffer; } public ParseResult( FailData f ) { IsSuccessful = false; Failure = f; } } public delegate ParseResult<T> Parser<T>( ParseBuffer buffer ); public static class ParserUtil { public static Parser<B> Bind<A, B>( Parser<A> parser, Func<A, Parser<B>> gen ) { return buffer => { var result = parser( buffer ); if ( result.IsSuccessful ) { return gen( result.Result )( result.Buffer ); } else { return new ParseResult<B>( new FailData( buffer.Index ) ); } }; } public static Parser<B> Bind<A, B>( Parser<A> parser, Func<Parser<B>> gen ) { return buffer => { var result = parser( buffer ); if ( result.IsSuccessful ) { return gen()( result.Buffer ); } else { return new ParseResult<B>( new FailData( buffer.Index ) ); } }; } public static Parser<A> Unit<A>( A value ) { return buffer => new ParseResult<A>( value, buffer ); } public static Parser<Empty> End = buffer => { if( buffer.Index == buffer.Text.Length ) { return new ParseResult<Empty>( new Empty(), buffer ); } else { return new ParseResult<Empty>( new FailData( buffer.Index ) ); } }; public static Parser<B> Map<A, B>( this Parser<A> parser, Func<A, B> f ) { return buffer => { var result = parser( buffer ); if ( result.IsSuccessful ) { return new ParseResult<B>( f( result.Result ), result.Buffer ); } else { return new ParseResult<B>( new FailData( buffer.Index ) ); } }; } public static Parser<Maybe<A>> OneOrNone<A>( this Parser<A> parser ) { return buffer => { var result = parser( buffer ); if ( result.IsSuccessful ) { return new ParseResult<Maybe<A>>( new Maybe<A>( result.Result ), result.Buffer ); } else { return new ParseResult<Maybe<A>>( new Maybe<A>(), buffer ); } }; } public static Parser<IEnumerable<A>> OneOrMore<A>( this Parser<A> parser ) { return Bind( parser, v => Bind( parser.ZeroOrMore(), vs => Unit( new A[] { v }.Concat( vs ) ) ) ); } public static Parser<IEnumerable<A>> ZeroOrMore<A>( this Parser<A> parser ) { return buffer => { var a = new List<A>(); var result = parser( buffer ); ParseBuffer? temp = null; while ( result.IsSuccessful ) { temp = result.Buffer; a.Add( result.Result ); result = parser( result.Buffer ); } if ( temp.HasValue ) { return new ParseResult<IEnumerable<A>>( a, temp.Value ); } else { return new ParseResult<IEnumerable<A>>( a, buffer ); } }; } public static Parser<A> Alternate<A>( params Parser<A>[] parsers ) { return buffer => { foreach( var p in parsers ) { var result = p( buffer ); if ( result.IsSuccessful ) { return new ParseResult<A>( result.Result, result.Buffer ); } } return new ParseResult<A>( new FailData( buffer.Index ) ); }; } public static Parser<string> ParseUntil<Ignore>( Parser<Ignore> end ) { return buffer => { var length = 0; var start = buffer.Index; var res = end( buffer ); while ( !res.IsSuccessful && start + length < buffer.Text.Length ) { length++; buffer.Index++; res = end( buffer ); } if ( res.IsSuccessful ) { return new ParseResult<string>( buffer.Text.Substring( start, length ), res.Buffer ); } else { return new ParseResult<string>( new FailData( buffer.Index ) ); } }; } public static Parser<char> EatCharIf( Func<char, bool> predicate ) { return buffer => { if ( buffer.Index < buffer.Text.Length && predicate( buffer.Text[buffer.Index] ) ) { var index = buffer.Index; buffer.Index++; return new ParseResult<char>( buffer.Text[index], buffer ); } else { return new ParseResult<char>( new FailData( buffer.Index ) ); } }; } public static Parser<char> EatChar = buffer => { if ( buffer.Index < buffer.Text.Length ) { var index = buffer.Index; buffer.Index++; return new ParseResult<char>( buffer.Text[index], buffer ); } else { return new ParseResult<char>( new FailData( buffer.Index ) ); } }; public static Parser<string> Match( string value ) { return buffer => { if ( value.Length + buffer.Index <= buffer.Text.Length ) { var target = buffer.Text.Substring( buffer.Index, value.Length ); if ( target == value ) { buffer.Index += value.Length; return new ParseResult<string>( value, buffer ); } } return new ParseResult<string>( new FailData( buffer.Index ) ); }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; internal class TestApp { private static unsafe long test_3(B* pb) { return (pb--)->m_bval; } private static unsafe long test_10(AA[,] ab, long i) { long j = 0; fixed (B* pb = &ab[--i, ++j].m_b) { return pb->m_bval; } } private static unsafe long test_17(B* pb1, long i) { B* pb; return (pb = pb1 + i)->m_bval; } private static unsafe long test_24(B* pb1, B* pb2) { return (pb1 > pb2 ? pb2 : null)->m_bval; } private static unsafe long test_31(long pb) { return ((B*)pb)->m_bval; } private static unsafe long test_38(double* pb, long i) { return ((B*)(pb + i))->m_bval; } private static unsafe long test_45(ref B b) { fixed (B* pb = &b) { return pb[0].m_bval; } } private static unsafe long test_52(B* pb) { return (--pb)[0].m_bval; } private static unsafe long test_59(B* pb, long i) { return (&pb[-(i << (int)i)])[0].m_bval; } private static unsafe long test_66(AA* px) { return AA.get_pb(px)[0].m_bval; } private static unsafe long test_73(long pb) { return ((B*)checked((long)pb))[0].m_bval; } private static unsafe long test_80(B* pb) { return AA.get_bv1((pb++)); } private static unsafe long test_87(B[,] ab, long i, long j) { fixed (B* pb = &ab[i, j]) { return AA.get_bv1(pb); } } private static unsafe long test_94(B* pb1) { B* pb; return AA.get_bv1((pb = pb1 - 8)); } private static unsafe long test_101(B* pb, B* pb1, B* pb2) { return AA.get_bv1((pb = pb + (pb2 - pb1))); } private static unsafe long test_108(B* pb1, bool trig) { fixed (B* pb = &AA.s_x.m_b) { return AA.get_bv1((trig ? pb : pb1)); } } private static unsafe long test_115(byte* pb) { return AA.get_bv1(((B*)(pb + 7))); } private static unsafe long test_122(B b) { return AA.get_bv2(*(&b)); } private static unsafe long test_129() { fixed (B* pb = &AA.s_x.m_b) { return AA.get_bv2(*pb); } } private static unsafe long test_136(B* pb, long i) { return AA.get_bv2(*(&pb[i * 2])); } private static unsafe long test_143(B* pb1, B* pb2) { return AA.get_bv2(*(pb1 >= pb2 ? pb1 : null)); } private static unsafe long test_150(long pb) { return AA.get_bv2(*((B*)pb)); } private static unsafe long test_157(B* pb) { return AA.get_bv3(ref *pb); } private static unsafe long test_164(B[] ab, long i) { fixed (B* pb = &ab[i]) { return AA.get_bv3(ref *pb); } } private static unsafe long test_171(B* pb) { return AA.get_bv3(ref *(pb += 6)); } private static unsafe long test_178(B* pb, long[,,] i, long ii) { return AA.get_bv3(ref *(&pb[++i[--ii, 0, 0]])); } private static unsafe long test_185(AA* px) { return AA.get_bv3(ref *((B*)AA.get_pb_i(px))); } private static unsafe long test_192(byte diff, A* pa) { return AA.get_bv3(ref *((B*)(((byte*)pa) + diff))); } private static unsafe long test_199() { AA loc_x = new AA(0, 100); return (&loc_x.m_b)->m_bval == 100 ? 100 : 101; } private static unsafe long test_206(B[][] ab, long i, long j) { fixed (B* pb = &ab[i][j]) { return pb->m_bval == 100 ? 100 : 101; } } private static unsafe long test_213(B* pb1, long i) { B* pb; return (pb = (B*)(((byte*)pb1) + i * sizeof(B)))->m_bval == 100 ? 100 : 101; } private static unsafe long test_220(B* pb, long[,,] i, long ii, byte jj) { return (&pb[i[ii - jj, 0, ii - jj] = ii - 1])->m_bval == 100 ? 100 : 101; } private static unsafe long test_227(ulong ub, byte lb) { return ((B*)(ub | lb))->m_bval == 100 ? 100 : 101; } private static unsafe long test_234(long p, long s) { return ((B*)((p >> 4) | s))->m_bval == 100 ? 100 : 101; } private static unsafe long test_241(B[] ab) { fixed (B* pb = &ab[0]) { return AA.get_i1(&pb->m_bval); } } private static unsafe long test_248(B* pb) { return AA.get_i1(&(++pb)->m_bval); } private static unsafe long test_255(B* pb, long[] i, long ii) { return AA.get_i1(&(&pb[i[ii]])->m_bval); } private static unsafe long test_262(AA* px) { return AA.get_i1(&(AA.get_pb_1(px) + 1)->m_bval); } private static unsafe long test_269(long pb) { return AA.get_i1(&((B*)checked(((long)pb) + 1))->m_bval); } private static unsafe long test_276(B* pb) { return AA.get_i2((pb--)->m_bval); } private static unsafe long test_283(AA[,] ab, long i) { long j = 0; fixed (B* pb = &ab[--i, ++j].m_b) { return AA.get_i2(pb->m_bval); } } private static unsafe long test_290(B* pb1, long i) { B* pb; return AA.get_i2((pb = pb1 + i)->m_bval); } private static unsafe long test_297(B* pb1, B* pb2) { return AA.get_i2((pb1 > pb2 ? pb2 : null)->m_bval); } private static unsafe long test_304(long pb) { return AA.get_i2(((B*)pb)->m_bval); } private static unsafe long test_311(double* pb, long i) { return AA.get_i2(((B*)(pb + i))->m_bval); } private static unsafe long test_318(ref B b) { fixed (B* pb = &b) { return AA.get_i3(ref pb->m_bval); } } private static unsafe long test_325(B* pb) { return AA.get_i3(ref (--pb)->m_bval); } private static unsafe long test_332(B* pb, long i) { return AA.get_i3(ref (&pb[-(i << (int)i)])->m_bval); } private static unsafe long test_339(AA* px) { return AA.get_i3(ref AA.get_pb(px)->m_bval); } private static unsafe long test_346(long pb) { return AA.get_i3(ref ((B*)checked((long)pb))->m_bval); } private static unsafe long test_353(B* pb) { return AA.get_bv1((pb++)) != 100 ? 99 : 100; } private static unsafe long test_360(B[,] ab, long i, long j) { fixed (B* pb = &ab[i, j]) { return AA.get_bv1(pb) != 100 ? 99 : 100; } } private static unsafe long test_367(B* pb1) { B* pb; return AA.get_bv1((pb = pb1 - 8)) != 100 ? 99 : 100; } private static unsafe long test_374(B* pb, B* pb1, B* pb2) { return AA.get_bv1((pb = pb + (pb2 - pb1))) != 100 ? 99 : 100; } private static unsafe long test_381(B* pb1, bool trig) { fixed (B* pb = &AA.s_x.m_b) { return AA.get_bv1((trig ? pb : pb1)) != 100 ? 99 : 100; } } private static unsafe long test_388(byte* pb) { return AA.get_bv1(((B*)(pb + 7))) != 100 ? 99 : 100; } private static unsafe long test_395(B* pb) { if (pb + 1 > pb) return 100; throw new Exception(); } private static unsafe int Main() { AA loc_x = new AA(0, 100); AA.init_all(0); loc_x = new AA(0, 100); if (test_3(&loc_x.m_b) != 100) { Console.WriteLine("test_3() failed."); return 103; } AA.init_all(0); loc_x = new AA(0, 100); if (test_10(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100) { Console.WriteLine("test_10() failed."); return 110; } AA.init_all(0); loc_x = new AA(0, 100); if (test_17(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_17() failed."); return 117; } AA.init_all(0); loc_x = new AA(0, 100); if (test_24(&loc_x.m_b + 1, &loc_x.m_b) != 100) { Console.WriteLine("test_24() failed."); return 124; } AA.init_all(0); loc_x = new AA(0, 100); if (test_31((long)&loc_x.m_b) != 100) { Console.WriteLine("test_31() failed."); return 131; } AA.init_all(0); loc_x = new AA(0, 100); if (test_38(((double*)(&loc_x.m_b)) - 4, 4) != 100) { Console.WriteLine("test_38() failed."); return 138; } AA.init_all(0); loc_x = new AA(0, 100); if (test_45(ref loc_x.m_b) != 100) { Console.WriteLine("test_45() failed."); return 145; } AA.init_all(0); loc_x = new AA(0, 100); if (test_52(&loc_x.m_b + 1) != 100) { Console.WriteLine("test_52() failed."); return 152; } AA.init_all(0); loc_x = new AA(0, 100); if (test_59(&loc_x.m_b + 2, 1) != 100) { Console.WriteLine("test_59() failed."); return 159; } AA.init_all(0); loc_x = new AA(0, 100); if (test_66(&loc_x) != 100) { Console.WriteLine("test_66() failed."); return 166; } AA.init_all(0); loc_x = new AA(0, 100); if (test_73((long)(long)&loc_x.m_b) != 100) { Console.WriteLine("test_73() failed."); return 173; } AA.init_all(0); loc_x = new AA(0, 100); if (test_80(&loc_x.m_b) != 100) { Console.WriteLine("test_80() failed."); return 180; } AA.init_all(0); loc_x = new AA(0, 100); if (test_87(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_87() failed."); return 187; } AA.init_all(0); loc_x = new AA(0, 100); if (test_94(&loc_x.m_b + 8) != 100) { Console.WriteLine("test_94() failed."); return 194; } AA.init_all(0); loc_x = new AA(0, 100); if (test_101(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100) { Console.WriteLine("test_101() failed."); return 201; } AA.init_all(0); loc_x = new AA(0, 100); if (test_108(&loc_x.m_b, true) != 100) { Console.WriteLine("test_108() failed."); return 208; } AA.init_all(0); loc_x = new AA(0, 100); if (test_115(((byte*)(&loc_x.m_b)) - 7) != 100) { Console.WriteLine("test_115() failed."); return 215; } AA.init_all(0); loc_x = new AA(0, 100); if (test_122(loc_x.m_b) != 100) { Console.WriteLine("test_122() failed."); return 222; } AA.init_all(0); loc_x = new AA(0, 100); if (test_129() != 100) { Console.WriteLine("test_129() failed."); return 229; } AA.init_all(0); loc_x = new AA(0, 100); if (test_136(&loc_x.m_b - 2, 1) != 100) { Console.WriteLine("test_136() failed."); return 236; } AA.init_all(0); loc_x = new AA(0, 100); if (test_143(&loc_x.m_b, &loc_x.m_b) != 100) { Console.WriteLine("test_143() failed."); return 243; } AA.init_all(0); loc_x = new AA(0, 100); if (test_150((long)&loc_x.m_b) != 100) { Console.WriteLine("test_150() failed."); return 250; } AA.init_all(0); loc_x = new AA(0, 100); if (test_157(&loc_x.m_b) != 100) { Console.WriteLine("test_157() failed."); return 257; } AA.init_all(0); loc_x = new AA(0, 100); if (test_164(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100) { Console.WriteLine("test_164() failed."); return 264; } AA.init_all(0); loc_x = new AA(0, 100); if (test_171(&loc_x.m_b - 6) != 100) { Console.WriteLine("test_171() failed."); return 271; } AA.init_all(0); loc_x = new AA(0, 100); if (test_178(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100) { Console.WriteLine("test_178() failed."); return 278; } AA.init_all(0); loc_x = new AA(0, 100); if (test_185(&loc_x) != 100) { Console.WriteLine("test_185() failed."); return 285; } AA.init_all(0); loc_x = new AA(0, 100); if (test_192((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100) { Console.WriteLine("test_192() failed."); return 292; } AA.init_all(0); loc_x = new AA(0, 100); if (test_199() != 100) { Console.WriteLine("test_199() failed."); return 299; } AA.init_all(0); loc_x = new AA(0, 100); if (test_206(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_206() failed."); return 306; } AA.init_all(0); loc_x = new AA(0, 100); if (test_213(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_213() failed."); return 313; } AA.init_all(0); loc_x = new AA(0, 100); if (test_220(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100) { Console.WriteLine("test_220() failed."); return 320; } AA.init_all(0); loc_x = new AA(0, 100); if (test_227(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100) { Console.WriteLine("test_227() failed."); return 327; } AA.init_all(0); loc_x = new AA(0, 100); if (test_234(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100) { Console.WriteLine("test_234() failed."); return 334; } AA.init_all(0); loc_x = new AA(0, 100); if (test_241(new B[] { loc_x.m_b }) != 100) { Console.WriteLine("test_241() failed."); return 341; } AA.init_all(0); loc_x = new AA(0, 100); if (test_248(&loc_x.m_b - 1) != 100) { Console.WriteLine("test_248() failed."); return 348; } AA.init_all(0); loc_x = new AA(0, 100); if (test_255(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100) { Console.WriteLine("test_255() failed."); return 355; } AA.init_all(0); loc_x = new AA(0, 100); if (test_262(&loc_x) != 100) { Console.WriteLine("test_262() failed."); return 362; } AA.init_all(0); loc_x = new AA(0, 100); if (test_269((long)(((long)&loc_x.m_b) - 1)) != 100) { Console.WriteLine("test_269() failed."); return 369; } AA.init_all(0); loc_x = new AA(0, 100); if (test_276(&loc_x.m_b) != 100) { Console.WriteLine("test_276() failed."); return 376; } AA.init_all(0); loc_x = new AA(0, 100); if (test_283(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100) { Console.WriteLine("test_283() failed."); return 383; } AA.init_all(0); loc_x = new AA(0, 100); if (test_290(&loc_x.m_b - 8, 8) != 100) { Console.WriteLine("test_290() failed."); return 390; } AA.init_all(0); loc_x = new AA(0, 100); if (test_297(&loc_x.m_b + 1, &loc_x.m_b) != 100) { Console.WriteLine("test_297() failed."); return 397; } AA.init_all(0); loc_x = new AA(0, 100); if (test_304((long)&loc_x.m_b) != 100) { Console.WriteLine("test_304() failed."); return 404; } AA.init_all(0); loc_x = new AA(0, 100); if (test_311(((double*)(&loc_x.m_b)) - 4, 4) != 100) { Console.WriteLine("test_311() failed."); return 411; } AA.init_all(0); loc_x = new AA(0, 100); if (test_318(ref loc_x.m_b) != 100) { Console.WriteLine("test_318() failed."); return 418; } AA.init_all(0); loc_x = new AA(0, 100); if (test_325(&loc_x.m_b + 1) != 100) { Console.WriteLine("test_325() failed."); return 425; } AA.init_all(0); loc_x = new AA(0, 100); if (test_332(&loc_x.m_b + 2, 1) != 100) { Console.WriteLine("test_332() failed."); return 432; } AA.init_all(0); loc_x = new AA(0, 100); if (test_339(&loc_x) != 100) { Console.WriteLine("test_339() failed."); return 439; } AA.init_all(0); loc_x = new AA(0, 100); if (test_346((long)(long)&loc_x.m_b) != 100) { Console.WriteLine("test_346() failed."); return 446; } AA.init_all(0); loc_x = new AA(0, 100); if (test_353(&loc_x.m_b) != 100) { Console.WriteLine("test_353() failed."); return 453; } AA.init_all(0); loc_x = new AA(0, 100); if (test_360(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100) { Console.WriteLine("test_360() failed."); return 460; } AA.init_all(0); loc_x = new AA(0, 100); if (test_367(&loc_x.m_b + 8) != 100) { Console.WriteLine("test_367() failed."); return 467; } AA.init_all(0); loc_x = new AA(0, 100); if (test_374(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100) { Console.WriteLine("test_374() failed."); return 474; } AA.init_all(0); loc_x = new AA(0, 100); if (test_381(&loc_x.m_b, true) != 100) { Console.WriteLine("test_381() failed."); return 481; } AA.init_all(0); loc_x = new AA(0, 100); if (test_388(((byte*)(&loc_x.m_b)) - 7) != 100) { Console.WriteLine("test_388() failed."); return 488; } AA.init_all(0); loc_x = new AA(0, 100); if (test_395((B*)1) != 100) { Console.WriteLine("test_395() failed."); return 495; } Console.WriteLine("All tests passed."); return 100; } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Reflection; using System.Security; using Common.Logging; using Quartz.Core; using Quartz.Impl.AdoJobStore; using Quartz.Impl.AdoJobStore.Common; using Quartz.Impl.Matchers; using Quartz.Simpl; using Quartz.Spi; using Quartz.Util; namespace Quartz.Impl { /// <summary> /// An implementation of <see cref="ISchedulerFactory" /> that /// does all of it's work of creating a <see cref="QuartzScheduler" /> instance /// based on the contents of a properties file. /// </summary> /// <remarks> /// <para> /// By default a properties are loaded from App.config's quartz section. /// If that fails, then the file is loaded "quartz.properties". If file does not exist, /// default configuration located (as a embedded resource) in Quartz.dll is loaded. If you /// wish to use a file other than these defaults, you must define the system /// property 'quartz.properties' to point to the file you want. /// </para> /// <para> /// See the sample properties that are distributed with Quartz for /// information about the various settings available within the file. /// </para> /// <para> /// Alternatively, you can explicitly Initialize the factory by calling one of /// the <see cref="Initialize()" /> methods before calling <see cref="GetScheduler()" />. /// </para> /// <para> /// Instances of the specified <see cref="IJobStore" />, /// <see cref="IThreadPool" />, classes will be created /// by name, and then any additional properties specified for them in the config /// file will be set on the instance by calling an equivalent 'set' method. For /// example if the properties file contains the property 'quartz.jobStore. /// myProp = 10' then after the JobStore class has been instantiated, the property /// 'MyProp' will be set with the value. Type conversion to primitive CLR types /// (int, long, float, double, boolean, enum and string) are performed before calling /// the property's setter method. /// </para> /// </remarks> /// <author>James House</author> /// <author>Anthony Eden</author> /// <author>Mohammad Rezaei</author> /// <author>Marko Lahma (.NET)</author> public class StdSchedulerFactory : ISchedulerFactory { private const string ConfigurationKeyPrefix = "quartz."; private const string ConfigurationKeyPrefixServer = "quartz.server"; public const string ConfigurationSectionName = "quartz"; public const string PropertiesFile = "quartz.config"; public const string PropertySchedulerInstanceName = "quartz.scheduler.instanceName"; public const string PropertySchedulerInstanceId = "quartz.scheduler.instanceId"; public const string PropertySchedulerInstanceIdGeneratorPrefix = "quartz.scheduler.instanceIdGenerator"; public const string PropertySchedulerInstanceIdGeneratorType = PropertySchedulerInstanceIdGeneratorPrefix + ".type"; public const string PropertySchedulerThreadName = "quartz.scheduler.threadName"; public const string PropertySchedulerBatchTimeWindow = "quartz.scheduler.batchTriggerAcquisitionFireAheadTimeWindow"; public const string PropertySchedulerMaxBatchSize = "quartz.scheduler.batchTriggerAcquisitionMaxCount"; public const string PropertySchedulerExporterPrefix = "quartz.scheduler.exporter"; public const string PropertySchedulerExporterType = PropertySchedulerExporterPrefix + ".type"; public const string PropertySchedulerProxy = "quartz.scheduler.proxy"; public const string PropertySchedulerProxyType = "quartz.scheduler.proxy.type"; public const string PropertySchedulerIdleWaitTime = "quartz.scheduler.idleWaitTime"; public const string PropertySchedulerDbFailureRetryInterval = "quartz.scheduler.dbFailureRetryInterval"; public const string PropertySchedulerMakeSchedulerThreadDaemon = "quartz.scheduler.makeSchedulerThreadDaemon"; public const string PropertySchedulerTypeLoadHelperType = "quartz.scheduler.typeLoadHelper.type"; public const string PropertySchedulerJobFactoryType = "quartz.scheduler.jobFactory.type"; public const string PropertySchedulerJobFactoryPrefix = "quartz.scheduler.jobFactory"; public const string PropertySchedulerInterruptJobsOnShutdown = "quartz.scheduler.interruptJobsOnShutdown"; public const string PropertySchedulerInterruptJobsOnShutdownWithWait = "quartz.scheduler.interruptJobsOnShutdownWithWait"; public const string PropertySchedulerContextPrefix = "quartz.context.key"; public const string PropertyThreadPoolPrefix = "quartz.threadPool"; public const string PropertyThreadPoolType = "quartz.threadPool.type"; public const string PropertyJobStorePrefix = "quartz.jobStore"; public const string PropertyJobStoreLockHandlerPrefix = PropertyJobStorePrefix + ".lockHandler"; public const string PropertyJobStoreLockHandlerType = PropertyJobStoreLockHandlerPrefix + ".type"; public const string PropertyTablePrefix = "tablePrefix"; public const string PropertySchedulerName = "schedName"; public const string PropertyJobStoreType = "quartz.jobStore.type"; public const string PropertyDataSourcePrefix = "quartz.dataSource"; public const string PropertyDbProvider = "quartz.dbprovider"; public const string PropertyDbProviderType = "connectionProvider.type"; public const string PropertyDataSourceProvider = "provider"; public const string PropertyDataSourceConnectionString = "connectionString"; public const string PropertyDataSourceConnectionStringName = "connectionStringName"; public const string PropertyPluginPrefix = "quartz.plugin"; public const string PropertyPluginType = "type"; public const string PropertyJobListenerPrefix = "quartz.jobListener"; public const string PropertyTriggerListenerPrefix = "quartz.triggerListener"; public const string PropertyListenerType = "type"; public const string DefaultInstanceId = "NON_CLUSTERED"; public const string PropertyCheckConfiguration = "quartz.checkConfiguration"; public const string AutoGenerateInstanceId = "AUTO"; public const string PropertyThreadExecutor = "quartz.threadExecutor"; public const string PropertyThreadExecutorType= "quartz.threadExecutor.type"; public const string PropertyObjectSerializer = "quartz.serializer"; public const string SystemPropertyAsInstanceId = "SYS_PROP"; private SchedulerException initException; private PropertiesParser cfg; private static readonly ILog log = LogManager.GetLogger(typeof (StdSchedulerFactory)); private string SchedulerName { get { return cfg.GetStringProperty(PropertySchedulerInstanceName, "QuartzScheduler"); } } protected ILog Log { get { return log; } } /// <summary> /// Returns a handle to the default Scheduler, creating it if it does not /// yet exist. /// </summary> /// <seealso cref="Initialize()"> /// </seealso> public static IScheduler GetDefaultScheduler() { StdSchedulerFactory fact = new StdSchedulerFactory(); return fact.GetScheduler(); } /// <summary> <para> /// Returns a handle to all known Schedulers (made by any /// StdSchedulerFactory instance.). /// </para> /// </summary> public virtual ICollection<IScheduler> AllSchedulers { get { return SchedulerRepository.Instance.LookupAll(); } } /// <summary> /// Initializes a new instance of the <see cref="StdSchedulerFactory"/> class. /// </summary> public StdSchedulerFactory() { } /// <summary> /// Initializes a new instance of the <see cref="StdSchedulerFactory"/> class. /// </summary> /// <param name="props">The props.</param> public StdSchedulerFactory(NameValueCollection props) { Initialize(props); } /// <summary> /// Initialize the <see cref="ISchedulerFactory" />. /// </summary> /// <remarks> /// By default a properties file named "quartz.properties" is loaded from /// the 'current working directory'. If that fails, then the /// "quartz.properties" file located (as an embedded resource) in the Quartz.NET /// assembly is loaded. If you wish to use a file other than these defaults, /// you must define the system property 'quartz.properties' to point to /// the file you want. /// </remarks> public void Initialize() { // short-circuit if already initialized if (cfg != null) { return; } if (initException != null) { throw initException; } NameValueCollection props = (NameValueCollection) ConfigurationManager.GetSection(ConfigurationSectionName); string requestedFile = QuartzEnvironment.GetEnvironmentVariable(PropertiesFile); string propFileName = requestedFile != null && requestedFile.Trim().Length > 0 ? requestedFile : "~/quartz.config"; // check for specials try { propFileName = FileUtil.ResolveFile(propFileName); } catch (SecurityException) { log.WarnFormat("Unable to resolve file path '{0}' due to security exception, probably running under medium trust"); propFileName = "quartz.config"; } if (props == null && File.Exists(propFileName)) { // file system try { PropertiesParser pp = PropertiesParser.ReadFromFileResource(propFileName); props = pp.UnderlyingProperties; Log.Info(string.Format("Quartz.NET properties loaded from configuration file '{0}'", propFileName)); } catch (Exception ex) { Log.Error("Could not load properties for Quartz from file {0}: {1}".FormatInvariant(propFileName, ex.Message), ex); } } if (props == null) { // read from assembly try { PropertiesParser pp = PropertiesParser.ReadFromEmbeddedAssemblyResource("Quartz.quartz.config"); props = pp.UnderlyingProperties; Log.Info("Default Quartz.NET properties loaded from embedded resource file"); } catch (Exception ex) { Log.Error("Could not load default properties for Quartz from Quartz assembly: {0}".FormatInvariant(ex.Message), ex); } } if (props == null) { throw new SchedulerConfigException( @"Could not find <quartz> configuration section from your application config or load default configuration from assembly. Please add configuration to your application config file to correctly initialize Quartz."); } Initialize(OverrideWithSysProps(props)); } /// <summary> /// Creates a new name value collection and overrides its values /// with system values (environment variables). /// </summary> /// <param name="props">The base properties to override.</param> /// <returns>A new NameValueCollection instance.</returns> private static NameValueCollection OverrideWithSysProps(NameValueCollection props) { NameValueCollection retValue = new NameValueCollection(props); IDictionary<string, string> vars = QuartzEnvironment.GetEnvironmentVariables(); foreach (string key in vars.Keys) { retValue.Set(key, vars[key]); } return retValue; } /// <summary> /// Initialize the <see cref="ISchedulerFactory" /> with /// the contents of the given key value collection object. /// </summary> public virtual void Initialize(NameValueCollection props) { cfg = new PropertiesParser(props); ValidateConfiguration(); } protected virtual void ValidateConfiguration() { if (!cfg.GetBooleanProperty(PropertyCheckConfiguration, true)) { // should not validate return; } // determine currently supported configuration keys via reflection List<string> supportedKeys = new List<string>(); List<FieldInfo> fields = new List<FieldInfo>(GetType().GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)); // choose constant string fields fields = fields.FindAll(field => field.FieldType == typeof (string)); // read value from each field foreach (FieldInfo field in fields) { string value = (string) field.GetValue(null); if (value != null && value.StartsWith(ConfigurationKeyPrefix) && value != ConfigurationKeyPrefix) { supportedKeys.Add(value); } } // now check against allowed foreach (string configurationKey in cfg.UnderlyingProperties.AllKeys) { if (!configurationKey.StartsWith(ConfigurationKeyPrefix) || configurationKey.StartsWith(ConfigurationKeyPrefixServer)) { // don't bother if truly unknown property continue; } bool isMatch = false; foreach (string supportedKey in supportedKeys) { if (configurationKey.StartsWith(supportedKey, StringComparison.InvariantCulture)) { isMatch = true; break; } } if (!isMatch) { throw new SchedulerConfigException("Unknown configuration property '" + configurationKey + "'"); } } } /// <summary> </summary> private IScheduler Instantiate() { if (cfg == null) { Initialize(); } if (initException != null) { throw initException; } ISchedulerExporter exporter = null; IJobStore js; IThreadPool tp; QuartzScheduler qs = null; IDbConnectionManager dbMgr = null; Type instanceIdGeneratorType = null; NameValueCollection tProps; bool autoId = false; TimeSpan idleWaitTime = TimeSpan.Zero; TimeSpan dbFailureRetry = TimeSpan.FromSeconds(15); IThreadExecutor threadExecutor; SchedulerRepository schedRep = SchedulerRepository.Instance; // Get Scheduler Properties // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ string schedName = cfg.GetStringProperty(PropertySchedulerInstanceName, "QuartzScheduler"); string threadName = cfg.GetStringProperty(PropertySchedulerThreadName, "{0}_QuartzSchedulerThread".FormatInvariant(schedName)); string schedInstId = cfg.GetStringProperty(PropertySchedulerInstanceId, DefaultInstanceId); if (schedInstId.Equals(AutoGenerateInstanceId)) { autoId = true; instanceIdGeneratorType = LoadType(cfg.GetStringProperty(PropertySchedulerInstanceIdGeneratorType)) ?? typeof(SimpleInstanceIdGenerator); } else if (schedInstId.Equals(SystemPropertyAsInstanceId)) { autoId = true; instanceIdGeneratorType = typeof(SystemPropertyInstanceIdGenerator); } Type typeLoadHelperType = LoadType(cfg.GetStringProperty(PropertySchedulerTypeLoadHelperType)); Type jobFactoryType = LoadType(cfg.GetStringProperty(PropertySchedulerJobFactoryType, null)); idleWaitTime = cfg.GetTimeSpanProperty(PropertySchedulerIdleWaitTime, idleWaitTime); if (idleWaitTime > TimeSpan.Zero && idleWaitTime < TimeSpan.FromMilliseconds(1000)) { throw new SchedulerException("quartz.scheduler.idleWaitTime of less than 1000ms is not legal."); } dbFailureRetry = cfg.GetTimeSpanProperty(PropertySchedulerDbFailureRetryInterval, dbFailureRetry); if (dbFailureRetry < TimeSpan.Zero) { throw new SchedulerException(PropertySchedulerDbFailureRetryInterval + " of less than 0 ms is not legal."); } bool makeSchedulerThreadDaemon = cfg.GetBooleanProperty(PropertySchedulerMakeSchedulerThreadDaemon); long batchTimeWindow = cfg.GetLongProperty(PropertySchedulerBatchTimeWindow, 0L); int maxBatchSize = cfg.GetIntProperty(PropertySchedulerMaxBatchSize, 1); bool interruptJobsOnShutdown = cfg.GetBooleanProperty(PropertySchedulerInterruptJobsOnShutdown, false); bool interruptJobsOnShutdownWithWait = cfg.GetBooleanProperty(PropertySchedulerInterruptJobsOnShutdownWithWait, false); NameValueCollection schedCtxtProps = cfg.GetPropertyGroup(PropertySchedulerContextPrefix, true); bool proxyScheduler = cfg.GetBooleanProperty(PropertySchedulerProxy, false); // Create type load helper ITypeLoadHelper loadHelper; try { loadHelper = ObjectUtils.InstantiateType<ITypeLoadHelper>(typeLoadHelperType ?? typeof(SimpleTypeLoadHelper)); } catch (Exception e) { throw new SchedulerConfigException("Unable to instantiate type load helper: {0}".FormatInvariant(e.Message), e); } loadHelper.Initialize(); // If Proxying to remote scheduler, short-circuit here... // ~~~~~~~~~~~~~~~~~~ if (proxyScheduler) { if (autoId) { schedInstId = DefaultInstanceId; } Type proxyType = loadHelper.LoadType(cfg.GetStringProperty(PropertySchedulerProxyType)) ?? typeof(RemotingSchedulerProxyFactory); IRemotableSchedulerProxyFactory factory; try { factory = ObjectUtils.InstantiateType<IRemotableSchedulerProxyFactory>(proxyType); ObjectUtils.SetObjectProperties(factory, cfg.GetPropertyGroup(PropertySchedulerProxy, true)); } catch (Exception e) { initException = new SchedulerException("Remotable proxy factory '{0}' could not be instantiated.".FormatInvariant(proxyType), e); throw initException; } string uid = QuartzSchedulerResources.GetUniqueIdentifier(schedName, schedInstId); RemoteScheduler remoteScheduler = new RemoteScheduler(uid, factory); schedRep.Bind(remoteScheduler); return remoteScheduler; } IJobFactory jobFactory = null; if (jobFactoryType != null) { try { jobFactory = ObjectUtils.InstantiateType<IJobFactory>(jobFactoryType); } catch (Exception e) { throw new SchedulerConfigException("Unable to Instantiate JobFactory: {0}".FormatInvariant(e.Message), e); } tProps = cfg.GetPropertyGroup(PropertySchedulerJobFactoryPrefix, true); try { ObjectUtils.SetObjectProperties(jobFactory, tProps); } catch (Exception e) { initException = new SchedulerException("JobFactory of type '{0}' props could not be configured.".FormatInvariant(jobFactoryType), e); throw initException; } } IInstanceIdGenerator instanceIdGenerator = null; if (instanceIdGeneratorType != null) { try { instanceIdGenerator = ObjectUtils.InstantiateType<IInstanceIdGenerator>(instanceIdGeneratorType); } catch (Exception e) { throw new SchedulerConfigException("Unable to Instantiate InstanceIdGenerator: {0}".FormatInvariant(e.Message), e); } tProps = cfg.GetPropertyGroup(PropertySchedulerInstanceIdGeneratorPrefix, true); try { ObjectUtils.SetObjectProperties(instanceIdGenerator, tProps); } catch (Exception e) { initException = new SchedulerException("InstanceIdGenerator of type '{0}' props could not be configured.".FormatInvariant(instanceIdGeneratorType), e); throw initException; } } // Get ThreadPool Properties // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Type tpType = loadHelper.LoadType(cfg.GetStringProperty(PropertyThreadPoolType)) ?? typeof(SimpleThreadPool); try { tp = ObjectUtils.InstantiateType<IThreadPool>(tpType); } catch (Exception e) { initException = new SchedulerException("ThreadPool type '{0}' could not be instantiated.".FormatInvariant(tpType), e); throw initException; } tProps = cfg.GetPropertyGroup(PropertyThreadPoolPrefix, true); try { ObjectUtils.SetObjectProperties(tp, tProps); } catch (Exception e) { initException = new SchedulerException("ThreadPool type '{0}' props could not be configured.".FormatInvariant(tpType), e); throw initException; } // Set up any DataSources // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IList<string> dsNames = cfg.GetPropertyGroups(PropertyDataSourcePrefix); foreach (string dataSourceName in dsNames) { string datasourceKey = "{0}.{1}".FormatInvariant(PropertyDataSourcePrefix, dataSourceName); NameValueCollection propertyGroup = cfg.GetPropertyGroup(datasourceKey, true); PropertiesParser pp = new PropertiesParser(propertyGroup); Type cpType = loadHelper.LoadType(pp.GetStringProperty(PropertyDbProviderType, null)); // custom connectionProvider... if (cpType != null) { IDbProvider cp; try { cp = ObjectUtils.InstantiateType<IDbProvider>(cpType); } catch (Exception e) { initException = new SchedulerException("ConnectionProvider of type '{0}' could not be instantiated.".FormatInvariant(cpType), e); throw initException; } try { // remove the type name, so it isn't attempted to be set pp.UnderlyingProperties.Remove(PropertyDbProviderType); ObjectUtils.SetObjectProperties(cp, pp.UnderlyingProperties); cp.Initialize(); } catch (Exception e) { initException = new SchedulerException("ConnectionProvider type '{0}' props could not be configured.".FormatInvariant(cpType), e); throw initException; } dbMgr = DBConnectionManager.Instance; dbMgr.AddConnectionProvider(dataSourceName, cp); } else { string dsProvider = pp.GetStringProperty(PropertyDataSourceProvider, null); string dsConnectionString = pp.GetStringProperty(PropertyDataSourceConnectionString, null); string dsConnectionStringName = pp.GetStringProperty(PropertyDataSourceConnectionStringName, null); if (dsConnectionString == null && !String.IsNullOrEmpty(dsConnectionStringName)) { ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[dsConnectionStringName]; if (connectionStringSettings == null) { initException = new SchedulerException("Named connection string '{0}' not found for DataSource: {1}".FormatInvariant(dsConnectionStringName, dataSourceName)); throw initException; } dsConnectionString = connectionStringSettings.ConnectionString; } if (dsProvider == null) { initException = new SchedulerException("Provider not specified for DataSource: {0}".FormatInvariant(dataSourceName)); throw initException; } if (dsConnectionString == null) { initException = new SchedulerException("Connection string not specified for DataSource: {0}".FormatInvariant(dataSourceName)); throw initException; } try { DbProvider dbp = new DbProvider(dsProvider, dsConnectionString); dbp.Initialize(); dbMgr = DBConnectionManager.Instance; dbMgr.AddConnectionProvider(dataSourceName, dbp); } catch (Exception exception) { initException = new SchedulerException("Could not Initialize DataSource: {0}".FormatInvariant(dataSourceName), exception); throw initException; } } } // Get object serializer properties // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IObjectSerializer objectSerializer; string objectSerializerType = cfg.GetStringProperty("quartz.serializer.type"); if (objectSerializerType != null) { tProps = cfg.GetPropertyGroup(PropertyObjectSerializer, true); try { objectSerializer = ObjectUtils.InstantiateType<IObjectSerializer>(loadHelper.LoadType(objectSerializerType)); log.Info("Using custom implementation for object serializer: " + objectSerializerType); ObjectUtils.SetObjectProperties(objectSerializer, tProps); } catch (Exception e) { initException = new SchedulerException("Object serializer type '" + objectSerializerType + "' could not be instantiated.", e); throw initException; } } else { log.Info("Using default implementation for object serializer"); objectSerializer = new DefaultObjectSerializer(); } // Get JobStore Properties // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Type jsType = loadHelper.LoadType(cfg.GetStringProperty(PropertyJobStoreType)); try { js = ObjectUtils.InstantiateType<IJobStore>(jsType ?? typeof(RAMJobStore)); } catch (Exception e) { initException = new SchedulerException("JobStore of type '{0}' could not be instantiated.".FormatInvariant(jsType), e); throw initException; } SchedulerDetailsSetter.SetDetails(js, schedName, schedInstId); tProps = cfg.GetPropertyGroup(PropertyJobStorePrefix, true, new string[] {PropertyJobStoreLockHandlerPrefix}); try { ObjectUtils.SetObjectProperties(js, tProps); } catch (Exception e) { initException = new SchedulerException("JobStore type '{0}' props could not be configured.".FormatInvariant(jsType), e); throw initException; } JobStoreSupport jobStoreSupport = js as JobStoreSupport; if (jobStoreSupport != null) { // Install custom lock handler (Semaphore) Type lockHandlerType = loadHelper.LoadType(cfg.GetStringProperty(PropertyJobStoreLockHandlerType)); if (lockHandlerType != null) { try { ISemaphore lockHandler; ConstructorInfo cWithDbProvider = lockHandlerType.GetConstructor(new Type[] {typeof (DbProvider)}); if (cWithDbProvider != null) { // takes db provider IDbProvider dbProvider = DBConnectionManager.Instance.GetDbProvider(jobStoreSupport.DataSource); lockHandler = (ISemaphore) cWithDbProvider.Invoke(new object[] { dbProvider }); } else { lockHandler = ObjectUtils.InstantiateType<ISemaphore>(lockHandlerType); } tProps = cfg.GetPropertyGroup(PropertyJobStoreLockHandlerPrefix, true); // If this lock handler requires the table prefix, add it to its properties. if (lockHandler is ITablePrefixAware) { tProps[PropertyTablePrefix] = jobStoreSupport.TablePrefix; tProps[PropertySchedulerName] = schedName; } try { ObjectUtils.SetObjectProperties(lockHandler, tProps); } catch (Exception e) { initException = new SchedulerException("JobStore LockHandler type '{0}' props could not be configured.".FormatInvariant(lockHandlerType), e); throw initException; } jobStoreSupport.LockHandler = lockHandler; Log.Info("Using custom data access locking (synchronization): " + lockHandlerType); } catch (Exception e) { initException = new SchedulerException("JobStore LockHandler type '{0}' could not be instantiated.".FormatInvariant(lockHandlerType), e); throw initException; } } } // Set up any SchedulerPlugins // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IList<string> pluginNames = cfg.GetPropertyGroups(PropertyPluginPrefix); ISchedulerPlugin[] plugins = new ISchedulerPlugin[pluginNames.Count]; for (int i = 0; i < pluginNames.Count; i++) { NameValueCollection pp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyPluginPrefix, pluginNames[i]), true); string plugInType = pp[PropertyPluginType]; if (plugInType == null) { initException = new SchedulerException("SchedulerPlugin type not specified for plugin '{0}'".FormatInvariant(pluginNames[i])); throw initException; } ISchedulerPlugin plugin; try { plugin = ObjectUtils.InstantiateType<ISchedulerPlugin>(LoadType(plugInType)); } catch (Exception e) { initException = new SchedulerException("SchedulerPlugin of type '{0}' could not be instantiated.".FormatInvariant(plugInType), e); throw initException; } try { ObjectUtils.SetObjectProperties(plugin, pp); } catch (Exception e) { initException = new SchedulerException("JobStore SchedulerPlugin '{0}' props could not be configured.".FormatInvariant(plugInType), e); throw initException; } plugins[i] = plugin; } // Set up any JobListeners // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IList<string> jobListenerNames = cfg.GetPropertyGroups(PropertyJobListenerPrefix); IJobListener[] jobListeners = new IJobListener[jobListenerNames.Count]; for (int i = 0; i < jobListenerNames.Count; i++) { NameValueCollection lp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyJobListenerPrefix, jobListenerNames[i]), true); string listenerType = lp[PropertyListenerType]; if (listenerType == null) { initException = new SchedulerException("JobListener type not specified for listener '{0}'".FormatInvariant(jobListenerNames[i])); throw initException; } IJobListener listener; try { listener = ObjectUtils.InstantiateType<IJobListener>(loadHelper.LoadType(listenerType)); } catch (Exception e) { initException = new SchedulerException("JobListener of type '{0}' could not be instantiated.".FormatInvariant(listenerType), e); throw initException; } try { PropertyInfo nameProperty = listener.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance); if (nameProperty != null && nameProperty.CanWrite) { nameProperty.GetSetMethod().Invoke(listener, new object[] {jobListenerNames[i]}); } ObjectUtils.SetObjectProperties(listener, lp); } catch (Exception e) { initException = new SchedulerException("JobListener '{0}' props could not be configured.".FormatInvariant(listenerType), e); throw initException; } jobListeners[i] = listener; } // Set up any TriggerListeners // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IList<string> triggerListenerNames = cfg.GetPropertyGroups(PropertyTriggerListenerPrefix); ITriggerListener[] triggerListeners = new ITriggerListener[triggerListenerNames.Count]; for (int i = 0; i < triggerListenerNames.Count; i++) { NameValueCollection lp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyTriggerListenerPrefix, triggerListenerNames[i]), true); string listenerType = lp[PropertyListenerType]; if (listenerType == null) { initException = new SchedulerException("TriggerListener type not specified for listener '{0}'".FormatInvariant(triggerListenerNames[i])); throw initException; } ITriggerListener listener; try { listener = ObjectUtils.InstantiateType<ITriggerListener>(loadHelper.LoadType(listenerType)); } catch (Exception e) { initException = new SchedulerException("TriggerListener of type '{0}' could not be instantiated.".FormatInvariant(listenerType), e); throw initException; } try { PropertyInfo nameProperty = listener.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance); if (nameProperty != null && nameProperty.CanWrite) { nameProperty.GetSetMethod().Invoke(listener, new object[] {triggerListenerNames[i]}); } ObjectUtils.SetObjectProperties(listener, lp); } catch (Exception e) { initException = new SchedulerException("TriggerListener '{0}' props could not be configured.".FormatInvariant(listenerType), e); throw initException; } triggerListeners[i] = listener; } // Get exporter // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ string exporterType = cfg.GetStringProperty(PropertySchedulerExporterType, null); if (exporterType != null) { try { exporter = ObjectUtils.InstantiateType<ISchedulerExporter>(loadHelper.LoadType(exporterType)); } catch (Exception e) { initException = new SchedulerException("Scheduler exporter of type '{0}' could not be instantiated.".FormatInvariant(exporterType), e); throw initException; } tProps = cfg.GetPropertyGroup(PropertySchedulerExporterPrefix, true); try { ObjectUtils.SetObjectProperties(exporter, tProps); } catch (Exception e) { initException = new SchedulerException("Scheduler exporter type '{0}' props could not be configured.".FormatInvariant(exporterType), e); throw initException; } } bool tpInited = false; bool qsInited = false; // Get ThreadExecutor Properties // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ string threadExecutorClass = cfg.GetStringProperty(PropertyThreadExecutorType); if (threadExecutorClass != null) { tProps = cfg.GetPropertyGroup(PropertyThreadExecutor, true); try { threadExecutor = ObjectUtils.InstantiateType<IThreadExecutor>(loadHelper.LoadType(threadExecutorClass)); log.Info("Using custom implementation for ThreadExecutor: " + threadExecutorClass); ObjectUtils.SetObjectProperties(threadExecutor, tProps); } catch (Exception e) { initException = new SchedulerException( "ThreadExecutor class '" + threadExecutorClass + "' could not be instantiated.", e); throw initException; } } else { log.Info("Using default implementation for ThreadExecutor"); threadExecutor = new DefaultThreadExecutor(); } // Fire everything up // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ try { IJobRunShellFactory jrsf = new StdJobRunShellFactory(); if (autoId) { try { schedInstId = DefaultInstanceId; if (js.Clustered) { schedInstId = instanceIdGenerator.GenerateInstanceId(); } } catch (Exception e) { Log.Error("Couldn't generate instance Id!", e); throw new SystemException("Cannot run without an instance id."); } } jobStoreSupport = js as JobStoreSupport; if (jobStoreSupport != null) { jobStoreSupport.DbRetryInterval = dbFailureRetry; jobStoreSupport.ThreadExecutor = threadExecutor; // object serializer jobStoreSupport.ObjectSerializer = objectSerializer; } QuartzSchedulerResources rsrcs = new QuartzSchedulerResources(); rsrcs.Name = schedName; rsrcs.ThreadName = threadName; rsrcs.InstanceId = schedInstId; rsrcs.JobRunShellFactory = jrsf; rsrcs.MakeSchedulerThreadDaemon = makeSchedulerThreadDaemon; rsrcs.BatchTimeWindow = TimeSpan.FromMilliseconds(batchTimeWindow); rsrcs.MaxBatchSize = maxBatchSize; rsrcs.InterruptJobsOnShutdown = interruptJobsOnShutdown; rsrcs.InterruptJobsOnShutdownWithWait = interruptJobsOnShutdownWithWait; rsrcs.SchedulerExporter = exporter; SchedulerDetailsSetter.SetDetails(tp, schedName, schedInstId); rsrcs.ThreadExecutor = threadExecutor; threadExecutor.Initialize(); rsrcs.ThreadPool = tp; tp.Initialize(); tpInited = true; rsrcs.JobStore = js; // add plugins foreach (ISchedulerPlugin plugin in plugins) { rsrcs.AddSchedulerPlugin(plugin); } qs = new QuartzScheduler(rsrcs, idleWaitTime); qsInited = true; // Create Scheduler ref... IScheduler sched = Instantiate(rsrcs, qs); // set job factory if specified if (jobFactory != null) { qs.JobFactory = jobFactory; } // Initialize plugins now that we have a Scheduler instance. for (int i = 0; i < plugins.Length; i++) { plugins[i].Initialize(pluginNames[i], sched); } // add listeners foreach (IJobListener listener in jobListeners) { qs.ListenerManager.AddJobListener(listener, EverythingMatcher<JobKey>.AllJobs()); } foreach (ITriggerListener listener in triggerListeners) { qs.ListenerManager.AddTriggerListener(listener, EverythingMatcher<TriggerKey>.AllTriggers()); } // set scheduler context data... foreach (string key in schedCtxtProps) { string val = schedCtxtProps.Get(key); sched.Context.Put(key, val); } // fire up job store, and runshell factory js.InstanceId = schedInstId; js.InstanceName = schedName; js.ThreadPoolSize = tp.PoolSize; js.Initialize(loadHelper, qs.SchedulerSignaler); jrsf.Initialize(sched); qs.Initialize(); Log.Info("Quartz scheduler '{0}' initialized".FormatInvariant(sched.SchedulerName)); Log.Info("Quartz scheduler version: {0}".FormatInvariant(qs.Version)); // prevents the repository from being garbage collected qs.AddNoGCObject(schedRep); // prevents the db manager from being garbage collected if (dbMgr != null) { qs.AddNoGCObject(dbMgr); } schedRep.Bind(sched); return sched; } catch (SchedulerException) { ShutdownFromInstantiateException(tp, qs, tpInited, qsInited); throw; } catch { ShutdownFromInstantiateException(tp, qs, tpInited, qsInited); throw; } } private void ShutdownFromInstantiateException(IThreadPool tp, QuartzScheduler qs, bool tpInited, bool qsInited) { try { if (qsInited) { qs.Shutdown(false); } else if (tpInited) { tp.Shutdown(false); } } catch (Exception e) { Log.Error("Got another exception while shutting down after instantiation exception", e); } } protected virtual IScheduler Instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler qs) { IScheduler sched = new StdScheduler(qs); return sched; } /// <summary> /// Needed while loadhelper is not constructed. /// </summary> /// <param name="typeName"></param> /// <returns></returns> protected virtual Type LoadType(string typeName) { if (string.IsNullOrEmpty(typeName)) { return null; } return Type.GetType(typeName, true); } /// <summary> /// Returns a handle to the Scheduler produced by this factory. /// </summary> /// <remarks> /// If one of the <see cref="Initialize()" /> methods has not be previously /// called, then the default (no-arg) <see cref="Initialize()" /> method /// will be called by this method. /// </remarks> public virtual IScheduler GetScheduler() { if (cfg == null) { Initialize(); } SchedulerRepository schedRep = SchedulerRepository.Instance; IScheduler sched = schedRep.Lookup(SchedulerName); if (sched != null) { if (sched.IsShutdown) { schedRep.Remove(SchedulerName); } else { return sched; } } sched = Instantiate(); return sched; } /// <summary> <para> /// Returns a handle to the Scheduler with the given name, if it exists (if /// it has already been instantiated). /// </para> /// </summary> public virtual IScheduler GetScheduler(string schedName) { return SchedulerRepository.Instance.Lookup(schedName); } } }
// // 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. // using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Azure.Management.HDInsight.Job { /// <summary> /// Operations for managing jobs against HDInsight clusters. /// </summary> public partial class JobOperationsExtensions { /// <summary> /// Gets the task log summary from execution of a jobDetails. /// </summary> /// <param name="jobId"> /// Required. The id of the job. /// </param> /// <param name="targetDirectory"> /// Required. The directory in which to download the logs to. /// </param> /// <param name="storageAccountName"> /// The name of the storage account /// </param> /// <param name="storageAccountKey"> /// The default storage account key. /// </param> /// <param name="defaultContainer"> /// The default container. /// </param> /// Cancellation token. /// </param> /// <returns> /// /// </returns> public static void DownloadJobTaskLogs(this IJobOperations operations, string jobId, string targetDirectory, string storageAccountName, string storageAccountKey, string defaultContainer) { Task.Factory.StartNew( (object s) => ((IJobOperations) s).DownloadJobTaskLogsAsync(jobId, targetDirectory, storageAccountName, storageAccountKey, defaultContainer), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default) .Unwrap() .GetAwaiter() .GetResult(); } /// <summary> /// Gets the task log summary from execution of a jobDetails. /// </summary> /// <param name="jobId"> /// Required. The id of the job. /// </param> /// <param name="targetDirectory"> /// Required. The directory in which to download the logs to. /// </param> /// <param name="storageAccountName"> /// The name of the storage account. /// </param> /// <param name="storageAccountKey"> /// The default storage account key. /// </param> /// <param name="defaultContainer"> /// The default container. /// </param> /// Cancellation token. /// </param> /// <returns> /// /// </returns> public static Task DownloadJobTaskLogsAsync(this IJobOperations operations, string jobId, string targetDirectory, string storageAccountName, string storageAccountKey, string defaultContainer) { return operations.DownloadJobTaskLogsAsync(jobId, targetDirectory, storageAccountName, storageAccountKey, defaultContainer, CancellationToken.None); } /// <summary> /// Gets the output from the execution of an individual jobDetails. /// </summary> /// <param name="jobId"> /// Required. The id of the job. /// </param> /// <param name="defaultContainer"> /// Required. The default container. /// </param> /// <param name="storageAccountName"> /// Required. The storage account the container lives on. /// </param> /// <returns> /// The output of an individual jobDetails by jobId. /// </returns> public static Stream GetJobOutput(this IJobOperations operations, string jobId, string storageAccountName, string storageAccountKey, string defaultContainer) { return Task.Factory.StartNew( (object s) => ((IJobOperations) s).GetJobOutputAsync(jobId, storageAccountName, storageAccountKey, defaultContainer), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default) .Unwrap() .GetAwaiter() .GetResult(); } /// <summary> /// Gets the output from the execution of an individual jobDetails. /// </summary> /// <param name="operations"></param> /// <param name="jobId"> /// Required. The id of the job. /// </param> /// <param name="storageAccountName"> /// Required. The storage account the container lives on. /// </param> /// <param name="storageAccountKey"></param> /// <param name="defaultContainer"> /// Required. The default container. /// </param> /// <returns> /// The output of an individual jobDetails by jobId. /// </returns> public static Task<Stream> GetJobOutputAsync(this IJobOperations operations, string jobId, string storageAccountName, string storageAccountKey, string defaultContainer) { return operations.GetJobOutputAsync(jobId, storageAccountName, storageAccountKey, defaultContainer, CancellationToken.None); } /// <summary> /// Gets the error logs from the execution of an individual jobDetails. /// </summary> /// <param name="jobId"> /// Required. The id of the job. /// </param> /// <param name="defaultContainer"> /// Required. The default container. /// </param> /// <param name="storageAccountName"> /// Required. The storage account the container lives on. /// </param> /// <returns> /// The error logs of an individual jobDetails by jobId. /// </returns> public static Stream GetJobErrorLogs(this IJobOperations operations, string jobId, string storageAccountName, string storageAccountKey, string defaultContainer) { return Task.Factory.StartNew( (object s) => ((IJobOperations)s).GetJobErrorLogsAsync(jobId, storageAccountName, storageAccountKey, defaultContainer), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default) .Unwrap() .GetAwaiter() .GetResult(); } /// <summary> /// Gets the error logs from the execution of an individual jobDetails. /// </summary> /// <param name="jobId"> /// Required. The id of the job. /// </param> /// <param name="defaultContainer"> /// Required. The default container. /// </param> /// <param name="storageAccountName"> /// Required. The storage account the container lives on. /// </param> /// <returns> /// The error logs of an individual jobDetails by jobId. /// </returns> public static Task<Stream> GetJobErrorLogsAsync(this IJobOperations operations, string jobId, string storageAccountName, string storageAccountKey, string defaultContainer) { return operations.GetJobErrorLogsAsync(jobId, storageAccountName, storageAccountKey, defaultContainer, CancellationToken.None); } /// <summary> /// Gets the task logs from the execution of an individual jobDetails. /// </summary> /// <param name="jobId"> /// Required. The id of the job. /// </param> /// <param name="defaultContainer"> /// Required. The default container. /// </param> /// <param name="storageAccountName"> /// Required. The storage account the container lives on. /// </param> /// <returns> /// The task logs of an individual jobDetails by jobId. /// </returns> public static Stream GetJobTaskLogSummary(this IJobOperations operations, string jobId, string storageAccountName, string storageAccountKey, string defaultContainer) { return Task.Factory.StartNew( (object s) => ((IJobOperations)s).GetJobTaskLogSummaryAsync(jobId, storageAccountName, storageAccountKey, defaultContainer), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default) .Unwrap() .GetAwaiter() .GetResult(); } /// <summary> /// Gets the task logs from the execution of an individual jobDetails. /// </summary> /// <param name="jobId"> /// Required. The id of the job. /// </param> /// <param name="defaultContainer"> /// Required. The default container. /// </param> /// <param name="storageAccountName"> /// Required. The storage account the container lives on. /// </param> /// <returns> /// The task logs of an individual jobDetails by jobId. /// </returns> public static Task<Stream> GetJobTaskLogSummaryAsync(this IJobOperations operations, string jobId, string storageAccountName, string storageAccountKey, string defaultContainer) { return operations.GetJobTaskLogSummaryAsync(jobId, storageAccountName, storageAccountKey, defaultContainer, CancellationToken.None); } } }
/* ************************************************************************* ** Custom classes used by C# ************************************************************************* */ using System; using System.Diagnostics; using System.IO; //#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) //using System.Management; //#endif using System.Text; using System.Text.RegularExpressions; using System.Threading; using i64 = System.Int64; using u32 = System.UInt32; using time_t = System.Int64; namespace Community.CsharpSqlite { using sqlite3_value = Sqlite3.Mem; public partial class Sqlite3 { static int atoi( byte[] inStr ) { return atoi( Encoding.UTF8.GetString( inStr, 0, inStr.Length ) ); } static int atoi( string inStr ) { int i; for ( i = 0; i < inStr.Length; i++ ) { //if ( !sqlite3Isdigit( inStr[i] ) && inStr[i] != '-' ) if ( inStr[i] < '0'&& inStr[i]> '9' && inStr[i] != '-' ) break; } int result = 0; #if WINDOWS_MOBILE try { result = Int32.Parse(inStr.Substring(0, i)); } catch { } return result; #else return ( Int32.TryParse( inStr.Substring( 0, i ), out result ) ? result : 0 ); #endif } static void fprintf( TextWriter tw, string zFormat, params object[] ap ) { tw.Write( sqlite3_mprintf( zFormat, ap ) ); } static void printf( string zFormat, params object[] ap ) { Console.Out.Write( sqlite3_mprintf( zFormat, ap ) ); } //Byte Buffer Testing static int memcmp( byte[] bA, byte[] bB, int Limit ) { if ( bA.Length < Limit ) return ( bA.Length < bB.Length ) ? -1 : +1; if ( bB.Length < Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( bA[i] != bB[i] ) return ( bA[i] < bB[i] ) ? -1 : 1; } return 0; } //Byte Buffer & String Testing static int memcmp( string A, byte[] bB, int Limit ) { if ( A.Length < Limit ) return ( A.Length < bB.Length ) ? -1 : +1; if ( bB.Length < Limit ) return +1; char[] cA = A.ToCharArray(); for ( int i = 0; i < Limit; i++ ) { if ( cA[i] != bB[i] ) return ( cA[i] < bB[i] ) ? -1 : 1; } return 0; } //byte with Offset & String Testing static int memcmp( byte[] a, int Offset, byte[] b, int Limit ) { if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; if ( b.Length < Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; } return 0; } //byte with Offset & String Testing static int memcmp( byte[] a, int Aoffset, byte[] b, int Boffset, int Limit ) { if ( a.Length < Aoffset + Limit ) return ( a.Length - Aoffset < b.Length - Boffset ) ? -1 : +1; if ( b.Length < Boffset + Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( a[i + Aoffset] != b[i + Boffset] ) return ( a[i + Aoffset] < b[i + Boffset] ) ? -1 : 1; } return 0; } static int memcmp( byte[] a, int Offset, string b, int Limit ) { if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; if ( b.Length < Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; } return 0; } //String Testing static int memcmp( string A, string B, int Limit ) { if ( A.Length < Limit ) return ( A.Length < B.Length ) ? -1 : +1; if ( B.Length < Limit ) return +1; int rc; if ( ( rc = String.Compare( A, 0, B, 0, Limit, StringComparison.Ordinal ) ) == 0 ) return 0; return rc < 0 ? -1 : +1; } // ---------------------------- // ** Builtin Functions // ---------------------------- static Regex oRegex = null; /* ** The regexp() function. two arguments are both strings ** Collating sequences are not used. */ static void regexpFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string zTest; /* The input string A */ string zRegex; /* The regex string B */ Debug.Assert( argc == 2 ); UNUSED_PARAMETER( argc ); zRegex = sqlite3_value_text( argv[0] ); zTest = sqlite3_value_text( argv[1] ); if ( zTest == null || String.IsNullOrEmpty( zRegex ) ) { sqlite3_result_int( context, 0 ); return; } if ( oRegex == null || oRegex.ToString() == zRegex ) { oRegex = new Regex( zRegex, RegexOptions.IgnoreCase ); } sqlite3_result_int( context, oRegex.IsMatch( zTest ) ? 1 : 0 ); } // ---------------------------- // ** Convertion routines // ---------------------------- static Object lock_va_list = new Object(); static string vaFORMAT; static int vaNEXT; static void va_start( object[] ap, string zFormat ) { vaFORMAT = zFormat; vaNEXT = 0; } static Boolean va_arg( object[] ap, Boolean sysType ) { return Convert.ToBoolean( ap[vaNEXT++] ); } static Byte[] va_arg( object[] ap, Byte[] sysType ) { return (Byte[])ap[vaNEXT++]; } static Byte[][] va_arg( object[] ap, Byte[][] sysType ) { if ( ap[vaNEXT] == null ) { { vaNEXT++; return null; } } else { return (Byte[][])ap[vaNEXT++]; } } static Char va_arg( object[] ap, Char sysType ) { if ( ap[vaNEXT] is Int32 && (int)ap[vaNEXT] == 0 ) { vaNEXT++; return (char)'0'; } else { if ( ap[vaNEXT] is Int64 ) if ( (i64)ap[vaNEXT] == 0 ) { vaNEXT++; return (char)'0'; } else return (char)( (i64)ap[vaNEXT++] ); else return (char)ap[vaNEXT++]; } } static Double va_arg( object[] ap, Double sysType ) { return Convert.ToDouble( ap[vaNEXT++] ); } static dxLog va_arg( object[] ap, dxLog sysType ) { return (dxLog)ap[vaNEXT++]; } static Int64 va_arg( object[] ap, Int64 sysType ) { if ( ap[vaNEXT] is System.Int64) return Convert.ToInt64( ap[vaNEXT++] ); else return (Int64)( ap[vaNEXT++].GetHashCode() ); } static Int32 va_arg( object[] ap, Int32 sysType ) { if ( Convert.ToInt64( ap[vaNEXT] ) > 0 && ( Convert.ToUInt32( ap[vaNEXT] ) > Int32.MaxValue ) ) return (Int32)( Convert.ToUInt32( ap[vaNEXT++] ) - System.UInt32.MaxValue - 1 ); else return (Int32)Convert.ToInt32( ap[vaNEXT++] ); } static Int32[] va_arg( object[] ap, Int32[] sysType ) { if ( ap[vaNEXT] == null ) { { vaNEXT++; return null; } } else { return (Int32[])ap[vaNEXT++]; } } static MemPage va_arg( object[] ap, MemPage sysType ) { return (MemPage)ap[vaNEXT++]; } static Object va_arg( object[] ap, Object sysType ) { return (Object)ap[vaNEXT++]; } static sqlite3 va_arg( object[] ap, sqlite3 sysType ) { return (sqlite3)ap[vaNEXT++]; } static sqlite3_mem_methods va_arg( object[] ap, sqlite3_mem_methods sysType ) { return (sqlite3_mem_methods)ap[vaNEXT++]; } static sqlite3_mutex_methods va_arg( object[] ap, sqlite3_mutex_methods sysType ) { return (sqlite3_mutex_methods)ap[vaNEXT++]; } static SrcList va_arg( object[] ap, SrcList sysType ) { return (SrcList)ap[vaNEXT++]; } static String va_arg( object[] ap, String sysType ) { if ( ap.Length < vaNEXT - 1 || ap[vaNEXT] == null ) { vaNEXT++; return "NULL"; } else { if ( ap[vaNEXT] is Byte[] ) if ( Encoding.UTF8.GetString( (byte[])ap[vaNEXT], 0, ( (byte[])ap[vaNEXT] ).Length ) == "\0" ) { vaNEXT++; return ""; } else return Encoding.UTF8.GetString( (byte[])ap[vaNEXT], 0, ( (byte[])ap[vaNEXT++] ).Length ); else if ( ap[vaNEXT] is Int32 ) { vaNEXT++; return null; } else if ( ap[vaNEXT] is StringBuilder ) return (String)ap[vaNEXT++].ToString(); else if ( ap[vaNEXT] is Char ) return ( (Char)ap[vaNEXT++] ).ToString(); else return (String)ap[vaNEXT++]; } } static Token va_arg( object[] ap, Token sysType ) { return (Token)ap[vaNEXT++]; } static UInt32 va_arg( object[] ap, UInt32 sysType ) { if ( ap[vaNEXT].GetType().IsClass ) { return (UInt32)ap[vaNEXT++].GetHashCode(); } else { return (UInt32)Convert.ToUInt32( ap[vaNEXT++] ); } } static UInt64 va_arg( object[] ap, UInt64 sysType ) { if ( ap[vaNEXT].GetType().IsClass ) { return (UInt64)ap[vaNEXT++].GetHashCode(); } else { return (UInt64)Convert.ToUInt64( ap[vaNEXT++] ); } } static void_function va_arg( object[] ap, void_function sysType ) { return (void_function)ap[vaNEXT++]; } static void va_end( ref string[] ap ) { ap = null; vaNEXT = -1; vaFORMAT = ""; } static void va_end( ref object[] ap ) { ap = null; vaNEXT = -1; vaFORMAT = ""; } public static tm localtime( time_t baseTime ) { System.DateTime RefTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); RefTime = RefTime.AddSeconds( Convert.ToDouble( baseTime ) ).ToLocalTime(); tm tm = new tm(); tm.tm_sec = RefTime.Second; tm.tm_min = RefTime.Minute; tm.tm_hour = RefTime.Hour; tm.tm_mday = RefTime.Day; tm.tm_mon = RefTime.Month; tm.tm_year = RefTime.Year; tm.tm_wday = (int)RefTime.DayOfWeek; tm.tm_yday = RefTime.DayOfYear; tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0; return tm; } public static long ToUnixtime( System.DateTime date ) { System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); System.TimeSpan timeSpan = date - unixStartTime; return Convert.ToInt64( timeSpan.TotalSeconds ); } public static System.DateTime ToCSharpTime( long unixTime ) { System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); return unixStartTime.AddSeconds( Convert.ToDouble( unixTime ) ); } public class tm { public int tm_sec; /* seconds after the minute - [0,59] */ public int tm_min; /* minutes after the hour - [0,59] */ public int tm_hour; /* hours since midnight - [0,23] */ public int tm_mday; /* day of the month - [1,31] */ public int tm_mon; /* months since January - [0,11] */ public int tm_year; /* years since 1900 */ public int tm_wday; /* days since Sunday - [0,6] */ public int tm_yday; /* days since January 1 - [0,365] */ public int tm_isdst; /* daylight savings time flag */ }; public struct FILETIME { public u32 dwLowDateTime; public u32 dwHighDateTime; } // Example (C#) public static int GetbytesPerSector( StringBuilder diskPath ) { #if NO_SQLITE_SILVERLIGHT // #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) ManagementObjectSearcher mosLogicalDisks = new ManagementObjectSearcher( "select * from Win32_LogicalDisk where DeviceID = '" + diskPath.ToString().Remove( diskPath.Length - 1, 1 ) + "'" ); try { foreach ( ManagementObject moLogDisk in mosLogicalDisks.Get() ) { ManagementObjectSearcher mosDiskDrives = new ManagementObjectSearcher( "select * from Win32_DiskDrive where SystemName = '" + moLogDisk["SystemName"] + "'" ); foreach ( ManagementObject moPDisk in mosDiskDrives.Get() ) { return int.Parse( moPDisk["BytesPerSector"].ToString() ); } } } catch { } return 4096; #else return 4096; #endif } static void SWAP<T>( ref T A, ref T B ) { T t = A; A = B; B = t; } static void x_CountStep( sqlite3_context context, int argc, sqlite3_value[] argv ) { SumCtx p; int type; Debug.Assert( argc <= 1 ); Mem pMem = sqlite3_aggregate_context( context, 1 );//sizeof(*p)); if ( pMem._SumCtx == null ) pMem._SumCtx = new SumCtx(); p = pMem._SumCtx; if ( p.Context == null ) p.Context = pMem; if ( argc == 0 || SQLITE_NULL == sqlite3_value_type( argv[0] ) ) { p.cnt++; p.iSum += 1; } else { type = sqlite3_value_numeric_type( argv[0] ); if ( p != null && type != SQLITE_NULL ) { p.cnt++; if ( type == SQLITE_INTEGER ) { i64 v = sqlite3_value_int64( argv[0] ); if ( v == 40 || v == 41 ) { sqlite3_result_error( context, "value of " + v + " handed to x_count", -1 ); return; } else { p.iSum += v; if ( !( p.approx | p.overflow != 0 ) ) { i64 iNewSum = p.iSum + v; int s1 = (int)( p.iSum >> ( sizeof( i64 ) * 8 - 1 ) ); int s2 = (int)( v >> ( sizeof( i64 ) * 8 - 1 ) ); int s3 = (int)( iNewSum >> ( sizeof( i64 ) * 8 - 1 ) ); p.overflow = ( ( s1 & s2 & ~s3 ) | ( ~s1 & ~s2 & s3 ) ) != 0 ? 1 : 0; p.iSum = iNewSum; } } } else { p.rSum += sqlite3_value_double( argv[0] ); p.approx = true; } } } } static void x_CountFinalize( sqlite3_context context ) { SumCtx p; Mem pMem = sqlite3_aggregate_context( context, 0 ); p = pMem._SumCtx; if ( p != null && p.cnt > 0 ) { if ( p.overflow != 0 ) { sqlite3_result_error( context, "integer overflow", -1 ); } else if ( p.approx ) { sqlite3_result_double( context, p.rSum ); } else if ( p.iSum == 42 ) { sqlite3_result_error( context, "x_count totals to 42", -1 ); } else { sqlite3_result_int64( context, p.iSum ); } } } #if SQLITE_MUTEX_W32 //---------------------WIN32 Definitions static int GetCurrentThreadId() { return Thread.CurrentThread.ManagedThreadId; } static long InterlockedIncrement( long location ) { Interlocked.Increment( ref location ); return location; } static void EnterCriticalSection( Object mtx ) { //long mid = mtx.GetHashCode(); //int tid = Thread.CurrentThread.ManagedThreadId; //long ticks = cnt++; //Debug.WriteLine(String.Format( "{2}: +EnterCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, ticks) ); Monitor.Enter( mtx ); } static void InitializeCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format( "{2}: +InitializeCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); Monitor.Enter( mtx ); } static void DeleteCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format( "{2}: +DeleteCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks) ); Monitor.Exit( mtx ); } static void LeaveCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format("{2}: +LeaveCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); Monitor.Exit( mtx ); } #endif // Miscellaneous Windows Constants //#define ERROR_FILE_NOT_FOUND 2L //#define ERROR_HANDLE_DISK_FULL 39L //#define ERROR_NOT_SUPPORTED 50L //#define ERROR_DISK_FULL 112L const long ERROR_FILE_NOT_FOUND = 2L; const long ERROR_HANDLE_DISK_FULL = 39L; const long ERROR_NOT_SUPPORTED = 50L; const long ERROR_DISK_FULL = 112L; private class SQLite3UpperToLower { static int[] sqlite3UpperToLower = new int[] { #if !NO_SQLITE_ASCII 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, 252,253,254,255 #endif }; public int this[int index] { get { if ( index < sqlite3UpperToLower.Length ) return sqlite3UpperToLower[index]; else return index; } } public int this[u32 index] { get { if ( index < sqlite3UpperToLower.Length ) return sqlite3UpperToLower[index]; else return (int)index; } } } static SQLite3UpperToLower sqlite3UpperToLower = new SQLite3UpperToLower(); static SQLite3UpperToLower UpperToLower = sqlite3UpperToLower; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundToNearestIntegerScalarDouble() { var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundToNearestIntegerScalarDouble { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundToNearestIntegerScalarDouble testClass) { var result = Sse41.RoundToNearestIntegerScalar(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNearestIntegerScalarDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) { var result = Sse41.RoundToNearestIntegerScalar( Sse2.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar1; private Vector128<Double> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToNearestIntegerScalarDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleUnaryOpTest__RoundToNearestIntegerScalarDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.RoundToNearestIntegerScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.RoundToNearestIntegerScalar( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.RoundToNearestIntegerScalar( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.RoundToNearestIntegerScalar( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) { var result = Sse41.RoundToNearestIntegerScalar( Sse2.LoadVector128((Double*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var result = Sse41.RoundToNearestIntegerScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToNearestIntegerScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToNearestIntegerScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarDouble(); var result = Sse41.RoundToNearestIntegerScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) { var result = Sse41.RoundToNearestIntegerScalar( Sse2.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.RoundToNearestIntegerScalar(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) { var result = Sse41.RoundToNearestIntegerScalar( Sse2.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.RoundToNearestIntegerScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.RoundToNearestIntegerScalar( Sse2.LoadVector128((Double*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[0], MidpointRounding.AwayFromZero))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToNearestIntegerScalar)}<Double>(Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = 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 copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { // Classes to allow some type checking for the API // These hold pointers to allocated objects in the unmanaged space. // These classes are subclassed by the various physical implementations of // objects. In particular, there is a version for physical instances in // unmanaged memory ("unman") and one for in managed memory ("XNA"). // Currently, the instances of these classes are a reference to a // physical representation and this has no releationship to other // instances. Someday, refarb the usage of these classes so each instance // refers to a particular physical instance and this class controls reference // counts and such. This should be done along with adding BSShapes. public class BulletWorld { public BulletWorld(uint worldId, BSScene bss) { worldID = worldId; physicsScene = bss; } public uint worldID; // The scene is only in here so very low level routines have a handle to print debug/error messages public BSScene physicsScene; } // An allocated Bullet btRigidBody public class BulletBody { public BulletBody(uint id) { ID = id; collisionType = CollisionType.Static; } public uint ID; public CollisionType collisionType; public virtual void Clear() { } public virtual bool HasPhysicalBody { get { return false; } } // Apply the specificed collision mask into the physical world public virtual bool ApplyCollisionMask(BSScene physicsScene) { // Should assert the body has been added to the physical world. // (The collision masks are stored in the collision proxy cache which only exists for // a collision body that is in the world.) return physicsScene.PE.SetCollisionGroupMask(this, BulletSimData.CollisionTypeMasks[collisionType].group, BulletSimData.CollisionTypeMasks[collisionType].mask); } // Used for log messages for a unique display of the memory/object allocated to this instance public virtual string AddrString { get { return "unknown"; } } public override string ToString() { StringBuilder buff = new StringBuilder(); buff.Append("<id="); buff.Append(ID.ToString()); buff.Append(",p="); buff.Append(AddrString); buff.Append(",c="); buff.Append(collisionType); buff.Append(">"); return buff.ToString(); } } public class BulletShape { public BulletShape() { shapeType = BSPhysicsShapeType.SHAPE_UNKNOWN; shapeKey = (System.UInt64)FixedShapeKey.KEY_NONE; isNativeShape = false; } public BSPhysicsShapeType shapeType; public System.UInt64 shapeKey; public bool isNativeShape; public virtual void Clear() { } public virtual bool HasPhysicalShape { get { return false; } } // Make another reference to this physical object. public virtual BulletShape Clone() { return new BulletShape(); } // Return 'true' if this and other refer to the same physical object public virtual bool ReferenceSame(BulletShape xx) { return false; } // Used for log messages for a unique display of the memory/object allocated to this instance public virtual string AddrString { get { return "unknown"; } } public override string ToString() { StringBuilder buff = new StringBuilder(); buff.Append("<p="); buff.Append(AddrString); buff.Append(",s="); buff.Append(shapeType.ToString()); buff.Append(",k="); buff.Append(shapeKey.ToString("X")); buff.Append(",n="); buff.Append(isNativeShape.ToString()); buff.Append(">"); return buff.ToString(); } } // An allocated Bullet btConstraint public class BulletConstraint { public BulletConstraint() { } public virtual void Clear() { } public virtual bool HasPhysicalConstraint { get { return false; } } // Used for log messages for a unique display of the memory/object allocated to this instance public virtual string AddrString { get { return "unknown"; } } } // An allocated HeightMapThing which holds various heightmap info. // Made a class rather than a struct so there would be only one // instance of this and C# will pass around pointers rather // than making copies. public class BulletHMapInfo { public BulletHMapInfo(uint id, float[] hm, float pSizeX, float pSizeY) { ID = id; heightMap = hm; terrainRegionBase = OMV.Vector3.Zero; minCoords = new OMV.Vector3(100f, 100f, 25f); maxCoords = new OMV.Vector3(101f, 101f, 26f); minZ = maxZ = 0f; sizeX = pSizeX; sizeY = pSizeY; } public uint ID; public float[] heightMap; public OMV.Vector3 terrainRegionBase; public OMV.Vector3 minCoords; public OMV.Vector3 maxCoords; public float sizeX, sizeY; public float minZ, maxZ; public BulletShape terrainShape; public BulletBody terrainBody; } // The general class of collsion object. public enum CollisionType { Avatar, PhantomToOthersAvatar, // An avatar that it phantom to other avatars but not to anything else Groundplane, Terrain, Static, Dynamic, VolumeDetect, // Linkset, // A linkset should be either Static or Dynamic LinksetChild, Unknown }; // Hold specification of group and mask collision flags for a CollisionType public struct CollisionTypeFilterGroup { public CollisionTypeFilterGroup(CollisionType t, uint g, uint m) { type = t; group = g; mask = m; } public CollisionType type; public uint group; public uint mask; }; public static class BulletSimData { // Map of collisionTypes to flags for collision groups and masks. // An object's 'group' is the collison groups this object belongs to // An object's 'filter' is the groups another object has to belong to in order to collide with me // A collision happens if ((obj1.group & obj2.filter) != 0) || ((obj2.group & obj1.filter) != 0) // // As mentioned above, don't use the CollisionFilterGroups definitions directly in the code // but, instead, use references to this dictionary. Finding and debugging // collision flag problems will be made easier. public static Dictionary<CollisionType, CollisionTypeFilterGroup> CollisionTypeMasks = new Dictionary<CollisionType, CollisionTypeFilterGroup>() { { CollisionType.Avatar, new CollisionTypeFilterGroup(CollisionType.Avatar, (uint)CollisionFilterGroups.BCharacterGroup, (uint)(CollisionFilterGroups.BAllGroup)) }, { CollisionType.PhantomToOthersAvatar, new CollisionTypeFilterGroup(CollisionType.PhantomToOthersAvatar, (uint)CollisionFilterGroups.BCharacterGroup, (uint)(CollisionFilterGroups.BAllGroup & ~CollisionFilterGroups.BCharacterGroup)) }, { CollisionType.Groundplane, new CollisionTypeFilterGroup(CollisionType.Groundplane, (uint)CollisionFilterGroups.BGroundPlaneGroup, // (uint)CollisionFilterGroups.BAllGroup) (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup)) }, { CollisionType.Terrain, new CollisionTypeFilterGroup(CollisionType.Terrain, (uint)CollisionFilterGroups.BTerrainGroup, (uint)(CollisionFilterGroups.BAllGroup & ~CollisionFilterGroups.BStaticGroup)) }, { CollisionType.Static, new CollisionTypeFilterGroup(CollisionType.Static, (uint)CollisionFilterGroups.BStaticGroup, (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup)) }, { CollisionType.Dynamic, new CollisionTypeFilterGroup(CollisionType.Dynamic, (uint)CollisionFilterGroups.BSolidGroup, (uint)(CollisionFilterGroups.BAllGroup)) }, { CollisionType.VolumeDetect, new CollisionTypeFilterGroup(CollisionType.VolumeDetect, (uint)CollisionFilterGroups.BSensorTrigger, (uint)(~CollisionFilterGroups.BSensorTrigger)) }, { CollisionType.LinksetChild, new CollisionTypeFilterGroup(CollisionType.LinksetChild, (uint)CollisionFilterGroups.BLinksetChildGroup, (uint)(CollisionFilterGroups.BNoneGroup)) // (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup)) }, }; } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.IO { using System; using System.IO; using Microsoft.Practices.TransientFaultHandling; /// <summary> /// Helpers related to <see cref="System.IO.File"/> and <see cref="System.IO.Directory"/>. /// </summary> public static class Extensions { /// <summary> /// A <see cref="ITransientErrorDetectionStrategy"/> for App_Data transient errors. /// </summary> private class AppDataTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy { /// <summary> /// Flags transient errors. /// </summary> /// <param name="ex">The error.</param> /// <returns>'true' if the error is transient.</returns> public bool IsTransient(Exception ex) { return ex is IOException || ex is UnauthorizedAccessException; } } /// <summary> /// Creates a default <see cref="RetryPolicy"/>. /// </summary> /// <param name="retryStrategy">The retry strategy.</param> /// <returns>The retry policy.</returns> public static RetryPolicy CreateRetryPolicy(this RetryStrategy retryStrategy) { var detectionStrategy = new AppDataTransientErrorDetectionStrategy(); return new RetryPolicy(detectionStrategy, retryStrategy); } /// <summary> /// Creates a <see cref="FileSystemWatcher"/> with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> /// <returns>The watcher.</returns> public static FileSystemWatcher CreateFileSystemWatcher(this RetryPolicy retryPolicy, string path) { return retryPolicy.ExecuteAction(() => new FileSystemWatcher(path) { InternalBufferSize = 1024 * 64, NotifyFilter = NotifyFilters.FileName, EnableRaisingEvents = true, IncludeSubdirectories = false, }); } /// <summary> /// Creates a <see cref="DirectoryInfo"/> with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> /// <returns>The directory.</returns> public static DirectoryInfo GetDirectory(this RetryPolicy retryPolicy, string path) { return retryPolicy.ExecuteAction(() => new DirectoryInfo(path)); } /// <summary> /// Calls Exists method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> /// <returns>'true' if the directory exists.</returns> public static bool DirectoryExists(this RetryPolicy retryPolicy, string path) { return retryPolicy.ExecuteAction(() => Directory.Exists(path)); } /// <summary> /// Calls CreateDirectory method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> /// <returns>The directory.</returns> public static DirectoryInfo DirectoryCreate(this RetryPolicy retryPolicy, string path) { return retryPolicy.ExecuteAction(() => Directory.CreateDirectory(path)); } /// <summary> /// Calls Delete method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> /// <param name="recursive">The flag to delete subdirectories.</param> public static void DirectoryDelete(this RetryPolicy retryPolicy, string path, bool recursive) { retryPolicy.ExecuteAction(() => Directory.Delete(path, recursive)); } /// <summary> /// Calls GetDirectories method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="directory">The directory.</param> /// <param name="searchPattern">The filter.</param> /// <returns>The directories.</returns> public static DirectoryInfo[] GetDirectories(this RetryPolicy retryPolicy, DirectoryInfo directory, string searchPattern) { return retryPolicy.ExecuteAction(() => directory.GetDirectories(searchPattern)); } /// <summary> /// Calls GetFiles method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="directory">The directory.</param> /// <param name="searchPattern">The filter.</param> /// <returns>The files.</returns> public static FileInfo[] GetFiles(this RetryPolicy retryPolicy, DirectoryInfo directory, string searchPattern) { return retryPolicy.ExecuteAction(() => directory.GetFiles(searchPattern)); } /// <summary> /// Calls Exists method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> /// <returns>'true' if the file exists.</returns> public static bool FileExists(this RetryPolicy retryPolicy, string path) { return retryPolicy.ExecuteAction(() => File.Exists(path)); } /// <summary> /// Calls Move method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="sourceFileName">The source path.</param> /// <param name="destFileName">The destination path.</param> public static void FileMove(this RetryPolicy retryPolicy, string sourceFileName, string destFileName) { retryPolicy.ExecuteAction(() => File.Move(sourceFileName, destFileName)); } /// <summary> /// Calls Delete method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> public static void FileDelete(this RetryPolicy retryPolicy, string path) { retryPolicy.ExecuteAction(() => File.Delete(path)); } /// <summary> /// Calls Delete method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="file">The file.</param> public static void FileDelete(this RetryPolicy retryPolicy, FileInfo file) { retryPolicy.ExecuteAction(file.Delete); } /// <summary> /// Calls Open method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> /// <param name="mode">The access mode.</param> /// <returns>The file stream.</returns> public static FileStream Open(this RetryPolicy retryPolicy, string path, FileMode mode) { return retryPolicy.ExecuteAction(() => File.Open(path, mode)); } /// <summary> /// Calls OpenText method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> /// <returns>The file stream.</returns> public static TextReader OpenText(this RetryPolicy retryPolicy, string path) { return retryPolicy.ExecuteAction(() => File.OpenText(path)); } /// <summary> /// Calls WriteAllBytes method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> /// <param name="bytes">The data.</param> public static void WriteAllBytes(this RetryPolicy retryPolicy, string path, byte[] bytes) { retryPolicy.ExecuteAction(() => File.WriteAllBytes(path, bytes)); } /// <summary> /// Calls ReadAllBytes method with retries. /// </summary> /// <param name="retryPolicy">The retry policy.</param> /// <param name="path">The path.</param> /// <returns>The data.</returns> public static byte[] ReadAllBytes(this RetryPolicy retryPolicy, string path) { return retryPolicy.ExecuteAction(() => File.ReadAllBytes(path)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace LocalSecurity.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Pickers; using Windows.Storage.Streams; using Windows.UI.Xaml.Media.Imaging; using Caliburn.Micro; using Core.Captcha; using Core.Common; using Core.Common.Links; using Core.Models; using Core.Models.Exceptions; using TheChan.Common; using TheChan.Common.Core; using TheChan.Common.UI; using TheChan.Extensions; namespace TheChan.ViewModels { public class ExtendedPostingViewModel : PropertyChangedBase { private string postText; private int selectionStart; private int selectionLength; private string eMail; private string name; private string subject; private bool isOp; private bool isSage; private bool isWorking; private bool canAttach; public ExtendedPostingViewModel(IShell shell, IBoard board, PostInfo postInfo, ThreadLink threadLink) { PostInfo = postInfo; Shell = shell; Board = board; BoardId = threadLink.BoardId; Parent = threadLink.ThreadNumber; SetupProperties(); } public ExtendedPostingViewModel(IShell shell, IBoard board, PostInfo postInfo, string boardId) { PostInfo = postInfo; Shell = shell; Board = board; BoardId = boardId; Parent = 0; IsNewThread = true; SetupProperties(); } private PostInfo PostInfo { get; } private IShell Shell { get; } private IBoard Board { get; } private string BoardId { get; } private long Parent { get; } public bool IsNewThread { get; } public event EventHandler<PostInfoChangedEventArgs> PostInfoChanged; public event EventHandler PostSent; public event EventHandler<CaptchaEntryRequestedEventArgs> CaptchaEntryRequested; public ObservableCollection<AttachmentViewModel> Attachments { get; } = new ObservableCollection<AttachmentViewModel>(); public bool IsWorking { get { return this.isWorking; } private set { if (value == this.isWorking) return; this.isWorking = value; NotifyOfPropertyChange(); } } public string PostText { get { return this.postText; } set { if (value == this.postText) return; var text = value.Replace("\r", "\n"); this.postText = text; PostInfo.Text = text; NotifyOfPropertyChange(); NotifyOfPostInfoChange(); } } public string EMail { get { return this.eMail; } set { if (value == this.eMail) return; this.eMail = value; PostInfo.EMail = value; IsSage = value.EqualsNc("sage"); NotifyOfPropertyChange(); NotifyOfPostInfoChange(); } } public string Name { get { return this.name; } set { if (value == this.name) return; this.name = value; PostInfo.Name = value; NotifyOfPropertyChange(); NotifyOfPostInfoChange(); } } public string Subject { get { return this.subject; } set { if (value == this.subject) return; this.subject = value; PostInfo.Subject = value; NotifyOfPropertyChange(); NotifyOfPostInfoChange(); } } public bool? IsOp { get { return this.isOp; } set { if (value == this.isOp) return; this.isOp = value.GetValueOrDefault(); PostInfo.IsOp = value.GetValueOrDefault(); NotifyOfPropertyChange(); NotifyOfPostInfoChange(); } } public bool? IsSage { get { return this.isSage; } set { if (value == this.isSage) return; var val = value.GetValueOrDefault(); this.isSage = val; if (val) EMail = "sage"; else if (EMail.EqualsNc("sage")) EMail = ""; NotifyOfPropertyChange(); } } public int SelectionStart { get { return this.selectionStart; } set { if (value == this.selectionStart) return; this.selectionStart = value; NotifyOfPropertyChange(); } } public int SelectionLength { get { return this.selectionLength; } set { if (value == this.selectionLength) return; this.selectionLength = value; NotifyOfPropertyChange(); } } public bool CanAttach { get { return this.canAttach; } private set { if (value == this.canAttach) return; this.canAttach = value; NotifyOfPropertyChange(); } } private void NotifyOfPostInfoChange() { PostInfoChanged?.Invoke(this, new PostInfoChangedEventArgs(PostInfo)); } private async void SetupProperties() { PostText = PostInfo.Text; Name = PostInfo.Name; EMail = PostInfo.EMail; Subject = PostInfo.Subject; IsOp = PostInfo.IsOp; Attachments.CollectionChanged += AttachmentsOnCollectionChanged; CanAttach = Board.MaxAttachments > 0; List<PostFileInfo> files = PostInfo.Files.ToList(); PostInfo.Files.Clear(); foreach (PostFileInfo fileInfo in files) { await Attach(fileInfo.StreamReference, fileInfo.Name); } } private void AttachmentsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { CanAttach = Attachments.Count < Board.MaxAttachments; } public void Insert(string text) { var selStart = SelectionStart; var selLen = SelectionLength; PostText = (PostText ?? "").Replace("\r\n", "\n").Insert(selStart, text); SelectionStart = selStart + selLen + text.Length; } public void Tag(string tag) { var selStart = SelectionStart; var selLen = SelectionLength; var first = $"[{tag}]"; var second = $"[/{tag}]"; PostText = (PostText ?? "") .Replace("\r\n", "\n") .Insert(selStart + selLen, second) .Insert(selStart, first); SelectionStart = selStart + selLen + first.Length + second.Length; } public async void Send() { IsWorking = true; Shell.LoadingInfo.InProgress(Localization.GetForView("Posting", "SendingPost")); PostInfo postInfo = PostInfo.Clone(); try { PostingResult result = DeviceUtils.GetDeviceFamily() == DeviceFamily.Mobile && !IsNewThread ? await Board.TryToPostWithoutCaptcha(postInfo, BoardId, Parent) : await Board.PostAsync(postInfo, BoardId, Parent); if (!result.IsSuccessful) throw new Exception(result.Error); Shell.LoadingInfo.Success(Localization.GetForView("Posting", "PostSent")); PostSent?.Invoke(this, new EventArgs()); PostInfo.Clear(); NotifyOfPostInfoChange(); if (Parent == 0 && result.PostNumber.HasValue) { Shell.Navigate<ThreadViewModel>(ThreadNavigation.NavigateToThread(BoardId, result.PostNumber.Value)); } IsWorking = false; Close(); } catch (CaptchaNeededException e) { CaptchaContent content = await Board.GetCaptchaContentAsync(e.Captcha); CaptchaEntryRequested?.Invoke(this, new CaptchaEntryRequestedEventArgs(e.Captcha, content, success => { if (success) { PostInfo.Captcha = e.Captcha; Send(); } else { Shell.LoadingInfo.Error(e.Message); IsWorking = false; } })); } catch (Exception e) { Shell.LoadingInfo.Error(e.Message); IsWorking = false; } } public async void PickAndAttach() { var picker = new FileOpenPicker(); foreach (string format in Board.AllowedAttachmentFormats) { picker.FileTypeFilter.Add(format); } picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; try { List<StorageFile> files = (await picker.PickMultipleFilesAsync()).ToList(); int howManyFilesCanAttach = Board.MaxAttachments - Attachments.Count; if (files.Count > howManyFilesCanAttach) files.RemoveRange(howManyFilesCanAttach, files.Count - howManyFilesCanAttach); foreach (StorageFile file in files) { await Attach(file); } } catch { // ok } } private async Task Attach(IRandomAccessStreamReference reference, string name) { if (Attachments.Count >= Board.MaxAttachments) return; var bitmap = new BitmapImage(); IRandomAccessStreamWithContentType stream = await reference.OpenReadAsync(); if (PostInfo.Files == null) { PostInfo.Files = new List<PostFileInfo>(); } var fileInfo = new PostFileInfo(name, reference); PostInfo.Files.Add(fileInfo); bitmap.SetSource(stream); Attachments.Add(new AttachmentViewModel { FileInfo = fileInfo, Image = bitmap, Type = stream.ContentType, }); } public Task Attach(IStorageFile file) { return Attach(file, file.Name); } public Task AttachPastedFile(IRandomAccessStreamReference reference) { return Attach(reference, Localization.GetForView("Posting", "Untitled")); } public void Detach(AttachmentViewModel attachment) { Attachments.Remove(attachment); PostInfo.Files.Remove(attachment.FileInfo); } public void Close() { if (!IsWorking) Shell.HidePopup(); } } public class PostInfoChangedEventArgs : EventArgs { public PostInfoChangedEventArgs(PostInfo postInfo) { PostInfo = postInfo; } public PostInfo PostInfo { get; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcdv = Google.Cloud.Dataproc.V1; using sys = System; namespace Google.Cloud.Dataproc.V1 { /// <summary>Resource name for the <c>Batch</c> resource.</summary> public sealed partial class BatchName : gax::IResourceName, sys::IEquatable<BatchName> { /// <summary>The possible contents of <see cref="BatchName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/batches/{batch}</c>. /// </summary> ProjectLocationBatch = 1, } private static gax::PathTemplate s_projectLocationBatch = new gax::PathTemplate("projects/{project}/locations/{location}/batches/{batch}"); /// <summary>Creates a <see cref="BatchName"/> 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="BatchName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static BatchName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new BatchName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="BatchName"/> with the pattern /// <c>projects/{project}/locations/{location}/batches/{batch}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="batchId">The <c>Batch</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="BatchName"/> constructed from the provided ids.</returns> public static BatchName FromProjectLocationBatch(string projectId, string locationId, string batchId) => new BatchName(ResourceNameType.ProjectLocationBatch, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), batchId: gax::GaxPreconditions.CheckNotNullOrEmpty(batchId, nameof(batchId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="BatchName"/> with pattern /// <c>projects/{project}/locations/{location}/batches/{batch}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="batchId">The <c>Batch</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="BatchName"/> with pattern /// <c>projects/{project}/locations/{location}/batches/{batch}</c>. /// </returns> public static string Format(string projectId, string locationId, string batchId) => FormatProjectLocationBatch(projectId, locationId, batchId); /// <summary> /// Formats the IDs into the string representation of this <see cref="BatchName"/> with pattern /// <c>projects/{project}/locations/{location}/batches/{batch}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="batchId">The <c>Batch</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="BatchName"/> with pattern /// <c>projects/{project}/locations/{location}/batches/{batch}</c>. /// </returns> public static string FormatProjectLocationBatch(string projectId, string locationId, string batchId) => s_projectLocationBatch.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(batchId, nameof(batchId))); /// <summary>Parses the given resource name string into a new <see cref="BatchName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/batches/{batch}</c></description></item> /// </list> /// </remarks> /// <param name="batchName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="BatchName"/> if successful.</returns> public static BatchName Parse(string batchName) => Parse(batchName, false); /// <summary> /// Parses the given resource name string into a new <see cref="BatchName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/batches/{batch}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="batchName">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="BatchName"/> if successful.</returns> public static BatchName Parse(string batchName, bool allowUnparsed) => TryParse(batchName, allowUnparsed, out BatchName 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="BatchName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/batches/{batch}</c></description></item> /// </list> /// </remarks> /// <param name="batchName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="BatchName"/>, 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 batchName, out BatchName result) => TryParse(batchName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="BatchName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/batches/{batch}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="batchName">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="BatchName"/>, 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 batchName, bool allowUnparsed, out BatchName result) { gax::GaxPreconditions.CheckNotNull(batchName, nameof(batchName)); gax::TemplatedResourceName resourceName; if (s_projectLocationBatch.TryParseName(batchName, out resourceName)) { result = FromProjectLocationBatch(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(batchName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private BatchName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string batchId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; BatchId = batchId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="BatchName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/batches/{batch}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="batchId">The <c>Batch</c> ID. Must not be <c>null</c> or empty.</param> public BatchName(string projectId, string locationId, string batchId) : this(ResourceNameType.ProjectLocationBatch, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), batchId: gax::GaxPreconditions.CheckNotNullOrEmpty(batchId, nameof(batchId))) { } /// <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>Batch</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string BatchId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationBatch: return s_projectLocationBatch.Expand(ProjectId, LocationId, BatchId); 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 BatchName); /// <inheritdoc/> public bool Equals(BatchName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(BatchName a, BatchName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(BatchName a, BatchName b) => !(a == b); } public partial class CreateBatchRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetBatchRequest { /// <summary> /// <see cref="gcdv::BatchName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::BatchName BatchName { get => string.IsNullOrEmpty(Name) ? null : gcdv::BatchName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListBatchesRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteBatchRequest { /// <summary> /// <see cref="gcdv::BatchName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::BatchName BatchName { get => string.IsNullOrEmpty(Name) ? null : gcdv::BatchName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class Batch { /// <summary> /// <see cref="gcdv::BatchName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::BatchName BatchName { get => string.IsNullOrEmpty(Name) ? null : gcdv::BatchName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; namespace fyiReporting.RdlDesign { /// <summary> /// Summary description for ChartCtl. /// </summary> internal class ChartCtl : System.Windows.Forms.UserControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; //AJM GJL 14082008 Adding more flags bool fChartType, fVector, fSubtype, fPalette, fRenderElement, fPercentWidth, ftooltip,ftooltipX; bool fNoRows, fDataSet, fPageBreakStart, fPageBreakEnd, tooltipYFormat, tooltipXFormat; bool fChartData; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox cbChartType; private System.Windows.Forms.ComboBox cbSubType; private System.Windows.Forms.ComboBox cbPalette; private System.Windows.Forms.ComboBox cbRenderElement; private System.Windows.Forms.Label label5; private System.Windows.Forms.NumericUpDown tbPercentWidth; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox tbNoRows; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox cbDataSet; private System.Windows.Forms.CheckBox chkPageBreakStart; private System.Windows.Forms.CheckBox chkPageBreakEnd; private System.Windows.Forms.ComboBox cbChartData; private ComboBox cbDataLabel; private CheckBox chkDataLabel; private Button bDataLabelExpr; private System.Windows.Forms.Label lData1; private ComboBox cbChartData2; private Label lData2; private ComboBox cbChartData3; private Label lData3; private Button bDataExpr; private Button bDataExpr3; private Button bDataExpr2; private ComboBox cbVector; private Button btnVectorExp; private Label label8; private Button button1; private Button button2; private Button button3; private CheckBox chkToolTip; private CheckBox checkBox1; private TextBox txtYToolFormat; private TextBox txtXToolFormat; private Label label9; private Label label10; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal ChartCtl(DesignXmlDraw dxDraw, List<XmlNode> ris) { _ReportItems = ris; _Draw = dxDraw; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { XmlNode node = _ReportItems[0]; string type = _Draw.GetElementValue(node, "Type", "Column"); this.cbChartType.Text = type; type = type.ToLowerInvariant(); lData2.Enabled = cbChartData2.Enabled = bDataExpr2.Enabled = (type == "scatter" || type == "bubble"); lData3.Enabled = cbChartData3.Enabled = bDataExpr3.Enabled = (type == "bubble"); //AJM GJL 14082008 this.chkToolTip.Checked = _Draw.GetElementValue(node, "fyi:Tooltip", "false").ToLower() == "true" ? true : false; this.checkBox1.Checked = _Draw.GetElementValue(node, "fyi:TooltipX", "false").ToLower() == "true" ? true : false; this.txtXToolFormat.Text = _Draw.GetElementValue(node, "fyi:TooltipXFormat",""); this.txtYToolFormat.Text = _Draw.GetElementValue(node, "fyi:TooltipYFormat",""); this.cbVector.Text = _Draw.GetElementValue(node, "fyi:RenderAsVector", "False"); this.cbSubType.Text = _Draw.GetElementValue(node, "Subtype", "Plain"); this.cbPalette.Text = _Draw.GetElementValue(node, "Palette", "Default"); this.cbRenderElement.Text = _Draw.GetElementValue(node, "ChartElementOutput", "Output"); this.tbPercentWidth.Text = _Draw.GetElementValue(node, "PointWidth", "0"); this.tbNoRows.Text = _Draw.GetElementValue(node, "NoRows", ""); // Handle the dataset for this dataregion object[] dsNames = _Draw.DataSetNames; string defName=""; if (dsNames != null && dsNames.Length > 0) { this.cbDataSet.Items.AddRange(_Draw.DataSetNames); defName = (string) dsNames[0]; } cbDataSet.Text = _Draw.GetDataSetNameValue(node); if (_Draw.GetReportItemDataRegionContainer(node) != null) cbDataSet.Enabled = false; // page breaks this.chkPageBreakStart.Checked = _Draw.GetElementValue(node, "PageBreakAtStart", "false").ToLower() == "true"? true: false; this.chkPageBreakEnd.Checked = _Draw.GetElementValue(node, "PageBreakAtEnd", "false").ToLower() == "true"? true: false; // Chart data-- this is a simplification of what is possible (TODO) string cdata=string.Empty; string cdata2 = string.Empty; string cdata3 = string.Empty; // <ChartData> // <ChartSeries> // <DataPoints> // <DataPoint> //<DataValues> // <DataValue> // <Value>=Sum(Fields!Sales.Value)</Value> // </DataValue> // <DataValue> // <Value>=Fields!Year.Value</Value> ----- only scatter and bubble // </DataValue> // <DataValue> // <Value>=Sum(Fields!Sales.Value)</Value> ----- only bubble // </DataValue> // </DataValues> // <DataLabel> // <Style> // <Format>c</Format> // </Style> // </DataLabel> // <Marker /> // </DataPoint> // </DataPoints> // </ChartSeries> // </ChartData> //Determine if we have a static series or not... We are not allowing this to be changed here. That decision is taken when creating the chart. 05122007GJL XmlNode ss = DesignXmlDraw.FindNextInHierarchy(node, "SeriesGroupings", "SeriesGrouping", "StaticSeries"); bool StaticSeries = ss != null; XmlNode dvs = DesignXmlDraw.FindNextInHierarchy(node, "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataValues"); int iter = 0; XmlNode cnode; foreach (XmlNode dv in dvs.ChildNodes) { if (dv.Name != "DataValue") continue; iter++; cnode = DesignXmlDraw.FindNextInHierarchy(dv, "Value"); if (cnode == null) continue; switch (iter) { case 1: cdata = cnode.InnerText; break; case 2: cdata2 = cnode.InnerText; break; case 3: cdata3 = cnode.InnerText; break; default: break; } } this.cbChartData.Text = cdata; this.cbChartData2.Text = cdata2; this.cbChartData3.Text = cdata3; //If the chart doesn't have a static series then dont show the datalabel values. 05122007GJL if (!StaticSeries) { //GJL 131107 Added data labels XmlNode labelExprNode = DesignXmlDraw.FindNextInHierarchy(node, "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataLabel", "Value"); if (labelExprNode != null) this.cbDataLabel.Text = labelExprNode.InnerText; XmlNode labelVisNode = DesignXmlDraw.FindNextInHierarchy(node, "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataLabel", "Visible"); if (labelVisNode != null) this.chkDataLabel.Checked = labelVisNode.InnerText.ToUpper().Equals("TRUE"); } chkDataLabel.Enabled = bDataLabelExpr.Enabled = cbDataLabel.Enabled = bDataExpr.Enabled = cbChartData.Enabled = !StaticSeries; // Don't allow the datalabel OR datavalues to be changed here if we have a static series GJL fChartType = fSubtype = fPalette = fRenderElement = fPercentWidth = fNoRows = fDataSet = fPageBreakStart = fPageBreakEnd = fChartData = false; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.cbChartType = new System.Windows.Forms.ComboBox(); this.cbSubType = new System.Windows.Forms.ComboBox(); this.cbPalette = new System.Windows.Forms.ComboBox(); this.cbRenderElement = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.tbPercentWidth = new System.Windows.Forms.NumericUpDown(); this.label6 = new System.Windows.Forms.Label(); this.tbNoRows = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.cbDataSet = new System.Windows.Forms.ComboBox(); this.chkPageBreakStart = new System.Windows.Forms.CheckBox(); this.chkPageBreakEnd = new System.Windows.Forms.CheckBox(); this.cbChartData = new System.Windows.Forms.ComboBox(); this.cbDataLabel = new System.Windows.Forms.ComboBox(); this.chkDataLabel = new System.Windows.Forms.CheckBox(); this.bDataLabelExpr = new System.Windows.Forms.Button(); this.lData1 = new System.Windows.Forms.Label(); this.cbChartData2 = new System.Windows.Forms.ComboBox(); this.lData2 = new System.Windows.Forms.Label(); this.cbChartData3 = new System.Windows.Forms.ComboBox(); this.lData3 = new System.Windows.Forms.Label(); this.bDataExpr = new System.Windows.Forms.Button(); this.bDataExpr3 = new System.Windows.Forms.Button(); this.bDataExpr2 = new System.Windows.Forms.Button(); this.cbVector = new System.Windows.Forms.ComboBox(); this.btnVectorExp = new System.Windows.Forms.Button(); this.label8 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.chkToolTip = new System.Windows.Forms.CheckBox(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.txtYToolFormat = new System.Windows.Forms.TextBox(); this.txtXToolFormat = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.tbPercentWidth)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(16, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(72, 16); this.label1.TabIndex = 0; this.label1.Text = "Chart Type"; // // label2 // this.label2.Location = new System.Drawing.Point(16, 37); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(72, 16); this.label2.TabIndex = 1; this.label2.Text = "Palette"; // // label3 // this.label3.Location = new System.Drawing.Point(16, 62); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(128, 16); this.label3.TabIndex = 2; this.label3.Text = "Render XML Element"; // // label4 // this.label4.Location = new System.Drawing.Point(16, 84); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(340, 19); this.label4.TabIndex = 3; this.label4.Text = "Percent width for Bars/Columns (>100% causes column overlap)"; // // cbChartType // this.cbChartType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbChartType.Items.AddRange(new object[] { "Area", "Bar", "Column", "Doughnut", "Line", "Map", "Pie", "Bubble", "Scatter"}); this.cbChartType.Location = new System.Drawing.Point(126, 9); this.cbChartType.Name = "cbChartType"; this.cbChartType.Size = new System.Drawing.Size(121, 21); this.cbChartType.TabIndex = 0; this.cbChartType.SelectedIndexChanged += new System.EventHandler(this.cbChartType_SelectedIndexChanged); // // cbSubType // this.cbSubType.Location = new System.Drawing.Point(331, 9); this.cbSubType.Name = "cbSubType"; this.cbSubType.Size = new System.Drawing.Size(80, 21); this.cbSubType.TabIndex = 1; this.cbSubType.SelectedIndexChanged += new System.EventHandler(this.cbSubType_SelectedIndexChanged); // // cbPalette // this.cbPalette.Items.AddRange(new object[] { "Default", "EarthTones", "Excel", "GrayScale", "Light", "Pastel", "SemiTransparent", "Patterned", "PatternedBlack", "Custom"}); this.cbPalette.Location = new System.Drawing.Point(126, 34); this.cbPalette.Name = "cbPalette"; this.cbPalette.Size = new System.Drawing.Size(121, 21); this.cbPalette.TabIndex = 2; this.cbPalette.SelectedIndexChanged += new System.EventHandler(this.cbPalette_SelectedIndexChanged); // // cbRenderElement // this.cbRenderElement.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbRenderElement.Items.AddRange(new object[] { "Output", "NoOutput"}); this.cbRenderElement.Location = new System.Drawing.Point(126, 59); this.cbRenderElement.Name = "cbRenderElement"; this.cbRenderElement.Size = new System.Drawing.Size(121, 21); this.cbRenderElement.TabIndex = 3; this.cbRenderElement.SelectedIndexChanged += new System.EventHandler(this.cbRenderElement_SelectedIndexChanged); // // label5 // this.label5.Location = new System.Drawing.Point(275, 12); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(53, 23); this.label5.TabIndex = 8; this.label5.Text = "Sub-type"; // // tbPercentWidth // this.tbPercentWidth.Location = new System.Drawing.Point(363, 80); this.tbPercentWidth.Name = "tbPercentWidth"; this.tbPercentWidth.Size = new System.Drawing.Size(48, 20); this.tbPercentWidth.TabIndex = 4; this.tbPercentWidth.ValueChanged += new System.EventHandler(this.tbPercentWidth_ValueChanged); // // label6 // this.label6.Location = new System.Drawing.Point(16, 104); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(100, 23); this.label6.TabIndex = 10; this.label6.Text = "No Rows Message"; // // tbNoRows // this.tbNoRows.Location = new System.Drawing.Point(156, 104); this.tbNoRows.Name = "tbNoRows"; this.tbNoRows.Size = new System.Drawing.Size(255, 20); this.tbNoRows.TabIndex = 5; this.tbNoRows.TextChanged += new System.EventHandler(this.tbNoRows_TextChanged); // // label7 // this.label7.Location = new System.Drawing.Point(16, 130); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(100, 23); this.label7.TabIndex = 12; this.label7.Text = "Data Set Name"; // // cbDataSet // this.cbDataSet.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDataSet.Location = new System.Drawing.Point(156, 128); this.cbDataSet.Name = "cbDataSet"; this.cbDataSet.Size = new System.Drawing.Size(255, 21); this.cbDataSet.TabIndex = 6; this.cbDataSet.SelectedIndexChanged += new System.EventHandler(this.cbDataSet_SelectedIndexChanged); // // chkPageBreakStart // this.chkPageBreakStart.Location = new System.Drawing.Point(19, 249); this.chkPageBreakStart.Name = "chkPageBreakStart"; this.chkPageBreakStart.Size = new System.Drawing.Size(134, 24); this.chkPageBreakStart.TabIndex = 13; this.chkPageBreakStart.Text = "Page Break at Start"; this.chkPageBreakStart.CheckedChanged += new System.EventHandler(this.chkPageBreakStart_CheckedChanged); // // chkPageBreakEnd // this.chkPageBreakEnd.Location = new System.Drawing.Point(19, 272); this.chkPageBreakEnd.Name = "chkPageBreakEnd"; this.chkPageBreakEnd.Size = new System.Drawing.Size(134, 24); this.chkPageBreakEnd.TabIndex = 14; this.chkPageBreakEnd.Text = "Page Break at End"; this.chkPageBreakEnd.CheckedChanged += new System.EventHandler(this.chkPageBreakEnd_CheckedChanged); // // cbChartData // this.cbChartData.Location = new System.Drawing.Point(156, 153); this.cbChartData.Name = "cbChartData"; this.cbChartData.Size = new System.Drawing.Size(255, 21); this.cbChartData.TabIndex = 7; this.cbChartData.TextChanged += new System.EventHandler(this.cbChartData_Changed); // // cbDataLabel // this.cbDataLabel.Enabled = false; this.cbDataLabel.Location = new System.Drawing.Point(156, 228); this.cbDataLabel.Name = "cbDataLabel"; this.cbDataLabel.Size = new System.Drawing.Size(254, 21); this.cbDataLabel.TabIndex = 17; this.cbDataLabel.TextChanged += new System.EventHandler(this.cbChartData_Changed); // // chkDataLabel // this.chkDataLabel.AutoSize = true; this.chkDataLabel.Location = new System.Drawing.Point(19, 231); this.chkDataLabel.Name = "chkDataLabel"; this.chkDataLabel.Size = new System.Drawing.Size(75, 17); this.chkDataLabel.TabIndex = 19; this.chkDataLabel.Text = "DataLabel"; this.chkDataLabel.UseVisualStyleBackColor = true; this.chkDataLabel.CheckedChanged += new System.EventHandler(this.chkDataLabel_CheckedChanged); // // bDataLabelExpr // this.bDataLabelExpr.Enabled = false; this.bDataLabelExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)))); this.bDataLabelExpr.Location = new System.Drawing.Point(415, 228); this.bDataLabelExpr.Name = "bDataLabelExpr"; this.bDataLabelExpr.Size = new System.Drawing.Size(22, 21); this.bDataLabelExpr.TabIndex = 20; this.bDataLabelExpr.Text = "fx"; this.bDataLabelExpr.UseVisualStyleBackColor = true; this.bDataLabelExpr.Click += new System.EventHandler(this.bDataLabelExpr_Click); // // lData1 // this.lData1.Location = new System.Drawing.Point(16, 157); this.lData1.Name = "lData1"; this.lData1.Size = new System.Drawing.Size(137, 23); this.lData1.TabIndex = 16; this.lData1.Text = "Chart Data (X Coordinate)"; // // cbChartData2 // this.cbChartData2.Location = new System.Drawing.Point(156, 178); this.cbChartData2.Name = "cbChartData2"; this.cbChartData2.Size = new System.Drawing.Size(255, 21); this.cbChartData2.TabIndex = 9; this.cbChartData2.TextChanged += new System.EventHandler(this.cbChartData_Changed); // // lData2 // this.lData2.Location = new System.Drawing.Point(16, 182); this.lData2.Name = "lData2"; this.lData2.Size = new System.Drawing.Size(100, 23); this.lData2.TabIndex = 18; this.lData2.Text = "Y Coordinate"; // // cbChartData3 // this.cbChartData3.Location = new System.Drawing.Point(156, 203); this.cbChartData3.Name = "cbChartData3"; this.cbChartData3.Size = new System.Drawing.Size(255, 21); this.cbChartData3.TabIndex = 11; this.cbChartData3.TextChanged += new System.EventHandler(this.cbChartData_Changed); // // lData3 // this.lData3.Location = new System.Drawing.Point(16, 207); this.lData3.Name = "lData3"; this.lData3.Size = new System.Drawing.Size(100, 23); this.lData3.TabIndex = 20; this.lData3.Text = "Bubble Size"; // // bDataExpr // this.bDataExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bDataExpr.Location = new System.Drawing.Point(415, 153); this.bDataExpr.Name = "bDataExpr"; this.bDataExpr.Size = new System.Drawing.Size(22, 21); this.bDataExpr.TabIndex = 8; this.bDataExpr.Tag = "d1"; this.bDataExpr.Text = "fx"; this.bDataExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bDataExpr.Click += new System.EventHandler(this.bDataExpr_Click); // // bDataExpr3 // this.bDataExpr3.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bDataExpr3.Location = new System.Drawing.Point(415, 203); this.bDataExpr3.Name = "bDataExpr3"; this.bDataExpr3.Size = new System.Drawing.Size(22, 21); this.bDataExpr3.TabIndex = 12; this.bDataExpr3.Tag = "d3"; this.bDataExpr3.Text = "fx"; this.bDataExpr3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bDataExpr3.Click += new System.EventHandler(this.bDataExpr_Click); // // bDataExpr2 // this.bDataExpr2.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bDataExpr2.Location = new System.Drawing.Point(415, 178); this.bDataExpr2.Name = "bDataExpr2"; this.bDataExpr2.Size = new System.Drawing.Size(22, 21); this.bDataExpr2.TabIndex = 10; this.bDataExpr2.Tag = "d2"; this.bDataExpr2.Text = "fx"; this.bDataExpr2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bDataExpr2.Click += new System.EventHandler(this.bDataExpr_Click); // // cbVector // this.cbVector.Items.AddRange(new object[] { "False", "True"}); this.cbVector.Location = new System.Drawing.Point(330, 34); this.cbVector.Name = "cbVector"; this.cbVector.Size = new System.Drawing.Size(80, 21); this.cbVector.TabIndex = 21; this.cbVector.SelectedIndexChanged += new System.EventHandler(this.cbVector_SelectedIndexChanged); // // btnVectorExp // this.btnVectorExp.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnVectorExp.Location = new System.Drawing.Point(415, 33); this.btnVectorExp.Name = "btnVectorExp"; this.btnVectorExp.Size = new System.Drawing.Size(22, 21); this.btnVectorExp.TabIndex = 22; this.btnVectorExp.Tag = "d4"; this.btnVectorExp.Text = "fx"; this.btnVectorExp.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnVectorExp.Click += new System.EventHandler(this.bDataExpr_Click); // // label8 // this.label8.Location = new System.Drawing.Point(275, 31); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(53, 27); this.label8.TabIndex = 23; this.label8.Text = "Render As Vector"; // // button1 // this.button1.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(415, 9); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(22, 21); this.button1.TabIndex = 24; this.button1.Tag = "d7"; this.button1.Text = "fx"; this.button1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button1.Click += new System.EventHandler(this.bDataExpr_Click); // // button2 // this.button2.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.Location = new System.Drawing.Point(251, 9); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(22, 21); this.button2.TabIndex = 25; this.button2.Tag = "d5"; this.button2.Text = "fx"; this.button2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button2.Visible = false; this.button2.Click += new System.EventHandler(this.bDataExpr_Click); // // button3 // this.button3.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button3.Location = new System.Drawing.Point(251, 34); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(22, 21); this.button3.TabIndex = 26; this.button3.Tag = "d6"; this.button3.Text = "fx"; this.button3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button3.Click += new System.EventHandler(this.bDataExpr_Click); // // chkToolTip // this.chkToolTip.AutoSize = true; this.chkToolTip.Location = new System.Drawing.Point(201, 255); this.chkToolTip.Name = "chkToolTip"; this.chkToolTip.Size = new System.Drawing.Size(79, 17); this.chkToolTip.TabIndex = 27; this.chkToolTip.Text = "Y Tooltips?"; this.chkToolTip.UseVisualStyleBackColor = true; this.chkToolTip.CheckedChanged += new System.EventHandler(this.chkToolTip_CheckedChanged); // // checkBox1 // this.checkBox1.AutoSize = true; this.checkBox1.Location = new System.Drawing.Point(201, 274); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(79, 17); this.checkBox1.TabIndex = 28; this.checkBox1.Text = "X Tooltips?"; this.checkBox1.UseVisualStyleBackColor = true; this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged); // // txtYToolFormat // this.txtYToolFormat.Location = new System.Drawing.Point(331, 253); this.txtYToolFormat.Name = "txtYToolFormat"; this.txtYToolFormat.Size = new System.Drawing.Size(78, 20); this.txtYToolFormat.TabIndex = 29; this.txtYToolFormat.TextChanged += new System.EventHandler(this.txtYToolFormat_TextChanged); // // txtXToolFormat // this.txtXToolFormat.Location = new System.Drawing.Point(331, 273); this.txtXToolFormat.Name = "txtXToolFormat"; this.txtXToolFormat.Size = new System.Drawing.Size(78, 20); this.txtXToolFormat.TabIndex = 30; this.txtXToolFormat.TextChanged += new System.EventHandler(this.txtXToolFormat_TextChanged); // // label9 // this.label9.Location = new System.Drawing.Point(286, 256); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(42, 19); this.label9.TabIndex = 31; this.label9.Text = "Format"; // // label10 // this.label10.Location = new System.Drawing.Point(286, 276); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(42, 19); this.label10.TabIndex = 32; this.label10.Text = "Format"; // // ChartCtl // this.Controls.Add(this.label10); this.Controls.Add(this.label9); this.Controls.Add(this.txtXToolFormat); this.Controls.Add(this.txtYToolFormat); this.Controls.Add(this.checkBox1); this.Controls.Add(this.chkToolTip); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.label8); this.Controls.Add(this.btnVectorExp); this.Controls.Add(this.cbVector); this.Controls.Add(this.bDataExpr2); this.Controls.Add(this.bDataExpr3); this.Controls.Add(this.bDataExpr); this.Controls.Add(this.cbChartData3); this.Controls.Add(this.lData3); this.Controls.Add(this.cbChartData2); this.Controls.Add(this.lData2); this.Controls.Add(this.bDataLabelExpr); this.Controls.Add(this.chkDataLabel); this.Controls.Add(this.cbDataLabel); this.Controls.Add(this.cbChartData); this.Controls.Add(this.lData1); this.Controls.Add(this.chkPageBreakEnd); this.Controls.Add(this.chkPageBreakStart); this.Controls.Add(this.cbDataSet); this.Controls.Add(this.label7); this.Controls.Add(this.tbNoRows); this.Controls.Add(this.label6); this.Controls.Add(this.tbPercentWidth); this.Controls.Add(this.label5); this.Controls.Add(this.cbRenderElement); this.Controls.Add(this.cbPalette); this.Controls.Add(this.cbSubType); this.Controls.Add(this.cbChartType); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "ChartCtl"; this.Size = new System.Drawing.Size(440, 303); ((System.ComponentModel.ISupportInitialize)(this.tbPercentWidth)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public bool IsValid() { return true; } public void Apply() { // take information in control and apply to all the style nodes // Only change information that has been marked as modified; // this way when group is selected it is possible to change just // the items you want and keep the rest the same. foreach (XmlNode riNode in this._ReportItems) ApplyChanges(riNode); // No more changes //AJM GJL 14082008 fChartType = fVector = fSubtype = fPalette = fRenderElement = fPercentWidth = fNoRows = fDataSet = fPageBreakStart = fPageBreakEnd = fChartData = ftooltip = ftooltipX = ftooltip = ftooltipX = false; } public void ApplyChanges(XmlNode node) { if (fChartType) { _Draw.SetElement(node, "Type", this.cbChartType.Text); } if (ftooltip)//now controls the displaying of Y value { _Draw.SetElement(node, "fyi:Tooltip", this.chkToolTip.Checked.ToString()); } if (ftooltipX)// controls the displaying of X value { _Draw.SetElement(node, "fyi:TooltipX", this.chkToolTip.Checked.ToString()); } if (tooltipXFormat) { _Draw.SetElement(node, "fyi:TooltipXFormat", this.txtXToolFormat.Text); } if (tooltipYFormat) { _Draw.SetElement(node, "fyi:TooltipYFormat", this.txtYToolFormat.Text); } if (fVector) //AJM GJL 14082008 { _Draw.SetElement(node, "fyi:RenderAsVector", this.cbVector.Text); } if (fSubtype) { _Draw.SetElement(node, "Subtype", this.cbSubType.Text); } if (fPalette) { _Draw.SetElement(node, "Palette", this.cbPalette.Text); } if (fRenderElement) { _Draw.SetElement(node, "ChartElementOutput", this.cbRenderElement.Text); } if (fPercentWidth) { _Draw.SetElement(node, "PointWidth", this.tbPercentWidth.Text); } if (fNoRows) { _Draw.SetElement(node, "NoRows", this.tbNoRows.Text); } if (fDataSet) { _Draw.SetElement(node, "DataSetName", this.cbDataSet.Text); } if (fPageBreakStart) { _Draw.SetElement(node, "PageBreakAtStart", this.chkPageBreakStart.Checked? "true": "false"); } if (fPageBreakEnd) { _Draw.SetElement(node, "PageBreakAtEnd", this.chkPageBreakEnd.Checked? "true": "false"); } if (fChartData) { // <ChartData> // <ChartSeries> // <DataPoints> // <DataPoint> // <DataValues> // <DataValue> // <Value>=Sum(Fields!Sales.Value)</Value> // </DataValue> --- you can have up to 3 DataValue elements // </DataValues> // <DataLabel> // <Style> // <Format>c</Format> // </Style> // </DataLabel> // <Marker /> // </DataPoint> // </DataPoints> // </ChartSeries> // </ChartData> XmlNode chartdata = _Draw.SetElement(node, "ChartData", null); XmlNode chartseries = _Draw.SetElement(chartdata, "ChartSeries", null); XmlNode datapoints = _Draw.SetElement(chartseries, "DataPoints", null); XmlNode datapoint = _Draw.SetElement(datapoints, "DataPoint", null); XmlNode datavalues = _Draw.SetElement(datapoint, "DataValues", null); _Draw.RemoveElementAll(datavalues, "DataValue"); XmlNode datalabel = _Draw.SetElement(datapoint, "DataLabel", null); XmlNode datavalue = _Draw.SetElement(datavalues, "DataValue", null); _Draw.SetElement(datavalue, "Value", this.cbChartData.Text); string type = cbChartType.Text.ToLowerInvariant(); if (type == "scatter" || type == "bubble") { datavalue = _Draw.CreateElement(datavalues, "DataValue", null); _Draw.SetElement(datavalue, "Value", this.cbChartData2.Text); if (type == "bubble") { datavalue = _Draw.CreateElement(datavalues, "DataValue", null); _Draw.SetElement(datavalue, "Value", this.cbChartData3.Text); } } _Draw.SetElement(datalabel, "Value", this.cbDataLabel.Text); _Draw.SetElement(datalabel, "Visible", this.chkDataLabel.Checked.ToString()); } } private void cbChartType_SelectedIndexChanged(object sender, System.EventArgs e) { fChartType = true; // Change the potential sub-types string savesub = cbSubType.Text; string[] subItems = new string [] {"Plain"}; bool bEnableY = false; bool bEnableBubble = false; switch (cbChartType.Text) { case "Column": subItems = new string [] {"Plain", "Stacked", "PercentStacked"}; break; case "Bar": subItems = new string [] {"Plain", "Stacked", "PercentStacked"}; break; case "Line": subItems = new string [] {"Plain", "Smooth"}; break; case "Pie": subItems = new string [] {"Plain", "Exploded"}; break; case "Area": subItems = new string [] {"Plain", "Stacked"}; break; case "Doughnut": break; case "Map": subItems = RdlDesigner.MapSubtypes; break; case "Scatter": subItems = new string [] {"Plain", "Line", "SmoothLine"}; bEnableY = true; break; case "Stock": break; case "Bubble": bEnableY = bEnableBubble = true; break; default: break; } cbSubType.Items.Clear(); cbSubType.Items.AddRange(subItems); lData2.Enabled = cbChartData2.Enabled = bDataExpr2.Enabled = bEnableY; lData3.Enabled = cbChartData3.Enabled = bDataExpr3.Enabled = bEnableBubble; int i=0; foreach (string s in subItems) { if (s == savesub) { cbSubType.SelectedIndex = i; return; } i++; } // Didn't match old style cbSubType.SelectedIndex = 0; } //AJM GJL 14082008 private void cbVector_SelectedIndexChanged(object sender, EventArgs e) { fVector = true; } private void cbSubType_SelectedIndexChanged(object sender, System.EventArgs e) { fSubtype = true; } private void cbPalette_SelectedIndexChanged(object sender, System.EventArgs e) { fPalette = true; } private void cbRenderElement_SelectedIndexChanged(object sender, System.EventArgs e) { fRenderElement = true; } private void tbPercentWidth_ValueChanged(object sender, System.EventArgs e) { fPercentWidth = true; } private void tbNoRows_TextChanged(object sender, System.EventArgs e) { fNoRows = true; } private void cbDataSet_SelectedIndexChanged(object sender, System.EventArgs e) { fDataSet = true; } private void chkPageBreakStart_CheckedChanged(object sender, System.EventArgs e) { fPageBreakStart = true; } private void chkPageBreakEnd_CheckedChanged(object sender, System.EventArgs e) { fPageBreakEnd = true; } private void cbChartData_Changed(object sender, System.EventArgs e) { fChartData = true; } private void bDataExpr_Click(object sender, System.EventArgs e) { Button bs = sender as Button; if (bs == null) return; Control ctl = null; switch (bs.Tag as string) { case "d1": ctl = cbChartData; break; case "d2": ctl = cbChartData2; break; case "d3": ctl = cbChartData3; break; //AJM GJL 14082008 case "d4": ctl = cbVector; fVector = true; break; case "d5": ctl = cbChartType; fChartType = true; break; case "d6": ctl = cbPalette; fPalette = true; break; case "d7": ctl = cbSubType; fSubtype = true; break; default: return; } DialogExprEditor ee = new DialogExprEditor(_Draw, ctl.Text, _ReportItems[0], false); try { DialogResult dlgr = ee.ShowDialog(); if (dlgr == DialogResult.OK) { ctl.Text = ee.Expression; fChartData = true; } } finally { ee.Dispose(); } } private void chkDataLabel_CheckedChanged(object sender, EventArgs e) { cbDataLabel.Enabled = bDataLabelExpr.Enabled = chkDataLabel.Checked; } private void bDataLabelExpr_Click(object sender, EventArgs e) { DialogExprEditor ee = new DialogExprEditor(_Draw, cbDataLabel.Text,_ReportItems[0] , false); try { if (ee.ShowDialog() == DialogResult.OK) { cbDataLabel.Text = ee.Expression; } } finally { ee.Dispose(); } return; } private void chkToolTip_CheckedChanged(object sender, EventArgs e) { ftooltip = true; } private void checkBox1_CheckedChanged(object sender, EventArgs e) { ftooltipX = true; } private void txtYToolFormat_TextChanged(object sender, EventArgs e) { tooltipYFormat = true; } private void txtXToolFormat_TextChanged(object sender, EventArgs e) { tooltipXFormat = true; } } }
// 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.Batch.Protocol.Models { using System.Linq; /// <summary> /// An Azure Batch job to add. /// </summary> public partial class JobAddParameter { /// <summary> /// Initializes a new instance of the JobAddParameter class. /// </summary> public JobAddParameter() { } /// <summary> /// Initializes a new instance of the JobAddParameter class. /// </summary> /// <param name="id">A string that uniquely identifies the job within /// the account.</param> /// <param name="poolInfo">The pool on which the Batch service runs the /// job's tasks.</param> /// <param name="displayName">The display name for the job.</param> /// <param name="priority">The priority of the job.</param> /// <param name="constraints">The execution constraints for the /// job.</param> /// <param name="jobManagerTask">Details of a Job Manager task to be /// launched when the job is started.</param> /// <param name="jobPreparationTask">The Job Preparation task.</param> /// <param name="jobReleaseTask">The Job Release task.</param> /// <param name="commonEnvironmentSettings">The list of common /// environment variable settings. These environment variables are set /// for all tasks in the job (including the Job Manager, Job /// Preparation and Job Release tasks).</param> /// <param name="onAllTasksComplete">The action the Batch service /// should take when all tasks in the job are in the completed /// state.</param> /// <param name="onTaskFailure">The action the Batch service should /// take when any task in the job fails. A task is considered to have /// failed if it completes with a non-zero exit code and has exhausted /// its retry count, or if it had a scheduling error.</param> /// <param name="metadata">A list of name-value pairs associated with /// the job as metadata.</param> /// <param name="usesTaskDependencies">The flag that determines if this /// job will use tasks with dependencies.</param> public JobAddParameter(string id, PoolInformation poolInfo, string displayName = default(string), int? priority = default(int?), JobConstraints constraints = default(JobConstraints), JobManagerTask jobManagerTask = default(JobManagerTask), JobPreparationTask jobPreparationTask = default(JobPreparationTask), JobReleaseTask jobReleaseTask = default(JobReleaseTask), System.Collections.Generic.IList<EnvironmentSetting> commonEnvironmentSettings = default(System.Collections.Generic.IList<EnvironmentSetting>), OnAllTasksComplete? onAllTasksComplete = default(OnAllTasksComplete?), OnTaskFailure? onTaskFailure = default(OnTaskFailure?), System.Collections.Generic.IList<MetadataItem> metadata = default(System.Collections.Generic.IList<MetadataItem>), bool? usesTaskDependencies = default(bool?)) { this.Id = id; this.DisplayName = displayName; this.Priority = priority; this.Constraints = constraints; this.JobManagerTask = jobManagerTask; this.JobPreparationTask = jobPreparationTask; this.JobReleaseTask = jobReleaseTask; this.CommonEnvironmentSettings = commonEnvironmentSettings; this.PoolInfo = poolInfo; this.OnAllTasksComplete = onAllTasksComplete; this.OnTaskFailure = onTaskFailure; this.Metadata = metadata; this.UsesTaskDependencies = usesTaskDependencies; } /// <summary> /// Gets or sets a string that uniquely identifies the job within the /// account. /// </summary> /// <remarks> /// The ID can contain any combination of alphanumeric characters /// including hyphens and underscores, and cannot contain more than 64 /// characters. It is common to use a GUID for the id. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets the display name for the job. /// </summary> /// <remarks> /// The display name need not be unique and can contain any Unicode /// characters up to a maximum length of 1024. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "displayName")] public string DisplayName { get; set; } /// <summary> /// Gets or sets the priority of the job. /// </summary> /// <remarks> /// Priority values can range from -1000 to 1000, with -1000 being the /// lowest priority and 1000 being the highest priority. The default /// value is 0. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "priority")] public int? Priority { get; set; } /// <summary> /// Gets or sets the execution constraints for the job. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "constraints")] public JobConstraints Constraints { get; set; } /// <summary> /// Gets or sets details of a Job Manager task to be launched when the /// job is started. /// </summary> /// <remarks> /// If the job does not specify a Job Manager task, the user must /// explicitly add tasks to the job. If the job does specify a Job /// Manager task, the Batch service creates the Job Manager task when /// the job is created, and will try to schedule the Job Manager task /// before scheduling other tasks in the job. The Job Manager task's /// typical purpose is to control and/or monitor job execution, for /// example by deciding what additional tasks to run, determining when /// the work is complete, etc. (However, a Job Manager task is not /// restricted to these activities - it is a fully-fledged task in the /// system and perform whatever actions are required for the job.) For /// example, a Job Manager task might download a file specified as a /// parameter, analyze the contents of that file and submit additional /// tasks based on those contents. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "jobManagerTask")] public JobManagerTask JobManagerTask { get; set; } /// <summary> /// Gets or sets the Job Preparation task. /// </summary> /// <remarks> /// If a job has a Job Preparation task, the Batch service will run the /// Job Preparation task on a compute node before starting any tasks of /// that job on that compute node. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "jobPreparationTask")] public JobPreparationTask JobPreparationTask { get; set; } /// <summary> /// Gets or sets the Job Release task. /// </summary> /// <remarks> /// A Job Release task cannot be specified without also specifying a /// Job Preparation task for the job. The Batch service runs the Job /// Release task on the compute nodes that have run the Job Preparation /// task. The primary purpose of the Job Release task is to undo /// changes to compute nodes made by the Job Preparation task. Example /// activities include deleting local files, or shutting down services /// that were started as part of job preparation. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "jobReleaseTask")] public JobReleaseTask JobReleaseTask { get; set; } /// <summary> /// Gets or sets the list of common environment variable settings. /// These environment variables are set for all tasks in the job /// (including the Job Manager, Job Preparation and Job Release tasks). /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "commonEnvironmentSettings")] public System.Collections.Generic.IList<EnvironmentSetting> CommonEnvironmentSettings { get; set; } /// <summary> /// Gets or sets the pool on which the Batch service runs the job's /// tasks. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "poolInfo")] public PoolInformation PoolInfo { get; set; } /// <summary> /// Gets or sets the action the Batch service should take when all /// tasks in the job are in the completed state. /// </summary> /// <remarks> /// Note that if a job contains no tasks, then all tasks are considered /// complete. This option is therefore most commonly used with a Job /// Manager task; if you want to use automatic job termination without /// a Job Manager, you should initially set onAllTasksComplete to /// noAction and update the job properties to set onAllTasksComplete to /// terminateJob once you have finished adding tasks. Permitted values /// are: noAction - do nothing. The job remains active unless /// terminated or disabled by some other means. terminateJob - /// terminate the job. The job's terminateReason is set to /// 'AllTasksComplete'. The default is noAction. Possible values /// include: 'noAction', 'terminateJob' /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "onAllTasksComplete")] public OnAllTasksComplete? OnAllTasksComplete { get; set; } /// <summary> /// Gets or sets the action the Batch service should take when any task /// in the job fails. A task is considered to have failed if it /// completes with a non-zero exit code and has exhausted its retry /// count, or if it had a scheduling error. /// </summary> /// <remarks> /// noAction - do nothing. performExitOptionsJobAction - take the /// action associated with the task exit condition in the task's /// exitConditions collection. (This may still result in no action /// being taken, if that is what the task specifies.) The default is /// noAction. Possible values include: 'noAction', /// 'performExitOptionsJobAction' /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "onTaskFailure")] public OnTaskFailure? OnTaskFailure { get; set; } /// <summary> /// Gets or sets a list of name-value pairs associated with the job as /// metadata. /// </summary> /// <remarks> /// The Batch service does not assign any meaning to metadata; it is /// solely for the use of user code. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "metadata")] public System.Collections.Generic.IList<MetadataItem> Metadata { get; set; } /// <summary> /// Gets or sets the flag that determines if this job will use tasks /// with dependencies. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "usesTaskDependencies")] public bool? UsesTaskDependencies { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (this.Id == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "Id"); } if (this.PoolInfo == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "PoolInfo"); } if (this.JobManagerTask != null) { this.JobManagerTask.Validate(); } if (this.JobPreparationTask != null) { this.JobPreparationTask.Validate(); } if (this.JobReleaseTask != null) { this.JobReleaseTask.Validate(); } if (this.CommonEnvironmentSettings != null) { foreach (var element in this.CommonEnvironmentSettings) { if (element != null) { element.Validate(); } } } if (this.PoolInfo != null) { this.PoolInfo.Validate(); } if (this.Metadata != null) { foreach (var element1 in this.Metadata) { if (element1 != null) { element1.Validate(); } } } } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // .NET Compact Framework 1.0 has no support for System.Runtime.Remoting.Messaging.CallContext #if !NETCF using System; using System.Runtime.Remoting.Messaging; using System.Security; namespace log4net.Util { /// <summary> /// Implementation of Properties collection for the <see cref="log4net.LogicalThreadContext"/> /// </summary> /// <remarks> /// <para> /// Class implements a collection of properties that is specific to each thread. /// The class is not synchronized as each thread has its own <see cref="PropertiesDictionary"/>. /// </para> /// <para> /// This class stores its properties in a slot on the <see cref="CallContext"/> named /// <c>log4net.Util.LogicalThreadContextProperties</c>. /// </para> /// <para> /// The <see cref="CallContext"/> requires a link time /// <see cref="System.Security.Permissions.SecurityPermission"/> for the /// <see cref="System.Security.Permissions.SecurityPermissionFlag.Infrastructure"/>. /// If the calling code does not have this permission then this context will be disabled. /// It will not store any property values set on it. /// </para> /// </remarks> /// <author>Nicko Cadell</author> public sealed class LogicalThreadContextProperties : ContextPropertiesBase { private const string c_SlotName = "log4net.Util.LogicalThreadContextProperties"; /// <summary> /// Flag used to disable this context if we don't have permission to access the CallContext. /// </summary> private bool m_disabled = false; #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LogicalThreadContextProperties" /> class. /// </para> /// </remarks> internal LogicalThreadContextProperties() { } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the value of a property /// </summary> /// <value> /// The value for the property with the specified key /// </value> /// <remarks> /// <para> /// Get or set the property value for the <paramref name="key"/> specified. /// </para> /// </remarks> override public object this[string key] { get { // Don't create the dictionary if it does not already exist PropertiesDictionary dictionary = GetProperties(false); if (dictionary != null) { return dictionary[key]; } return null; } set { // Force the dictionary to be created var props = GetProperties(true); // Reason for cloning the dictionary below: object instances set on the CallContext // need to be immutable to correctly flow through async/await var immutableProps = new PropertiesDictionary(props); immutableProps[key] = value; SetCallContextData(immutableProps); } } #endregion Public Instance Properties #region Public Instance Methods /// <summary> /// Remove a property /// </summary> /// <param name="key">the key for the entry to remove</param> /// <remarks> /// <para> /// Remove the value for the specified <paramref name="key"/> from the context. /// </para> /// </remarks> public void Remove(string key) { PropertiesDictionary dictionary = GetProperties(false); if (dictionary != null) { var immutableProps = new PropertiesDictionary(dictionary); immutableProps.Remove(key); SetCallContextData(immutableProps); } } /// <summary> /// Clear all the context properties /// </summary> /// <remarks> /// <para> /// Clear all the context properties /// </para> /// </remarks> public void Clear() { PropertiesDictionary dictionary = GetProperties(false); if (dictionary != null) { var immutableProps = new PropertiesDictionary(); SetCallContextData(immutableProps); } } #endregion Public Instance Methods #region Internal Instance Methods /// <summary> /// Get the PropertiesDictionary stored in the LocalDataStoreSlot for this thread. /// </summary> /// <param name="create">create the dictionary if it does not exist, otherwise return null if is does not exist</param> /// <returns>the properties for this thread</returns> /// <remarks> /// <para> /// The collection returned is only to be used on the calling thread. If the /// caller needs to share the collection between different threads then the /// caller must clone the collection before doings so. /// </para> /// </remarks> internal PropertiesDictionary GetProperties(bool create) { if (!m_disabled) { try { PropertiesDictionary properties = GetCallContextData(); if (properties == null && create) { properties = new PropertiesDictionary(); SetCallContextData(properties); } return properties; } catch (SecurityException secEx) { m_disabled = true; // Thrown if we don't have permission to read or write the CallContext LogLog.Warn(declaringType, "SecurityException while accessing CallContext. Disabling LogicalThreadContextProperties", secEx); } } // Only get here is we are disabled because of a security exception if (create) { return new PropertiesDictionary(); } return null; } #endregion Internal Instance Methods #region Private Static Methods /// <summary> /// Gets the call context get data. /// </summary> /// <returns>The peroperties dictionary stored in the call context</returns> /// <remarks> /// The <see cref="CallContext"/> method <see cref="CallContext.GetData"/> has a /// security link demand, therfore we must put the method call in a seperate method /// that we can wrap in an exception handler. /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif private static PropertiesDictionary GetCallContextData() { #if !NETCF return CallContext.LogicalGetData(c_SlotName) as PropertiesDictionary; #else return CallContext.GetData(c_SlotName) as PropertiesDictionary; #endif } /// <summary> /// Sets the call context data. /// </summary> /// <param name="properties">The properties.</param> /// <remarks> /// The <see cref="CallContext"/> method <see cref="CallContext.SetData"/> has a /// security link demand, therfore we must put the method call in a seperate method /// that we can wrap in an exception handler. /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif private static void SetCallContextData(PropertiesDictionary properties) { #if !NETCF CallContext.LogicalSetData(c_SlotName, properties); #else CallContext.SetData(c_SlotName, properties); #endif } #endregion #region Private Static Fields /// <summary> /// The fully qualified type of the LogicalThreadContextProperties class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(LogicalThreadContextProperties); #endregion Private Static Fields } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Threading.Tasks; using Microsoft.PowerShell.MarkdownRender; namespace Microsoft.PowerShell.Commands { /// <summary> /// Class for implementing Set-MarkdownOption cmdlet. /// </summary> [Cmdlet( VerbsCommon.Set, "MarkdownOption", DefaultParameterSetName = IndividualSetting, HelpUri = "https://go.microsoft.com/fwlink/?linkid=2006265")] [OutputType(typeof(Microsoft.PowerShell.MarkdownRender.PSMarkdownOptionInfo))] public class SetMarkdownOptionCommand : PSCmdlet { /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 1. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header1Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 2. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header2Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 3. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header3Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 4. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header4Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 5. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header5Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 6. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header6Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for code block background. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Code { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for image alt text foreground. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string ImageAltTextForegroundColor { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for link foreground. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string LinkForegroundColor { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for italics text foreground. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string ItalicsForegroundColor { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for bold text foreground. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string BoldForegroundColor { get; set; } /// <summary> /// Gets or sets the switch to PassThru the values set. /// </summary> [Parameter] public SwitchParameter PassThru { get; set; } /// <summary> /// Gets or sets the Theme. /// </summary> [ValidateNotNullOrEmpty] [Parameter(ParameterSetName = ThemeParamSet, Mandatory = true)] [ValidateSet(DarkThemeName, LightThemeName)] public string Theme { get; set; } /// <summary> /// Gets or sets InputObject. /// </summary> [ValidateNotNullOrEmpty] [Parameter(ParameterSetName = InputObjectParamSet, Mandatory = true, ValueFromPipeline = true, Position = 0)] public PSObject InputObject { get; set; } private const string IndividualSetting = "IndividualSetting"; private const string InputObjectParamSet = "InputObject"; private const string ThemeParamSet = "Theme"; private const string MarkdownOptionInfoVariableName = "PSMarkdownOptionInfo"; private const string LightThemeName = "Light"; private const string DarkThemeName = "Dark"; /// <summary> /// Override EndProcessing. /// </summary> protected override void EndProcessing() { PSMarkdownOptionInfo mdOptionInfo = null; switch (ParameterSetName) { case ThemeParamSet: mdOptionInfo = new PSMarkdownOptionInfo(); if (string.Equals(Theme, LightThemeName, StringComparison.OrdinalIgnoreCase)) { mdOptionInfo.SetLightTheme(); } else if (string.Equals(Theme, DarkThemeName, StringComparison.OrdinalIgnoreCase)) { mdOptionInfo.SetDarkTheme(); } break; case InputObjectParamSet: object baseObj = InputObject.BaseObject; mdOptionInfo = baseObj as PSMarkdownOptionInfo; if (mdOptionInfo == null) { var errorMessage = StringUtil.Format(ConvertMarkdownStrings.InvalidInputObjectType, baseObj.GetType()); ErrorRecord errorRecord = new ErrorRecord( new ArgumentException(errorMessage), "InvalidObject", ErrorCategory.InvalidArgument, InputObject); } break; case IndividualSetting: mdOptionInfo = new PSMarkdownOptionInfo(); SetOptions(mdOptionInfo); break; } this.CommandInfo.Module.SessionState.PSVariable.Set(MarkdownOptionInfoVariableName, mdOptionInfo); if(PassThru.IsPresent) { WriteObject(mdOptionInfo); } } private void SetOptions(PSMarkdownOptionInfo mdOptionInfo) { if (!string.IsNullOrEmpty(Header1Color)) { mdOptionInfo.Header1 = Header1Color; } if (!string.IsNullOrEmpty(Header2Color)) { mdOptionInfo.Header2 = Header2Color; } if (!string.IsNullOrEmpty(Header3Color)) { mdOptionInfo.Header3 = Header3Color; } if (!string.IsNullOrEmpty(Header4Color)) { mdOptionInfo.Header4 = Header4Color; } if (!string.IsNullOrEmpty(Header5Color)) { mdOptionInfo.Header5 = Header5Color; } if (!string.IsNullOrEmpty(Header6Color)) { mdOptionInfo.Header6 = Header6Color; } if (!string.IsNullOrEmpty(Code)) { mdOptionInfo.Code = Code; } if (!string.IsNullOrEmpty(ImageAltTextForegroundColor)) { mdOptionInfo.Image = ImageAltTextForegroundColor; } if (!string.IsNullOrEmpty(LinkForegroundColor)) { mdOptionInfo.Link = LinkForegroundColor; } if (!string.IsNullOrEmpty(ItalicsForegroundColor)) { mdOptionInfo.EmphasisItalics = ItalicsForegroundColor; } if (!string.IsNullOrEmpty(BoldForegroundColor)) { mdOptionInfo.EmphasisBold = BoldForegroundColor; } } } /// <summary> /// Implements the cmdlet for getting the Markdown options that are set. /// </summary> [Cmdlet( VerbsCommon.Get, "MarkdownOption", HelpUri = "https://go.microsoft.com/fwlink/?linkid=2006371")] [OutputType(typeof(Microsoft.PowerShell.MarkdownRender.PSMarkdownOptionInfo))] public class GetMarkdownOptionCommand : PSCmdlet { private const string MarkdownOptionInfoVariableName = "PSMarkdownOptionInfo"; /// <summary> /// Override EndProcessing. /// </summary> protected override void EndProcessing() { WriteObject(this.CommandInfo.Module.SessionState.PSVariable.GetValue(MarkdownOptionInfoVariableName, new PSMarkdownOptionInfo())); } } }
//----------------------------------------------------------------------- // <copyright file="ActorMaterializer.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Runtime.Serialization; using Akka.Actor; using Akka.Configuration; using Akka.Dispatch; using Akka.Event; using Akka.Pattern; using Akka.Streams.Dsl; using Akka.Streams.Dsl.Internal; using Akka.Streams.Implementation; using Akka.Streams.Supervision; using Akka.Util; using Reactive.Streams; using Decider = Akka.Streams.Supervision.Decider; namespace Akka.Streams { /// <summary> /// A ActorMaterializer takes the list of transformations comprising a /// <see cref="IFlow{TOut,TMat}"/> and materializes them in the form of /// <see cref="IProcessor{T1,T2}"/> instances. How transformation /// steps are split up into asynchronous regions is implementation /// dependent. /// </summary> public abstract class ActorMaterializer : IMaterializer, IDisposable { public static Config DefaultConfig() => ConfigurationFactory.FromResource<ActorMaterializer>("Akka.Streams.reference.conf"); #region static /// <summary> /// <para> /// Creates a ActorMaterializer which will execute every step of a transformation /// pipeline within its own <see cref="ActorBase"/>. The required <see cref="IActorRefFactory"/> /// (which can be either an <see cref="ActorSystem"/> or an <see cref="IActorContext"/>) /// will be used to create one actor that in turn creates actors for the transformation steps. /// </para> /// <para> /// The materializer's <see cref="ActorMaterializerSettings"/> will be obtained from the /// configuration of the <paramref name="context"/>'s underlying <see cref="ActorSystem"/>. /// </para> /// <para> /// The <paramref name="namePrefix"/> is used as the first part of the names of the actors running /// the processing steps. The default <paramref name="namePrefix"/> is "flow". The actor names are built up of /// `namePrefix-flowNumber-flowStepNumber-stepName`. /// </para> /// </summary> public static ActorMaterializer Create(IActorRefFactory context, ActorMaterializerSettings settings = null, string namePrefix = null) { var haveShutDown = new AtomicBoolean(); var system = ActorSystemOf(context); system.Settings.InjectTopLevelFallback(DefaultConfig()); settings = settings ?? ActorMaterializerSettings.Create(system); return new ActorMaterializerImpl( system: system, settings: settings, dispatchers: system.Dispatchers, supervisor: context.ActorOf(StreamSupervisor.Props(settings, haveShutDown).WithDispatcher(settings.Dispatcher), StreamSupervisor.NextName()), haveShutDown: haveShutDown, flowNames: EnumerableActorName.Create(namePrefix ?? "Flow")); } private static ActorSystem ActorSystemOf(IActorRefFactory context) { if (context is ExtendedActorSystem) return (ActorSystem)context; if (context is IActorContext) return ((IActorContext)context).System; if (context == null) throw new ArgumentNullException(nameof(context), "IActorRefFactory must be defined"); throw new ArgumentException($"ActorRefFactory context must be a ActorSystem or ActorContext, got [{context.GetType()}]"); } #endregion public abstract ActorMaterializerSettings Settings { get; } /// <summary> /// Indicates if the materializer has been shut down. /// </summary> public abstract bool IsShutdown { get; } public abstract MessageDispatcher ExecutionContext { get; } public abstract ActorSystem System { get; } public abstract ILoggingAdapter Logger { get; } public abstract IActorRef Supervisor { get; } public abstract IMaterializer WithNamePrefix(string namePrefix); public abstract TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable); public abstract ICancelable ScheduleOnce(TimeSpan delay, Action action); public abstract ICancelable ScheduleRepeatedly(TimeSpan initialDelay, TimeSpan interval, Action action); public abstract ActorMaterializerSettings EffectiveSettings(Attributes attributes); /// <summary> /// Shuts down this materializer and all the stages that have been materialized through this materializer. After /// having shut down, this materializer cannot be used again. Any attempt to materialize stages after having /// shut down will result in an <see cref="IllegalStateException"/> being thrown at materialization time. /// </summary> public abstract void Shutdown(); public abstract IActorRef ActorOf(MaterializationContext context, Props props); public void Dispose() => Shutdown(); } /// <summary> /// INTERNAL API /// </summary> internal static class ActorMaterializerHelper { internal static ActorMaterializer Downcast(IMaterializer materializer) { //FIXME this method is going to cause trouble for other Materializer implementations var downcast = materializer as ActorMaterializer; if (downcast != null) return downcast; throw new ArgumentException($"Expected {typeof(ActorMaterializer)} but got {materializer.GetType()}"); } } /// <summary> /// This exception signals that an actor implementing a Reactive Streams Subscriber, Publisher or Processor /// has been terminated without being notified by an onError, onComplete or cancel signal. This usually happens /// when an ActorSystem is shut down while stream processing actors are still running. /// </summary> [Serializable] public class AbruptTerminationException : Exception { public readonly IActorRef Actor; public AbruptTerminationException(IActorRef actor) : base($"Processor actor [{actor}] terminated abruptly") { Actor = actor; } protected AbruptTerminationException(SerializationInfo info, StreamingContext context) : base(info, context) { Actor = (IActorRef)info.GetValue("Actor", typeof(IActorRef)); } } /// <summary> /// This exception or subtypes thereof should be used to signal materialization failures. /// </summary> public class MaterializationException : Exception { public MaterializationException(string message, Exception innerException) : base(message, innerException) { } protected MaterializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// This class describes the configurable properties of the <see cref="ActorMaterializer"/>. /// Please refer to the withX methods for descriptions of the individual settings. /// </summary> public sealed class ActorMaterializerSettings { public static ActorMaterializerSettings Create(ActorSystem system) { var config = system.Settings.Config.GetConfig("akka.stream.materializer"); return Create(config ?? Config.Empty); } private static ActorMaterializerSettings Create(Config config) { return new ActorMaterializerSettings( initialInputBufferSize: config.GetInt("initial-input-buffer-size", 4), maxInputBufferSize: config.GetInt("max-input-buffer-size", 16), dispatcher: config.GetString("dispatcher", string.Empty), supervisionDecider: Deciders.StoppingDecider, subscriptionTimeoutSettings: StreamSubscriptionTimeoutSettings.Create(config), isDebugLogging: config.GetBoolean("debug-logging"), outputBurstLimit: config.GetInt("output-burst-limit", 1000), isFuzzingMode: config.GetBoolean("debug.fuzzing-mode"), isAutoFusing: config.GetBoolean("auto-fusing", true), maxFixedBufferSize: config.GetInt("max-fixed-buffer-size", 1000000000), syncProcessingLimit: config.GetInt("sync-processing-limit", 1000)); } private const int DefaultlMaxFixedbufferSize = 1000; public readonly int InitialInputBufferSize; public readonly int MaxInputBufferSize; public readonly string Dispatcher; public readonly Decider SupervisionDecider; public readonly StreamSubscriptionTimeoutSettings SubscriptionTimeoutSettings; public readonly bool IsDebugLogging; public readonly int OutputBurstLimit; public readonly bool IsFuzzingMode; public readonly bool IsAutoFusing; public readonly int MaxFixedBufferSize; public readonly int SyncProcessingLimit; public ActorMaterializerSettings(int initialInputBufferSize, int maxInputBufferSize, string dispatcher, Decider supervisionDecider, StreamSubscriptionTimeoutSettings subscriptionTimeoutSettings, bool isDebugLogging, int outputBurstLimit, bool isFuzzingMode, bool isAutoFusing, int maxFixedBufferSize, int syncProcessingLimit = DefaultlMaxFixedbufferSize) { InitialInputBufferSize = initialInputBufferSize; MaxInputBufferSize = maxInputBufferSize; Dispatcher = dispatcher; SupervisionDecider = supervisionDecider; SubscriptionTimeoutSettings = subscriptionTimeoutSettings; IsDebugLogging = isDebugLogging; OutputBurstLimit = outputBurstLimit; IsFuzzingMode = isFuzzingMode; IsAutoFusing = isAutoFusing; MaxFixedBufferSize = maxFixedBufferSize; SyncProcessingLimit = syncProcessingLimit; } public ActorMaterializerSettings WithInputBuffer(int initialSize, int maxSize) { return new ActorMaterializerSettings(initialSize, maxSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit); } public ActorMaterializerSettings WithDispatcher(string dispatcher) { return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit); } public ActorMaterializerSettings WithSupervisionStrategy(Decider decider) { return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, decider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit); } public ActorMaterializerSettings WithDebugLogging(bool isEnabled) { return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, isEnabled, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit); } public ActorMaterializerSettings WithFuzzingMode(bool isFuzzingMode) { return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, isFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit); } public ActorMaterializerSettings WithAutoFusing(bool isAutoFusing) { return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, isAutoFusing, MaxFixedBufferSize, SyncProcessingLimit); } public ActorMaterializerSettings WithMaxFixedBufferSize(int maxFixedBufferSize) { return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, maxFixedBufferSize, SyncProcessingLimit); } public ActorMaterializerSettings WithSyncProcessingLimit(int limit) { return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, limit); } public ActorMaterializerSettings WithSubscriptionTimeoutSettings(StreamSubscriptionTimeoutSettings settings) { if (Equals(settings, SubscriptionTimeoutSettings)) return this; return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, settings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit); } } /// <summary> /// Leaked publishers and subscribers are cleaned up when they are not used within a given deadline, configured by <see cref="StreamSubscriptionTimeoutSettings"/>. /// </summary> public sealed class StreamSubscriptionTimeoutSettings : IEquatable<StreamSubscriptionTimeoutSettings> { public static StreamSubscriptionTimeoutSettings Create(Config config) { var c = config.GetConfig("subscription-timeout") ?? Config.Empty; var configMode = c.GetString("mode", "cancel").ToLowerInvariant(); StreamSubscriptionTimeoutTerminationMode mode; switch (configMode) { case "no": case "off": case "false": case "noop": mode = StreamSubscriptionTimeoutTerminationMode.NoopTermination; break; case "warn": mode = StreamSubscriptionTimeoutTerminationMode.WarnTermination; break; case "cancel": mode = StreamSubscriptionTimeoutTerminationMode.CancelTermination; break; default: throw new ArgumentException("akka.stream.materializer.subscribtion-timeout.mode was not defined or has invalid value. Valid values are: no, off, false, noop, warn, cancel"); } return new StreamSubscriptionTimeoutSettings( mode: mode, timeout: c.GetTimeSpan("timeout", TimeSpan.FromSeconds(5))); } public readonly StreamSubscriptionTimeoutTerminationMode Mode; public readonly TimeSpan Timeout; public StreamSubscriptionTimeoutSettings(StreamSubscriptionTimeoutTerminationMode mode, TimeSpan timeout) { Mode = mode; Timeout = timeout; } public override bool Equals(object obj) { if (ReferenceEquals(obj, null)) return false; if (ReferenceEquals(obj, this)) return true; if (obj is StreamSubscriptionTimeoutSettings) return Equals((StreamSubscriptionTimeoutSettings) obj); return false; } public bool Equals(StreamSubscriptionTimeoutSettings other) => Mode == other.Mode && Timeout.Equals(other.Timeout); public override int GetHashCode() { unchecked { return ((int)Mode * 397) ^ Timeout.GetHashCode(); } } public override string ToString() => $"StreamSubscriptionTimeoutSettings<{Mode}, {Timeout}>"; } /// <summary> /// This mode describes what shall happen when the subscription timeout expires /// for substream Publishers created by operations like <see cref="InternalFlowOperations.PrefixAndTail{T,TMat}"/>. /// </summary> public enum StreamSubscriptionTimeoutTerminationMode { /// <summary> /// Do not do anything when timeout expires. /// </summary> NoopTermination, /// <summary> /// Log a warning when the timeout expires. /// </summary> WarnTermination, /// <summary> /// When the timeout expires attach a Subscriber that will immediately cancel its subscription. /// </summary> CancelTermination } public static class ActorMaterializerExtensions { /// <summary> /// <para> /// Creates a ActorMaterializer which will execute every step of a transformation /// pipeline within its own <see cref="ActorBase"/>. The required <see cref="IActorRefFactory"/> /// (which can be either an <see cref="ActorSystem"/> or an <see cref="IActorContext"/>) /// will be used to create one actor that in turn creates actors for the transformation steps. /// </para> /// <para> /// The materializer's <see cref="ActorMaterializerSettings"/> will be obtained from the /// configuration of the <paramref name="context"/>'s underlying <see cref="ActorSystem"/>. /// </para> /// <para> /// The <paramref name="namePrefix"/> is used as the first part of the names of the actors running /// the processing steps. The default <paramref name="namePrefix"/> is "flow". The actor names are built up of /// namePrefix-flowNumber-flowStepNumber-stepName. /// </para> /// </summary> public static ActorMaterializer Materializer(this IActorRefFactory context, ActorMaterializerSettings settings = null, string namePrefix = null) => ActorMaterializer.Create(context, settings, namePrefix); } }
// 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 OLEDB.Test.ModuleCore; namespace System.Xml.Tests { public partial class TCInvalidXML : TCXMLReaderBaseGeneral { // Type is System.Xml.Tests.TCInvalidXML // Test Case public override void AddChildren() { // for function Read36a { this.AddChild(new CVariation(Read36a) { Attribute = new Variation("Read with surrogate in attr.val.begin") }); } // for function Read36b { this.AddChild(new CVariation(Read36b) { Attribute = new Variation("Read with surrogate in attr.val.mid") }); } // for function Read36c { this.AddChild(new CVariation(Read36c) { Attribute = new Variation("Read with surrogate in attr.val.end") }); } // for function Read37 { this.AddChild(new CVariation(Read37) { Attribute = new Variation("Read with surrogate in a DTD") }); } // for function Read37a { this.AddChild(new CVariation(Read37a) { Attribute = new Variation("Read with surrogate in a DTD.begin") }); } // for function Read37b { this.AddChild(new CVariation(Read37b) { Attribute = new Variation("Read with surrogate in a DTD.mid") }); } // for function Read37c { this.AddChild(new CVariation(Read37c) { Attribute = new Variation("Read with surrogate in a DTD.end") }); } // for function InvalidCommentCharacters { this.AddChild(new CVariation(InvalidCommentCharacters) { Attribute = new Variation("For non-well-formed XMLs, check for the line info in the error message") }); } // for function FactoryReaderInvalidCharacter { this.AddChild(new CVariation(FactoryReaderInvalidCharacter) { Attribute = new Variation("The XmlReader is reporting errors with -ve column values") }); } // for function Read1 { this.AddChild(new CVariation(Read1) { Attribute = new Variation("Read with invalid content") }); } // for function Read2 { this.AddChild(new CVariation(Read2) { Attribute = new Variation("Read with invalid end tag") }); } // for function Read3 { this.AddChild(new CVariation(Read3) { Attribute = new Variation("Read with invalid name") }); } // for function Read4 { this.AddChild(new CVariation(Read4) { Attribute = new Variation("Read with invalid characters") }); } // for function Read6 { this.AddChild(new CVariation(Read6) { Attribute = new Variation("Read with missing root end element") }); } // for function Read11 { this.AddChild(new CVariation(Read11) { Attribute = new Variation("Read with invalid namespace") }); } // for function Read12 { this.AddChild(new CVariation(Read12) { Attribute = new Variation("Attribute containing invalid character &") }); } // for function Read13 { this.AddChild(new CVariation(Read13) { Attribute = new Variation("Incomplete DOCTYPE") }); } // for function Read14 { this.AddChild(new CVariation(Read14) { Attribute = new Variation("Undefined namespace") }); } // for function Read15 { this.AddChild(new CVariation(Read15) { Attribute = new Variation("Read an XML Fragment which has unclosed elements") }); } // for function Read21 { this.AddChild(new CVariation(Read21) { Attribute = new Variation("Read invalid PIs") }); } // for function Read22 { this.AddChild(new CVariation(Read22) { Attribute = new Variation("Tag name > 4K, invalid") }); } // for function Read22a { this.AddChild(new CVariation(Read22a) { Attribute = new Variation("Surrogate char in name > 4K, invalid") }); } // for function Read23 { this.AddChild(new CVariation(Read23) { Attribute = new Variation("Line number/position of whitespace before external entity (regression)") }); } // for function Read24a { this.AddChild(new CVariation(Read24a) { Attribute = new Variation("1.Valid XML declaration.Errata5") { Param = "1.0" } }); } // for function Read25b { this.AddChild(new CVariation(Read25b) { Attribute = new Variation("4.Invalid XML declaration.version") { Param = "0.9" } }); this.AddChild(new CVariation(Read25b) { Attribute = new Variation("3.Invalid XML declaration.version") { Param = "0.1" } }); this.AddChild(new CVariation(Read25b) { Attribute = new Variation("1.Invalid XML declaration.version") { Param = "2.0" } }); this.AddChild(new CVariation(Read25b) { Attribute = new Variation("5.Invalid XML declaration.version") { Param = "1" } }); this.AddChild(new CVariation(Read25b) { Attribute = new Variation("6.Invalid XML declaration.version") { Param = "1.a" } }); this.AddChild(new CVariation(Read25b) { Attribute = new Variation("7.Invalid XML declaration.version") { Param = "#45" } }); this.AddChild(new CVariation(Read25b) { Attribute = new Variation("8.Invalid XML declaration.version") { Param = "\\uD812" } }); this.AddChild(new CVariation(Read25b) { Attribute = new Variation("2.Invalid XML declaration.version") { Param = "1.1." } }); } // for function Read26b { this.AddChild(new CVariation(Read26b) { Attribute = new Variation("6.Invalid XML declaration.standalone") { Param = "0" } }); this.AddChild(new CVariation(Read26b) { Attribute = new Variation("2.Invalid XML declaration.standalone") { Param = "false" } }); this.AddChild(new CVariation(Read26b) { Attribute = new Variation("4.Invalid XML declaration.standalone") { Param = "No" } }); this.AddChild(new CVariation(Read26b) { Attribute = new Variation("5.Invalid XML declaration.standalone") { Param = "1" } }); this.AddChild(new CVariation(Read26b) { Attribute = new Variation("3.Invalid XML declaration.standalone") { Param = "Yes" } }); this.AddChild(new CVariation(Read26b) { Attribute = new Variation("7.Invalid XML declaration.standalone") { Param = "#45" } }); this.AddChild(new CVariation(Read26b) { Attribute = new Variation("8.Invalid XML declaration.standalone") { Param = "\\uD812" } }); this.AddChild(new CVariation(Read26b) { Attribute = new Variation("1.Invalid XML declaration.standalone") { Param = "true" } }); } // for function Read28 { this.AddChild(new CVariation(Read28) { Attribute = new Variation("Read with invalid surrogate inside comment") }); } // for function Read29a { this.AddChild(new CVariation(Read29a) { Attribute = new Variation("Read with invalid surrogate inside comment.begin") }); } // for function Read29b { this.AddChild(new CVariation(Read29b) { Attribute = new Variation("Read with invalid surrogate inside comment.mid") }); } // for function Read29c { this.AddChild(new CVariation(Read29c) { Attribute = new Variation("Read with invalid surrogate inside comment.end") }); } // for function Read30 { this.AddChild(new CVariation(Read30) { Attribute = new Variation("Read with invalid surrogate inside PI") }); } // for function Read30a { this.AddChild(new CVariation(Read30a) { Attribute = new Variation("Read with invalid surrogate inside PI.begin") }); } // for function Read30b { this.AddChild(new CVariation(Read30b) { Attribute = new Variation("Read with invalid surrogate inside PI.mid") }); } // for function Read30c { this.AddChild(new CVariation(Read30c) { Attribute = new Variation("Read with invalid surrogate inside PI.end") }); } // for function Read31 { this.AddChild(new CVariation(Read31) { Attribute = new Variation("Read an invalid character which is a lower part of the surrogate pair") }); } // for function Read31a { this.AddChild(new CVariation(Read31a) { Attribute = new Variation("Read an invalid character which is a lower part of the surrogate pair.begin") }); } // for function Read31b { this.AddChild(new CVariation(Read31b) { Attribute = new Variation("Read an invalid character which is a lower part of the surrogate pair.mid") }); } // for function Read31c { this.AddChild(new CVariation(Read31c) { Attribute = new Variation("Read an invalid character which is a lower part of the surrogate pair.end") }); } // for function Read32 { this.AddChild(new CVariation(Read32) { Attribute = new Variation("Read with surrogate in a name") }); } // for function Read32a { this.AddChild(new CVariation(Read32a) { Attribute = new Variation("Read with surrogate in a name.begin") }); } // for function Read32b { this.AddChild(new CVariation(Read32b) { Attribute = new Variation("Read with surrogate in a name.mid") }); } // for function Read32c { this.AddChild(new CVariation(Read32c) { Attribute = new Variation("Read with surrogate in a name.end") }); } // for function Read33 { this.AddChild(new CVariation(Read33) { Attribute = new Variation("Read with invalid surrogate inside text") }); } // for function Read33a { this.AddChild(new CVariation(Read33a) { Attribute = new Variation("Read with invalid surrogate inside text.begin") }); } // for function Read33b { this.AddChild(new CVariation(Read33b) { Attribute = new Variation("Read with invalid surrogate inside text.mid") }); } // for function Read33c { this.AddChild(new CVariation(Read33c) { Attribute = new Variation("Read with invalid surrogate inside text.end") }); } // for function Read34 { this.AddChild(new CVariation(Read34) { Attribute = new Variation("Read with invalid surrogate inside CDATA") }); } // for function Read34a { this.AddChild(new CVariation(Read34a) { Attribute = new Variation("Read with invalid surrogate inside CDATA.begin") }); } // for function Read34b { this.AddChild(new CVariation(Read34b) { Attribute = new Variation("Read with invalid surrogate inside CDATA.mid") }); } // for function Read34c { this.AddChild(new CVariation(Read34c) { Attribute = new Variation("Read with invalid surrogate inside CDATA.end") }); } // for function Read35 { this.AddChild(new CVariation(Read35) { Attribute = new Variation("Read with surrogate in attr.name") }); } // for function Read35a { this.AddChild(new CVariation(Read35a) { Attribute = new Variation("Read with surrogate in attr.name.begin") }); } // for function Read35b { this.AddChild(new CVariation(Read35b) { Attribute = new Variation("Read with surrogate in attr.name.mid") }); } // for function Read35c { this.AddChild(new CVariation(Read35c) { Attribute = new Variation("Read with surrogate in attr.name.end") }); } // for function Read36 { this.AddChild(new CVariation(Read36) { Attribute = new Variation("Read with surrogate in attr.val") }); } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the AprZScorePesoLongitud class. /// </summary> [Serializable] public partial class AprZScorePesoLongitudCollection : ActiveList<AprZScorePesoLongitud, AprZScorePesoLongitudCollection> { public AprZScorePesoLongitudCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprZScorePesoLongitudCollection</returns> public AprZScorePesoLongitudCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprZScorePesoLongitud o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the APR_ZScorePesoLongitud table. /// </summary> [Serializable] public partial class AprZScorePesoLongitud : ActiveRecord<AprZScorePesoLongitud>, IActiveRecord { #region .ctors and Default Settings public AprZScorePesoLongitud() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprZScorePesoLongitud(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprZScorePesoLongitud(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprZScorePesoLongitud(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("APR_ZScorePesoLongitud", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "id"; colvarId.DataType = DbType.Int32; colvarId.MaxLength = 0; colvarId.AutoIncrement = true; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @""; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema); colvarSexo.ColumnName = "Sexo"; colvarSexo.DataType = DbType.Int32; colvarSexo.MaxLength = 0; colvarSexo.AutoIncrement = false; colvarSexo.IsNullable = true; colvarSexo.IsPrimaryKey = false; colvarSexo.IsForeignKey = false; colvarSexo.IsReadOnly = false; colvarSexo.DefaultSetting = @""; colvarSexo.ForeignKeyTableName = ""; schema.Columns.Add(colvarSexo); TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema); colvarEdad.ColumnName = "Edad"; colvarEdad.DataType = DbType.Int32; colvarEdad.MaxLength = 0; colvarEdad.AutoIncrement = false; colvarEdad.IsNullable = true; colvarEdad.IsPrimaryKey = false; colvarEdad.IsForeignKey = false; colvarEdad.IsReadOnly = false; colvarEdad.DefaultSetting = @""; colvarEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarEdad); TableSchema.TableColumn colvarSD4neg = new TableSchema.TableColumn(schema); colvarSD4neg.ColumnName = "SD4neg"; colvarSD4neg.DataType = DbType.Decimal; colvarSD4neg.MaxLength = 0; colvarSD4neg.AutoIncrement = false; colvarSD4neg.IsNullable = true; colvarSD4neg.IsPrimaryKey = false; colvarSD4neg.IsForeignKey = false; colvarSD4neg.IsReadOnly = false; colvarSD4neg.DefaultSetting = @""; colvarSD4neg.ForeignKeyTableName = ""; schema.Columns.Add(colvarSD4neg); TableSchema.TableColumn colvarSD3neg = new TableSchema.TableColumn(schema); colvarSD3neg.ColumnName = "SD3neg"; colvarSD3neg.DataType = DbType.Decimal; colvarSD3neg.MaxLength = 0; colvarSD3neg.AutoIncrement = false; colvarSD3neg.IsNullable = true; colvarSD3neg.IsPrimaryKey = false; colvarSD3neg.IsForeignKey = false; colvarSD3neg.IsReadOnly = false; colvarSD3neg.DefaultSetting = @""; colvarSD3neg.ForeignKeyTableName = ""; schema.Columns.Add(colvarSD3neg); TableSchema.TableColumn colvarSD2neg = new TableSchema.TableColumn(schema); colvarSD2neg.ColumnName = "SD2neg"; colvarSD2neg.DataType = DbType.Decimal; colvarSD2neg.MaxLength = 0; colvarSD2neg.AutoIncrement = false; colvarSD2neg.IsNullable = true; colvarSD2neg.IsPrimaryKey = false; colvarSD2neg.IsForeignKey = false; colvarSD2neg.IsReadOnly = false; colvarSD2neg.DefaultSetting = @""; colvarSD2neg.ForeignKeyTableName = ""; schema.Columns.Add(colvarSD2neg); TableSchema.TableColumn colvarSD1neg = new TableSchema.TableColumn(schema); colvarSD1neg.ColumnName = "SD1neg"; colvarSD1neg.DataType = DbType.Decimal; colvarSD1neg.MaxLength = 0; colvarSD1neg.AutoIncrement = false; colvarSD1neg.IsNullable = true; colvarSD1neg.IsPrimaryKey = false; colvarSD1neg.IsForeignKey = false; colvarSD1neg.IsReadOnly = false; colvarSD1neg.DefaultSetting = @""; colvarSD1neg.ForeignKeyTableName = ""; schema.Columns.Add(colvarSD1neg); TableSchema.TableColumn colvarSD0 = new TableSchema.TableColumn(schema); colvarSD0.ColumnName = "SD0"; colvarSD0.DataType = DbType.Decimal; colvarSD0.MaxLength = 0; colvarSD0.AutoIncrement = false; colvarSD0.IsNullable = true; colvarSD0.IsPrimaryKey = false; colvarSD0.IsForeignKey = false; colvarSD0.IsReadOnly = false; colvarSD0.DefaultSetting = @""; colvarSD0.ForeignKeyTableName = ""; schema.Columns.Add(colvarSD0); TableSchema.TableColumn colvarSD1 = new TableSchema.TableColumn(schema); colvarSD1.ColumnName = "SD1"; colvarSD1.DataType = DbType.Decimal; colvarSD1.MaxLength = 0; colvarSD1.AutoIncrement = false; colvarSD1.IsNullable = true; colvarSD1.IsPrimaryKey = false; colvarSD1.IsForeignKey = false; colvarSD1.IsReadOnly = false; colvarSD1.DefaultSetting = @""; colvarSD1.ForeignKeyTableName = ""; schema.Columns.Add(colvarSD1); TableSchema.TableColumn colvarSD2 = new TableSchema.TableColumn(schema); colvarSD2.ColumnName = "SD2"; colvarSD2.DataType = DbType.Decimal; colvarSD2.MaxLength = 0; colvarSD2.AutoIncrement = false; colvarSD2.IsNullable = true; colvarSD2.IsPrimaryKey = false; colvarSD2.IsForeignKey = false; colvarSD2.IsReadOnly = false; colvarSD2.DefaultSetting = @""; colvarSD2.ForeignKeyTableName = ""; schema.Columns.Add(colvarSD2); TableSchema.TableColumn colvarSD3 = new TableSchema.TableColumn(schema); colvarSD3.ColumnName = "SD3"; colvarSD3.DataType = DbType.Decimal; colvarSD3.MaxLength = 0; colvarSD3.AutoIncrement = false; colvarSD3.IsNullable = true; colvarSD3.IsPrimaryKey = false; colvarSD3.IsForeignKey = false; colvarSD3.IsReadOnly = false; colvarSD3.DefaultSetting = @""; colvarSD3.ForeignKeyTableName = ""; schema.Columns.Add(colvarSD3); TableSchema.TableColumn colvarSD4 = new TableSchema.TableColumn(schema); colvarSD4.ColumnName = "SD4"; colvarSD4.DataType = DbType.Decimal; colvarSD4.MaxLength = 0; colvarSD4.AutoIncrement = false; colvarSD4.IsNullable = true; colvarSD4.IsPrimaryKey = false; colvarSD4.IsForeignKey = false; colvarSD4.IsReadOnly = false; colvarSD4.DefaultSetting = @""; colvarSD4.ForeignKeyTableName = ""; schema.Columns.Add(colvarSD4); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_ZScorePesoLongitud",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public int Id { get { return GetColumnValue<int>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("Sexo")] [Bindable(true)] public int? Sexo { get { return GetColumnValue<int?>(Columns.Sexo); } set { SetColumnValue(Columns.Sexo, value); } } [XmlAttribute("Edad")] [Bindable(true)] public int? Edad { get { return GetColumnValue<int?>(Columns.Edad); } set { SetColumnValue(Columns.Edad, value); } } [XmlAttribute("SD4neg")] [Bindable(true)] public decimal? SD4neg { get { return GetColumnValue<decimal?>(Columns.SD4neg); } set { SetColumnValue(Columns.SD4neg, value); } } [XmlAttribute("SD3neg")] [Bindable(true)] public decimal? SD3neg { get { return GetColumnValue<decimal?>(Columns.SD3neg); } set { SetColumnValue(Columns.SD3neg, value); } } [XmlAttribute("SD2neg")] [Bindable(true)] public decimal? SD2neg { get { return GetColumnValue<decimal?>(Columns.SD2neg); } set { SetColumnValue(Columns.SD2neg, value); } } [XmlAttribute("SD1neg")] [Bindable(true)] public decimal? SD1neg { get { return GetColumnValue<decimal?>(Columns.SD1neg); } set { SetColumnValue(Columns.SD1neg, value); } } [XmlAttribute("SD0")] [Bindable(true)] public decimal? SD0 { get { return GetColumnValue<decimal?>(Columns.SD0); } set { SetColumnValue(Columns.SD0, value); } } [XmlAttribute("SD1")] [Bindable(true)] public decimal? SD1 { get { return GetColumnValue<decimal?>(Columns.SD1); } set { SetColumnValue(Columns.SD1, value); } } [XmlAttribute("SD2")] [Bindable(true)] public decimal? SD2 { get { return GetColumnValue<decimal?>(Columns.SD2); } set { SetColumnValue(Columns.SD2, value); } } [XmlAttribute("SD3")] [Bindable(true)] public decimal? SD3 { get { return GetColumnValue<decimal?>(Columns.SD3); } set { SetColumnValue(Columns.SD3, value); } } [XmlAttribute("SD4")] [Bindable(true)] public decimal? SD4 { get { return GetColumnValue<decimal?>(Columns.SD4); } set { SetColumnValue(Columns.SD4, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int? varSexo,int? varEdad,decimal? varSD4neg,decimal? varSD3neg,decimal? varSD2neg,decimal? varSD1neg,decimal? varSD0,decimal? varSD1,decimal? varSD2,decimal? varSD3,decimal? varSD4) { AprZScorePesoLongitud item = new AprZScorePesoLongitud(); item.Sexo = varSexo; item.Edad = varEdad; item.SD4neg = varSD4neg; item.SD3neg = varSD3neg; item.SD2neg = varSD2neg; item.SD1neg = varSD1neg; item.SD0 = varSD0; item.SD1 = varSD1; item.SD2 = varSD2; item.SD3 = varSD3; item.SD4 = varSD4; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varId,int? varSexo,int? varEdad,decimal? varSD4neg,decimal? varSD3neg,decimal? varSD2neg,decimal? varSD1neg,decimal? varSD0,decimal? varSD1,decimal? varSD2,decimal? varSD3,decimal? varSD4) { AprZScorePesoLongitud item = new AprZScorePesoLongitud(); item.Id = varId; item.Sexo = varSexo; item.Edad = varEdad; item.SD4neg = varSD4neg; item.SD3neg = varSD3neg; item.SD2neg = varSD2neg; item.SD1neg = varSD1neg; item.SD0 = varSD0; item.SD1 = varSD1; item.SD2 = varSD2; item.SD3 = varSD3; item.SD4 = varSD4; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn SexoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn EdadColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn SD4negColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn SD3negColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn SD2negColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn SD1negColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn SD0Column { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn SD1Column { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn SD2Column { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn SD3Column { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn SD4Column { get { return Schema.Columns[11]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"id"; public static string Sexo = @"Sexo"; public static string Edad = @"Edad"; public static string SD4neg = @"SD4neg"; public static string SD3neg = @"SD3neg"; public static string SD2neg = @"SD2neg"; public static string SD1neg = @"SD1neg"; public static string SD0 = @"SD0"; public static string SD1 = @"SD1"; public static string SD2 = @"SD2"; public static string SD3 = @"SD3"; public static string SD4 = @"SD4"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using NUnit.Framework; using Whois.Parsers; namespace Whois.Parsing.Whois.Nic.Asia.Asia { [TestFixture] public class AsiaParsingTests : ParsingTests { private WhoisParser parser; [SetUp] public void SetUp() { SerilogConfig.Init(); parser = new WhoisParser(); } [Test] public void Test_found() { var sample = SampleReader.Read("whois.nic.asia", "asia", "found.txt"); var response = parser.Parse("whois.nic.asia", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.asia/asia/Found", response.TemplateName); Assert.AreEqual("novalash.asia", response.DomainName.ToString()); Assert.AreEqual("D1032500-ASIA", response.RegistryDomainId); // Registrar Details Assert.AreEqual("007Names, Inc. R94-ASIA (91)", response.Registrar.Name); Assert.AreEqual(new DateTime(2010, 10, 01, 03, 30, 34, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2008, 10, 30, 22, 54, 15, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2012, 10, 30, 22, 54, 15, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("7AERFN4T4P", response.Registrant.RegistryId); Assert.AreEqual("Sophy Merszei", response.Registrant.Name); Assert.AreEqual("Novalash", response.Registrant.Organization); Assert.AreEqual("+1.8664301261", response.Registrant.TelephoneNumber); Assert.AreEqual("khickman@awsp.com", response.Registrant.Email); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("3701 W. Alabama", response.Registrant.Address[0]); Assert.AreEqual("Houston", response.Registrant.Address[1]); Assert.AreEqual("TX", response.Registrant.Address[2]); Assert.AreEqual("US", response.Registrant.Address[3]); Assert.AreEqual("77027", response.Registrant.Address[4]); // AdminContact Details Assert.AreEqual("5MTMZMT3K1", response.AdminContact.RegistryId); Assert.AreEqual(":Sophy Merszei", response.AdminContact.Name); Assert.AreEqual("Novalash", response.AdminContact.Organization); Assert.AreEqual("+1.8664301261", response.AdminContact.TelephoneNumber); Assert.AreEqual("khickman@awsp.com", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("3701 W. Alabama", response.AdminContact.Address[0]); Assert.AreEqual("Houston", response.AdminContact.Address[1]); Assert.AreEqual("US", response.AdminContact.Address[2]); Assert.AreEqual("77027", response.AdminContact.Address[3]); // BillingContact Details Assert.AreEqual("5MTMZMT3K1", response.BillingContact.RegistryId); Assert.AreEqual("Sophy Merszei", response.BillingContact.Name); Assert.AreEqual("Novalash", response.BillingContact.Organization); Assert.AreEqual("+1.8664301261", response.BillingContact.TelephoneNumber); Assert.AreEqual("khickman@awsp.com", response.BillingContact.Email); // BillingContact Address Assert.AreEqual(5, response.BillingContact.Address.Count); Assert.AreEqual("3701 W. Alabama", response.BillingContact.Address[0]); Assert.AreEqual("Houston", response.BillingContact.Address[1]); Assert.AreEqual("TX", response.BillingContact.Address[2]); Assert.AreEqual("US", response.BillingContact.Address[3]); Assert.AreEqual("77027", response.BillingContact.Address[4]); // TechnicalContact Details Assert.AreEqual("FR-11594d9eed91", response.TechnicalContact.RegistryId); Assert.AreEqual("Edward Lin", response.TechnicalContact.Name); Assert.AreEqual("EDM Enterprise Co., LTD", response.TechnicalContact.Organization); Assert.AreEqual("+886.425625115", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("doamina@yahoo.com", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("No. 10 Lane 241, Chung Shan Road", response.TechnicalContact.Address[0]); Assert.AreEqual("Shen Kang Hsiang", response.TechnicalContact.Address[1]); Assert.AreEqual("Taichung Hsien", response.TechnicalContact.Address[2]); Assert.AreEqual("TW", response.TechnicalContact.Address[3]); Assert.AreEqual("35000", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns2.rackspace.com", response.NameServers[0]); Assert.AreEqual("ns.raskspace.com", response.NameServers[1]); // Domain Status Assert.AreEqual(2, response.DomainStatus.Count); Assert.AreEqual("CLIENT DELETE PROHIBITED", response.DomainStatus[0]); Assert.AreEqual("CLIENT TRANSFER PROHIBITED", response.DomainStatus[1]); Assert.AreEqual(50, response.FieldsParsed); } [Test] public void Test_other_status_single() { var sample = SampleReader.Read("whois.nic.asia", "asia", "other_status_single.txt"); var response = parser.Parse("whois.nic.asia", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.asia/asia/Found", response.TemplateName); Assert.AreEqual("cj7.asia", response.DomainName.ToString()); Assert.AreEqual("D93126-ASIA", response.RegistryDomainId); // Registrar Details Assert.AreEqual("dotASIA R4-ASIA (9998)", response.Registrar.Name); Assert.AreEqual(new DateTime(2008, 03, 16, 04, 30, 25, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2008, 01, 15, 11, 28, 02, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2010, 01, 15, 11, 28, 02, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("FR-1158300cc88a", response.Registrant.RegistryId); Assert.AreEqual("Pioneer Domain (Temporary Delegation)", response.Registrant.Name); Assert.AreEqual("DotAsia Organisation", response.Registrant.Organization); Assert.AreEqual("+852.35202635", response.Registrant.TelephoneNumber); Assert.AreEqual("domains@registry.asia", response.Registrant.Email); // Registrant Address Assert.AreEqual(6, response.Registrant.Address.Count); Assert.AreEqual("Unit 617, Miramar Tower", response.Registrant.Address[0]); Assert.AreEqual("132 Nathan Road", response.Registrant.Address[1]); Assert.AreEqual("Tsim Sha Tsui", response.Registrant.Address[2]); Assert.AreEqual("Kowloon", response.Registrant.Address[3]); Assert.AreEqual("HK", response.Registrant.Address[4]); Assert.AreEqual("HK", response.Registrant.Address[5]); // AdminContact Details Assert.AreEqual("FR-11582fd1b4a9", response.AdminContact.RegistryId); Assert.AreEqual(":DotAsia Organisation", response.AdminContact.Name); Assert.AreEqual("DotAsia Organisation", response.AdminContact.Organization); Assert.AreEqual("+852.35202635", response.AdminContact.TelephoneNumber); Assert.AreEqual("domains@registry.asia", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(5, response.AdminContact.Address.Count); Assert.AreEqual("Unit 617, Miramar Tower", response.AdminContact.Address[0]); Assert.AreEqual("132 Nathan Road", response.AdminContact.Address[1]); Assert.AreEqual("Tsim Sha Tsui", response.AdminContact.Address[2]); Assert.AreEqual("HK", response.AdminContact.Address[3]); Assert.AreEqual("HK", response.AdminContact.Address[4]); // BillingContact Details Assert.AreEqual("FR-11582fd1b4a9", response.BillingContact.RegistryId); Assert.AreEqual("DotAsia Organisation", response.BillingContact.Name); Assert.AreEqual("DotAsia Organisation", response.BillingContact.Organization); Assert.AreEqual("+852.35202635", response.BillingContact.TelephoneNumber); Assert.AreEqual("domains@registry.asia", response.BillingContact.Email); // BillingContact Address Assert.AreEqual(6, response.BillingContact.Address.Count); Assert.AreEqual("Unit 617, Miramar Tower", response.BillingContact.Address[0]); Assert.AreEqual("132 Nathan Road", response.BillingContact.Address[1]); Assert.AreEqual("Tsim Sha Tsui", response.BillingContact.Address[2]); Assert.AreEqual("Kowloon", response.BillingContact.Address[3]); Assert.AreEqual("HK", response.BillingContact.Address[4]); Assert.AreEqual("HK", response.BillingContact.Address[5]); // TechnicalContact Details Assert.AreEqual("FR-11582fd1b4a9", response.TechnicalContact.RegistryId); Assert.AreEqual("DotAsia Organisation", response.TechnicalContact.Name); Assert.AreEqual("DotAsia Organisation", response.TechnicalContact.Organization); Assert.AreEqual("+852.35202635", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("domains@registry.asia", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(6, response.TechnicalContact.Address.Count); Assert.AreEqual("Unit 617, Miramar Tower", response.TechnicalContact.Address[0]); Assert.AreEqual("132 Nathan Road", response.TechnicalContact.Address[1]); Assert.AreEqual("Tsim Sha Tsui", response.TechnicalContact.Address[2]); Assert.AreEqual("Kowloon", response.TechnicalContact.Address[3]); Assert.AreEqual("HK", response.TechnicalContact.Address[4]); Assert.AreEqual("HK", response.TechnicalContact.Address[5]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns1.dotasia.org", response.NameServers[0]); Assert.AreEqual("ns2.dotasia.org", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("OK", response.DomainStatus[0]); Assert.AreEqual(53, response.FieldsParsed); } [Test] public void Test_not_found() { var sample = SampleReader.Read("whois.nic.asia", "asia", "not_found.txt"); var response = parser.Parse("whois.nic.asia", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.NotFound, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("generic/tld/NotFound001", response.TemplateName); Assert.AreEqual(1, response.FieldsParsed); } [Test] public void Test_found_status_registered() { var sample = SampleReader.Read("whois.nic.asia", "asia", "found_status_registered.txt"); var response = parser.Parse("whois.nic.asia", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.asia/asia/Found", response.TemplateName); Assert.AreEqual("cj7.asia", response.DomainName.ToString()); Assert.AreEqual("D93126-ASIA", response.RegistryDomainId); // Registrar Details Assert.AreEqual("dotASIA R4-ASIA (800046)", response.Registrar.Name); Assert.AreEqual(new DateTime(2014, 01, 15, 22, 20, 16, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2008, 01, 15, 11, 28, 02, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2015, 01, 15, 11, 28, 02, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("FR-132aa75b4bf65", response.Registrant.RegistryId); Assert.AreEqual("RAXCO ASSETS CORP.", response.Registrant.Name); Assert.AreEqual("RAXCO ASSETS CORP.", response.Registrant.Organization); Assert.AreEqual("+852.21190333", response.Registrant.TelephoneNumber); Assert.AreEqual("+852.23045326", response.Registrant.FaxNumber); Assert.AreEqual("eddie.yeung@bingogroup.com.hk", response.Registrant.Email); // Registrant Address Assert.AreEqual(5, response.Registrant.Address.Count); Assert.AreEqual("RM 1201-1204 12/F", response.Registrant.Address[0]); Assert.AreEqual("SEA BIRD HSE", response.Registrant.Address[1]); Assert.AreEqual("22-28 WYNDHAM ST CENTRAL HK", response.Registrant.Address[2]); Assert.AreEqual("Hong Kong", response.Registrant.Address[3]); Assert.AreEqual("HK", response.Registrant.Address[4]); // AdminContact Details Assert.AreEqual("FR-132aa7afe0967", response.AdminContact.RegistryId); Assert.AreEqual(":Eddie Yeung", response.AdminContact.Name); Assert.AreEqual("RAXCO ASSETS CORP.", response.AdminContact.Organization); Assert.AreEqual("+852.21190333", response.AdminContact.TelephoneNumber); Assert.AreEqual("eddie.yeung@bingogroup.com.hk", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(5, response.AdminContact.Address.Count); Assert.AreEqual("RM 1201-1204 12/F", response.AdminContact.Address[0]); Assert.AreEqual("SEA BIRD HSE", response.AdminContact.Address[1]); Assert.AreEqual("22-28 WYNDHAM ST CENTRAL HK", response.AdminContact.Address[2]); Assert.AreEqual("Hong Kong", response.AdminContact.Address[3]); Assert.AreEqual("HK", response.AdminContact.Address[4]); // BillingContact Details Assert.AreEqual("FR-132aa774c1b66", response.BillingContact.RegistryId); Assert.AreEqual("Frankie Chan", response.BillingContact.Name); Assert.AreEqual("RAXCO ASSETS CORP.", response.BillingContact.Organization); Assert.AreEqual("+852.21190333", response.BillingContact.TelephoneNumber); Assert.AreEqual("eddie.yeung@bingogroup.com.hk", response.BillingContact.Email); // BillingContact Address Assert.AreEqual(5, response.BillingContact.Address.Count); Assert.AreEqual("RM 1201-1204 12/F", response.BillingContact.Address[0]); Assert.AreEqual("SEA BIRD HSE", response.BillingContact.Address[1]); Assert.AreEqual("22-28 WYNDHAM ST CENTRAL HK", response.BillingContact.Address[2]); Assert.AreEqual("Hong Kong", response.BillingContact.Address[3]); Assert.AreEqual("HK", response.BillingContact.Address[4]); // TechnicalContact Details Assert.AreEqual("FR-132aa7afe0967", response.TechnicalContact.RegistryId); Assert.AreEqual("Eddie Yeung", response.TechnicalContact.Name); Assert.AreEqual("RAXCO ASSETS CORP.", response.TechnicalContact.Organization); Assert.AreEqual("+852.21190333", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("eddie.yeung@bingogroup.com.hk", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(5, response.TechnicalContact.Address.Count); Assert.AreEqual("RM 1201-1204 12/F", response.TechnicalContact.Address[0]); Assert.AreEqual("SEA BIRD HSE", response.TechnicalContact.Address[1]); Assert.AreEqual("22-28 WYNDHAM ST CENTRAL HK", response.TechnicalContact.Address[2]); Assert.AreEqual("Hong Kong", response.TechnicalContact.Address[3]); Assert.AreEqual("HK", response.TechnicalContact.Address[4]); // Nameservers Assert.AreEqual(6, response.NameServers.Count); Assert.AreEqual("ns1.dnspod.net", response.NameServers[0]); Assert.AreEqual("ns2.dnspod.net", response.NameServers[1]); Assert.AreEqual("ns3.dnspod.net", response.NameServers[2]); Assert.AreEqual("ns4.dnspod.net", response.NameServers[3]); Assert.AreEqual("ns5.dnspod.net", response.NameServers[4]); Assert.AreEqual("ns6.dnspod.net", response.NameServers[5]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("OK", response.DomainStatus[0]); Assert.AreEqual(55, response.FieldsParsed); } [Test] public void Test_reserved() { var sample = SampleReader.Read("whois.nic.asia", "asia", "reserved.txt"); var response = parser.Parse("whois.nic.asia", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Reserved, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.nic.asia/asia/Reserved", response.TemplateName); Assert.AreEqual(1, response.FieldsParsed); } } }
using System; namespace Tamir.SharpSsh.jsch { /* -*-mode:java; c-basic-offset:2; -*- */ /* Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ public class DHG1 : KeyExchange { internal static byte[] g = new byte[] {2}; internal static byte[] p = new byte[] { (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xC9, (byte) 0x0F, (byte) 0xDA, (byte) 0xA2, (byte) 0x21, (byte) 0x68, (byte) 0xC2, (byte) 0x34, (byte) 0xC4, (byte) 0xC6, (byte) 0x62, (byte) 0x8B, (byte) 0x80, (byte) 0xDC, (byte) 0x1C, (byte) 0xD1, (byte) 0x29, (byte) 0x02, (byte) 0x4E, (byte) 0x08, (byte) 0x8A, (byte) 0x67, (byte) 0xCC, (byte) 0x74, (byte) 0x02, (byte) 0x0B, (byte) 0xBE, (byte) 0xA6, (byte) 0x3B, (byte) 0x13, (byte) 0x9B, (byte) 0x22, (byte) 0x51, (byte) 0x4A, (byte) 0x08, (byte) 0x79, (byte) 0x8E, (byte) 0x34, (byte) 0x04, (byte) 0xDD, (byte) 0xEF, (byte) 0x95, (byte) 0x19, (byte) 0xB3, (byte) 0xCD, (byte) 0x3A, (byte) 0x43, (byte) 0x1B, (byte) 0x30, (byte) 0x2B, (byte) 0x0A, (byte) 0x6D, (byte) 0xF2, (byte) 0x5F, (byte) 0x14, (byte) 0x37, (byte) 0x4F, (byte) 0xE1, (byte) 0x35, (byte) 0x6D, (byte) 0x6D, (byte) 0x51, (byte) 0xC2, (byte) 0x45, (byte) 0xE4, (byte) 0x85, (byte) 0xB5, (byte) 0x76, (byte) 0x62, (byte) 0x5E, (byte) 0x7E, (byte) 0xC6, (byte) 0xF4, (byte) 0x4C, (byte) 0x42, (byte) 0xE9, (byte) 0xA6, (byte) 0x37, (byte) 0xED, (byte) 0x6B, (byte) 0x0B, (byte) 0xFF, (byte) 0x5C, (byte) 0xB6, (byte) 0xF4, (byte) 0x06, (byte) 0xB7, (byte) 0xED, (byte) 0xEE, (byte) 0x38, (byte) 0x6B, (byte) 0xFB, (byte) 0x5A, (byte) 0x89, (byte) 0x9F, (byte) 0xA5, (byte) 0xAE, (byte) 0x9F, (byte) 0x24, (byte) 0x11, (byte) 0x7C, (byte) 0x4B, (byte) 0x1F, (byte) 0xE6, (byte) 0x49, (byte) 0x28, (byte) 0x66, (byte) 0x51, (byte) 0xEC, (byte) 0xE6, (byte) 0x53, (byte) 0x81, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }; internal const int SSH_MSG_KEXDH_INIT = 30; internal const int SSH_MSG_KEXDH_REPLY = 31; internal const int RSA = 0; internal const int DSS = 1; private int type = 0; private int state; internal DH dh; // HASH sha; // byte[] K; // byte[] H; internal byte[] V_S; internal byte[] V_C; internal byte[] I_S; internal byte[] I_C; // byte[] K_S; internal byte[] e; private Buffer buf; private Packet packet; public override void init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C) { this.session = session; this.V_S = V_S; this.V_C = V_C; this.I_S = I_S; this.I_C = I_C; // sha=new SHA1(); // sha.init(); try { Type t = Type.GetType(session.getConfig("sha-1")); sha = (HASH) (Activator.CreateInstance(t)); sha.init(); } catch (Exception ee) { Console.WriteLine(ee); } buf = new Buffer(); packet = new Packet(buf); try { Type t = Type.GetType(session.getConfig("dh")); dh = (DH) (Activator.CreateInstance(t)); dh.init(); } catch (Exception ee) { throw ee; } dh.setP(p); dh.setG(g); // The client responds with: // byte SSH_MSG_KEXDH_INIT(30) // mpint e <- g^x mod p // x is a random number (1 < x < (p-1)/2) e = dh.getE(); packet.reset(); buf.putByte((byte) SSH_MSG_KEXDH_INIT); buf.putMPInt(e); session.write(packet); state = SSH_MSG_KEXDH_REPLY; } public override bool next(Buffer _buf) { int i, j; bool result = false; switch (state) { case SSH_MSG_KEXDH_REPLY: // The server responds with: // byte SSH_MSG_KEXDH_REPLY(31) // string server public host key and certificates (K_S) // mpint f // string signature of H j = _buf.getInt(); j = _buf.getByte(); j = _buf.getByte(); if (j != 31) { Console.WriteLine("type: must be 31 " + j); result = false; break; } K_S = _buf.getString(); // K_S is server_key_blob, which includes .... // string ssh-dss // impint p of dsa // impint q of dsa // impint g of dsa // impint pub_key of dsa //System.out.print("K_S: "); //dump(K_S, 0, K_S.length); byte[] f = _buf.getMPInt(); byte[] sig_of_H = _buf.getString(); /* for(int ii=0; ii<sig_of_H.length;ii++){ System.out.print(Integer.toHexString(sig_of_H[ii]&0xff)); System.out.print(": "); } Console.WriteLine(""); */ dh.setF(f); K = dh.getK(); //The hash H is computed as the HASH hash of the concatenation of the //following: // string V_C, the client's version string (CR and NL excluded) // string V_S, the server's version string (CR and NL excluded) // string I_C, the payload of the client's SSH_MSG_KEXINIT // string I_S, the payload of the server's SSH_MSG_KEXINIT // string K_S, the host key // mpint e, exchange value sent by the client // mpint f, exchange value sent by the server // mpint K, the shared secret // This value is called the exchange hash, and it is used to authenti- // cate the key exchange. buf.reset(); buf.putString(V_C); buf.putString(V_S); buf.putString(I_C); buf.putString(I_S); buf.putString(K_S); buf.putMPInt(e); buf.putMPInt(f); buf.putMPInt(K); byte[] foo = new byte[buf.getLength()]; buf.getByte(foo); sha.update(foo, 0, foo.Length); H = sha.digest(); //System.out.print("H -> "); //dump(H, 0, H.length); i = 0; j = 0; j = (int) ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); String alg = Util.getString(K_S, i, j); i += j; result = false; if (alg.Equals("ssh-rsa")) { byte[] tmp; byte[] ee; byte[] n; type = RSA; j = (int) ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j; ee = tmp; j = (int) ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j; n = tmp; // SignatureRSA sig=new SignatureRSA(); // sig.init(); SignatureRSA sig = null; try { Type t = Type.GetType(session.getConfig("signature.rsa")); sig = (SignatureRSA) (Activator.CreateInstance(t)); sig.init(); } catch (Exception eee) { Console.WriteLine(eee); } sig.setPubKey(ee, n); sig.update(H); result = sig.verify(sig_of_H); //MainClass.dump(ee, n, sig_of_H, H); } else if (alg.Equals("ssh-dss")) { byte[] q = null; byte[] tmp; byte[] p; byte[] g; type = DSS; j = (int) ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j; p = tmp; j = (int) ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j; q = tmp; j = (int) ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j; g = tmp; j = (int) ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); tmp = new byte[j]; Array.Copy(K_S, i, tmp, 0, j); i += j; f = tmp; // SignatureDSA sig=new SignatureDSA(); // sig.init(); SignatureDSA sig = null; try { Type t = Type.GetType(session.getConfig("signature.dss")); sig = (SignatureDSA) (Activator.CreateInstance(t)); sig.init(); } catch (Exception ee) { Console.WriteLine(ee); } sig.setPubKey(f, p, q, g); sig.update(H); result = sig.verify(sig_of_H); } else { Console.WriteLine("unknow alg"); } state = STATE_END; break; } return result; } public override String getKeyType() { if (type == DSS) return "DSA"; return "RSA"; } public override int getState() { return state; } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. // Licensed under the MIT License. using System; using System.Windows; using System.Diagnostics; using System.ComponentModel; namespace InteractiveDataDisplay.WPF { /// <summary> /// Data series to define the color of markers. /// Converts value to brush (using <see cref="PaletteConverter"/>) and provides properties to control this convertion. /// </summary> public class ColorSeries : DataSeries { /// <summary> /// Initializes a new instance of the <see cref="ColorSeries"/> class. /// <para>The key for this data series is "C", default converter is <see cref="PaletteConverter"/>, /// default value is black color.</para> /// </summary> public ColorSeries() { this.Key = "C"; this.Description = "Color of the points"; this.Data = "Black"; this.Converter = new PaletteConverter(); this.DataChanged += new EventHandler(ColorSeries_DataChanged); } void ColorSeries_DataChanged(object sender, EventArgs e) { try { if (this.Data != null) { if (Palette.IsNormalized) { if (double.IsNaN(this.MinValue) || double.IsNaN(this.MaxValue)) PaletteRange = Range.Empty; else PaletteRange = new Range(this.MinValue, this.MaxValue); } } } catch (Exception exc) { Debug.WriteLine("Wrong value in ColorSeries: " + exc.Message); } } #region Palette /// <summary> /// Identifies the <see cref="Palette"/> dependency property. /// </summary> public static readonly DependencyProperty PaletteProperty = DependencyProperty.Register("Palette", typeof(IPalette), typeof(ColorSeries), new PropertyMetadata(InteractiveDataDisplay.WPF.Palette.Heat, (s,a) => ((ColorSeries)s).OnPalettePropertyChanged(a))); private void OnPalettePropertyChanged(DependencyPropertyChangedEventArgs e) { Palette newPalette = (Palette)e.NewValue; (Converter as PaletteConverter).Palette = newPalette; if (newPalette.IsNormalized && Data != null) { if (double.IsNaN(MinValue) || double.IsNaN(MaxValue)) PaletteRange = Range.Empty; else PaletteRange = new Range(MinValue, MaxValue); } else if (!newPalette.IsNormalized) PaletteRange = new Range(newPalette.Range.Min, newPalette.Range.Max); RaiseDataChanged(); } /// <summary> /// Gets or sets the color palette for markers. Defines mapping of values to colors. /// Is used only if the data is of any numeric type. /// <para>Default value is heat palette.</para> /// </summary> [TypeConverter(typeof(StringToPaletteTypeConverter))] public IPalette Palette { get { return (IPalette)GetValue(PaletteProperty); } set { SetValue(PaletteProperty, value); } } #endregion #region PaletteRange /// <summary> /// Identifies the <see cref="PaletteRange"/> dependency property. /// </summary> public static readonly DependencyProperty PaletteRangeProperty = DependencyProperty.Register("PaletteRange", typeof(Range), typeof(ColorSeries), new PropertyMetadata(new Range(0, 1), null)); /// <summary> /// Gets or sets the range which is displayed in legend if <see cref="ColorSeries.Palette"/> is normalized. /// Otherwise this property is ignored. /// <para>Default value is (0, 1).</para> /// </summary> public Range PaletteRange { get { return (Range)GetValue(PaletteRangeProperty); } set { SetValue(PaletteRangeProperty, value); } } #endregion } /// <summary> /// Data series to define the size of markers. /// Provides properties to set minimum and maximum sizes of markers to display. /// </summary> public class SizeSeries : DataSeries { /// <summary> /// Initializes a new instance of the <see cref="SizeSeries"/> class. /// The key for this data series is "D", default value is 10. /// </summary> public SizeSeries() { this.Key = "D"; this.Description = "Size of the points"; this.Data = 10; this.DataChanged += new EventHandler(SizeSeries_DataChanged); } void SizeSeries_DataChanged(object sender, EventArgs e) { try { if (this.Data != null) { Range range = Range.Empty; if (!double.IsNaN(this.MinValue) && !double.IsNaN(this.MaxValue)) range = new Range(this.MinValue, this.MaxValue); if (this.Converter != null) (this.Converter as ResizeConverter).Origin = range; Range = range; First = FindFirstDataItem(); } } catch (Exception exc) { Debug.WriteLine("Wrong value in SizeSeries: " + exc.Message); } } #region Range /// <summary> /// Identifies the <see cref="Range"/> dependency property. /// </summary> public static readonly DependencyProperty RangeProperty = DependencyProperty.Register("Range", typeof(Range), typeof(SizeSeries), new PropertyMetadata(new Range(0, 1), null)); /// <summary> /// Gets the actual size range of markers. /// </summary> public Range Range { get { return (Range)GetValue(RangeProperty); } internal set { SetValue(RangeProperty, value); } } #endregion #region Min, Max /// <summary> /// Identifies the <see cref="Min"/> dependency property. /// </summary> public static readonly DependencyProperty MinProperty = DependencyProperty.Register("Min", typeof(double), typeof(SizeSeries), new PropertyMetadata(Double.NaN, OnMinMaxPropertyChanged)); /// <summary> /// Gets or sets the minimum of size of markers to draw. /// <para>Default value is Double.NaN.</para> /// </summary> public double Min { get { return (double)GetValue(MinProperty); } set { SetValue(MinProperty, value); } } /// <summary> /// Identifies the <see cref="Max"/> dependency property. /// </summary> public static readonly DependencyProperty MaxProperty = DependencyProperty.Register("Max", typeof(double), typeof(SizeSeries), new PropertyMetadata(Double.NaN, OnMinMaxPropertyChanged)); /// <summary> /// Gets or sets the maximum of size of markers to draw. /// <para>Default value is Double.NaN.</para> /// </summary> public double Max { get { return (double)GetValue(MaxProperty); } set { SetValue(MaxProperty, value); } } private static void OnMinMaxPropertyChanged(object sender, DependencyPropertyChangedEventArgs e) { SizeSeries m = sender as SizeSeries; if (Double.IsNaN(m.Min) || Double.IsNaN(m.Max)) m.Converter = null; else { if (m.Converter == null) { if (m.Data != null) m.Converter = new ResizeConverter(new Range(m.MinValue, m.MaxValue), new Range(m.Min, m.Max)); else m.Converter = new ResizeConverter(new Range(0, 1), new Range(m.Min, m.Max)); } else (m.Converter as ResizeConverter).Resized = new Range(m.Min, m.Max); } m.RaiseDataChanged(); } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ReadOnlyDictionary<TKey, TValue> ** ** <OWNER>gpaperin</OWNER> ** ** Purpose: Read-only wrapper for another generic dictionary. ** ===========================================================*/ namespace System.Collections.ObjectModel { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] [DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> { private readonly IDictionary<TKey, TValue> m_dictionary; [NonSerialized] private Object m_syncRoot; [NonSerialized] private KeyCollection m_keys; [NonSerialized] private ValueCollection m_values; public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) { throw new ArgumentNullException("dictionary"); } Contract.EndContractBlock(); m_dictionary = dictionary; } protected IDictionary<TKey, TValue> Dictionary { get { return m_dictionary; } } public KeyCollection Keys { get { Contract.Ensures(Contract.Result<KeyCollection>() != null); if (m_keys == null) { m_keys = new KeyCollection(m_dictionary.Keys); } return m_keys; } } public ValueCollection Values { get { Contract.Ensures(Contract.Result<ValueCollection>() != null); if (m_values == null) { m_values = new ValueCollection(m_dictionary.Values); } return m_values; } } #region IDictionary<TKey, TValue> Members public bool ContainsKey(TKey key) { return m_dictionary.ContainsKey(key); } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return Keys; } } public bool TryGetValue(TKey key, out TValue value) { return m_dictionary.TryGetValue(key, out value); } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return Values; } } public TValue this[TKey key] { get { return m_dictionary[key]; } } void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool IDictionary<TKey, TValue>.Remove(TKey key) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } TValue IDictionary<TKey, TValue>.this[TKey key] { get { return m_dictionary[key]; } set { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members public int Count { get { return m_dictionary.Count; } } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return m_dictionary.Contains(item); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { m_dictionary.CopyTo(array, arrayIndex); } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return m_dictionary.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_dictionary).GetEnumerator(); } #endregion #region IDictionary Members private static bool IsCompatibleKey(object key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } return key is TKey; } void IDictionary.Add(object key, object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IDictionary.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool IDictionary.Contains(object key) { return IsCompatibleKey(key) && ContainsKey((TKey)key); } IDictionaryEnumerator IDictionary.GetEnumerator() { IDictionary d = m_dictionary as IDictionary; if (d != null) { return d.GetEnumerator(); } return new DictionaryEnumerator(m_dictionary); } bool IDictionary.IsFixedSize { get { return true; } } bool IDictionary.IsReadOnly { get { return true; } } ICollection IDictionary.Keys { get { return Keys; } } void IDictionary.Remove(object key) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ICollection IDictionary.Values { get { return Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { return this[(TKey)key]; } return null; } set { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { m_dictionary.CopyTo(pairs, index); } else { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; if (dictEntryArray != null) { foreach (var item in m_dictionary) { dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value); } } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } try { foreach (var item in m_dictionary) { objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value); } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_dictionary as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } [Serializable] private struct DictionaryEnumerator : IDictionaryEnumerator { private readonly IDictionary<TKey, TValue> m_dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator; public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary) { m_dictionary = dictionary; m_enumerator = m_dictionary.GetEnumerator(); } public DictionaryEntry Entry { get { return new DictionaryEntry(m_enumerator.Current.Key, m_enumerator.Current.Value); } } public object Key { get { return m_enumerator.Current.Key; } } public object Value { get { return m_enumerator.Current.Value; } } public object Current { get { return Entry; } } public bool MoveNext() { return m_enumerator.MoveNext(); } public void Reset() { m_enumerator.Reset(); } } #endregion #region IReadOnlyDictionary members IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { return Keys; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { return Values; } } #endregion IReadOnlyDictionary members [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private readonly ICollection<TKey> m_collection; [NonSerialized] private Object m_syncRoot; internal KeyCollection(ICollection<TKey> collection) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } m_collection = collection; } #region ICollection<T> Members void ICollection<TKey>.Add(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void ICollection<TKey>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool ICollection<TKey>.Contains(TKey item) { return m_collection.Contains(item); } public void CopyTo(TKey[] array, int arrayIndex) { m_collection.CopyTo(array, arrayIndex); } public int Count { get { return m_collection.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } bool ICollection<TKey>.Remove(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } #endregion #region IEnumerable<T> Members public IEnumerator<TKey> GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TKey>(m_collection, array, index); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #endregion } [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private readonly ICollection<TValue> m_collection; [NonSerialized] private Object m_syncRoot; internal ValueCollection(ICollection<TValue> collection) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } m_collection = collection; } #region ICollection<T> Members void ICollection<TValue>.Add(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void ICollection<TValue>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool ICollection<TValue>.Contains(TValue item) { return m_collection.Contains(item); } public void CopyTo(TValue[] array, int arrayIndex) { m_collection.CopyTo(array, arrayIndex); } public int Count { get { return m_collection.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } bool ICollection<TValue>.Remove(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } #endregion #region IEnumerable<T> Members public IEnumerator<TValue> GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TValue>(m_collection, array, index); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #endregion ICollection Members } } // To share code when possible, use a non-generic class to get rid of irrelevant type parameters. internal static class ReadOnlyDictionaryHelpers { #region Helper method for our KeyCollection and ValueCollection // Abstracted away to avoid redundant implementations. internal static void CopyToNonGenericICollectionHelper<T>(ICollection<T> collection, Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < collection.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } // Easy out if the ICollection<T> implements the non-generic ICollection ICollection nonGenericCollection = collection as ICollection; if (nonGenericCollection != null) { nonGenericCollection.CopyTo(array, index); return; } T[] items = array as T[]; if (items != null) { collection.CopyTo(items, index); } else { // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } try { foreach (var item in collection) { objects[index++] = item; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } } #endregion Helper method for our KeyCollection and ValueCollection } }
//----------------------------------------------------------------------- // <copyright file="AugmentedImageDatabaseInspector.cs" company="Google"> // // Copyright 2018 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using GoogleARCore; using UnityEditor; using UnityEngine; [CustomEditor(typeof(AugmentedImageDatabase))] [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Internal")] public class AugmentedImageDatabaseInspector : Editor { private const float k_ImageSpacerHeight = 55f; private const int k_PageSize = 5; private const float k_HeaderHeight = 30f; private static readonly Vector2 k_ContainerStart = new Vector2(14f, 87f); private static BackgroundJobExecutor s_QualityBackgroundExecutor = new BackgroundJobExecutor(); private static AugmentedImageDatabase s_DatabaseForQualityJobs = null; private static Dictionary<string, string> s_UpdatedQualityScores = new Dictionary<string, string>(); private int m_PageIndex = 0; public override void OnInspectorGUI() { AugmentedImageDatabase database = target as AugmentedImageDatabase; if (database == null) { return; } _RunDirtyQualityJobs(database); m_PageIndex = Mathf.Min(m_PageIndex, database.Count / k_PageSize); _DrawTitle(); _DrawContainer(); _DrawColumnNames(); int displayedImageCount = 0; int removeAt = -1; int pageStartIndex = m_PageIndex * k_PageSize; int pageEndIndex = Mathf.Min(database.Count, pageStartIndex + k_PageSize); for (int i = pageStartIndex; i < pageEndIndex; i++, displayedImageCount++) { AugmentedImageDatabaseEntry updatedImage; bool wasRemoved; _DrawImageField(database[i], out updatedImage, out wasRemoved); if (wasRemoved) { removeAt = i; } else if (!database[i].Equals(updatedImage)) { database[i] = updatedImage; } } if (removeAt > -1) { database.RemoveAt(removeAt); } _DrawImageSpacers(displayedImageCount); _DrawPageField(database.Count); } private static void _RunDirtyQualityJobs(AugmentedImageDatabase database) { if (database == null) { return; } if (s_DatabaseForQualityJobs != database) { // If another database is already running quality evaluation, // stop all pending jobs to prioritise the current database. if (s_DatabaseForQualityJobs != null) { s_QualityBackgroundExecutor.RemoveAllPendingJobs(); } s_DatabaseForQualityJobs = database; } _UpdateDatabaseQuality(database); // Set database dirty to refresh inspector UI for each frame that there are still pending jobs. // Otherwise if there exists one frame with no newly finished jobs, the UI will never get refreshed. // EditorUtility.SetDirty can only be called from main thread. if (s_QualityBackgroundExecutor.PendingJobsCount > 0) { EditorUtility.SetDirty(database); return; } List<AugmentedImageDatabaseEntry> dirtyEntries = database.GetDirtyQualityEntries(); if (dirtyEntries.Count == 0) { return; } string cliBinaryPath; if (!AugmentedImageDatabase.FindCliBinaryPath(out cliBinaryPath)) { return; } for (int i = 0; i < dirtyEntries.Count; ++i) { AugmentedImageDatabaseEntry image = dirtyEntries[i]; var imagePath = AssetDatabase.GetAssetPath(image.Texture); var textureGUID = image.TextureGUID; s_QualityBackgroundExecutor.PushJob(() => { string quality; string error; ShellHelper.RunCommand(cliBinaryPath, string.Format("eval-img --input_image_path \"{0}\"", imagePath), out quality, out error); if (!string.IsNullOrEmpty(error)) { Debug.LogWarning(error); return; } lock (s_UpdatedQualityScores) { s_UpdatedQualityScores.Add(textureGUID, quality); } }); } // For refreshing inspector UI as new jobs have been enqueued. EditorUtility.SetDirty(database); } private static void _UpdateDatabaseQuality(AugmentedImageDatabase database) { lock (s_UpdatedQualityScores) { if (s_UpdatedQualityScores.Count == 0) { return; } for (int i = 0; i < database.Count; ++i) { if (s_UpdatedQualityScores.ContainsKey(database[i].TextureGUID)) { AugmentedImageDatabaseEntry updatedImage = database[i]; updatedImage.Quality = s_UpdatedQualityScores[updatedImage.TextureGUID]; database[i] = updatedImage; } } s_UpdatedQualityScores.Clear(); } // For refreshing inspector UI for updated quality scores. EditorUtility.SetDirty(database); } private void _DrawTitle() { const string TITLE_STRING = "Images in Database"; GUIStyle titleStyle = new GUIStyle(); titleStyle.alignment = TextAnchor.MiddleCenter; titleStyle.stretchWidth = true; titleStyle.fontSize = 14; titleStyle.normal.textColor = Color.white; titleStyle.padding.bottom = 15; EditorGUILayout.BeginVertical(); GUILayout.Space(15); EditorGUILayout.LabelField(TITLE_STRING, titleStyle); GUILayout.Space(5); EditorGUILayout.EndVertical(); } private void _DrawContainer() { var containerRect = new Rect(k_ContainerStart.x, k_ContainerStart.y, EditorGUIUtility.currentViewWidth - 30, (k_PageSize * k_ImageSpacerHeight) + k_HeaderHeight); GUI.Box(containerRect, string.Empty); } private void _DrawColumnNames() { EditorGUILayout.BeginVertical(); GUILayout.Space(5); EditorGUILayout.BeginHorizontal(); GUILayout.Space(45); var style = new GUIStyle(GUI.skin.label); style.alignment = TextAnchor.MiddleLeft; GUILayoutOption[] options = { GUILayout.Height(k_HeaderHeight - 10), GUILayout.MaxWidth(80f) }; EditorGUILayout.LabelField("Name", style, options); GUILayout.Space(5); EditorGUILayout.LabelField("Width(m)", style, options); GUILayout.Space(5); EditorGUILayout.LabelField("Quality", style, options); GUILayout.FlexibleSpace(); GUILayout.Space(60); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); } private string _QualityForDisplay(string quality) { if (string.IsNullOrEmpty(quality)) { return "Calculating..."; } if (quality == "?") { return "?"; } return quality + "/100"; } private void _DrawImageField(AugmentedImageDatabaseEntry image, out AugmentedImageDatabaseEntry updatedImage, out bool wasRemoved) { updatedImage = new AugmentedImageDatabaseEntry(); EditorGUILayout.BeginVertical(); GUILayout.Space(5); EditorGUILayout.BeginHorizontal(); GUILayout.Space(15); var buttonStyle = new GUIStyle(GUI.skin.button); buttonStyle.margin = new RectOffset(10, 10, 13, 0); wasRemoved = GUILayout.Button("X", buttonStyle); var textFieldStyle = new GUIStyle(GUI.skin.textField); textFieldStyle.margin = new RectOffset(5, 5, 15, 0); updatedImage.Name = EditorGUILayout.TextField(image.Name, textFieldStyle, GUILayout.MaxWidth(80f)); GUILayout.Space(5); updatedImage.Width = EditorGUILayout.FloatField(image.Width, textFieldStyle, GUILayout.MaxWidth(80f)); var labelStyle = new GUIStyle(GUI.skin.label); labelStyle.alignment = TextAnchor.MiddleLeft; GUILayout.Space(5); EditorGUILayout.LabelField(_QualityForDisplay(image.Quality), labelStyle, GUILayout.Height(42), GUILayout.MaxWidth(80f)); GUILayout.FlexibleSpace(); updatedImage.Texture = EditorGUILayout.ObjectField(image.Texture, typeof(Texture2D), false, GUILayout.Height(45), GUILayout.Width(45)) as Texture2D; if (updatedImage.TextureGUID == image.TextureGUID) { updatedImage.Quality = image.Quality; } GUILayout.Space(15); EditorGUILayout.EndHorizontal(); GUILayout.Space(5); EditorGUILayout.EndVertical(); } private void _DrawImageSpacers(int displayedImageCount) { EditorGUILayout.BeginVertical(); GUILayout.Space((k_PageSize - displayedImageCount) * k_ImageSpacerHeight); EditorGUILayout.EndVertical(); } private void _DrawPageField(int imageCount) { var lastPageIndex = Mathf.Max(imageCount - 1, 0) / k_PageSize; EditorGUILayout.BeginHorizontal(); GUILayout.Space(15); var labelStyle = new GUIStyle(GUI.skin.label); labelStyle.alignment = TextAnchor.MiddleLeft; EditorGUILayout.LabelField(string.Format("{0} Total Images", imageCount), labelStyle, GUILayout.Height(42), GUILayout.Width(100)); GUILayout.FlexibleSpace(); EditorGUILayout.LabelField("Page", labelStyle, GUILayout.Height(42), GUILayout.Width(30)); var textStyle = new GUIStyle(GUI.skin.textField); textStyle.margin = new RectOffset(0, 0, 15, 0); var pageString = EditorGUILayout.TextField((m_PageIndex + 1).ToString(), textStyle, GUILayout.Width(30)); int pageNumber; int.TryParse(pageString, out pageNumber); m_PageIndex = Mathf.Clamp(pageNumber - 1, 0, lastPageIndex); var buttonStyle = new GUIStyle(GUI.skin.button); buttonStyle.margin = new RectOffset(10, 10, 13, 0); GUI.enabled = m_PageIndex > 0; bool moveLeft = GUILayout.Button("<", buttonStyle); GUI.enabled = m_PageIndex < lastPageIndex; bool moveRight = GUILayout.Button(">", buttonStyle); GUI.enabled = true; m_PageIndex = moveLeft ? m_PageIndex - 1 : m_PageIndex; m_PageIndex = moveRight ? m_PageIndex + 1 : m_PageIndex; GUILayout.Space(15); EditorGUILayout.EndHorizontal(); } } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Annotations; using NodaTime.Globalization; using NodaTime.Text.Patterns; using NodaTime.Utility; using System.Globalization; using System.Text; namespace NodaTime.Text { /// <summary> /// Represents a pattern for parsing and formatting <see cref="LocalDate"/> values. /// </summary> /// <threadsafety> /// When used with a read-only <see cref="CultureInfo" />, this type is immutable and instances /// may be shared freely between threads. We recommend only using read-only cultures for patterns, although this is /// not currently enforced. /// </threadsafety> [Immutable] // Well, assuming an immutable culture... public sealed class LocalDatePattern : IPattern<LocalDate> { internal static readonly LocalDate DefaultTemplateValue = new LocalDate(2000, 1, 1); private const string DefaultFormatPattern = "D"; // Long internal static readonly PatternBclSupport<LocalDate> BclSupport = new PatternBclSupport<LocalDate>(DefaultFormatPattern, fi => fi.LocalDatePatternParser); /// <summary> /// Gets an invariant local date pattern which is ISO-8601 compatible and which round trips values, but doesn't include the calendar system. /// This corresponds to the text pattern "uuuu'-'MM'-'dd". /// </summary> /// <remarks> /// This pattern corresponds to the 'R' standard pattern. /// </remarks> /// <value>An invariant local date pattern which is ISO-8601 compatible.</value> public static LocalDatePattern Iso => Patterns.IsoPatternImpl; /// <summary> /// Gets an invariant local date pattern which round trips values including the calendar system. /// This corresponds to the text pattern "uuuu'-'MM'-'dd '('c')'". /// </summary> /// <remarks> /// This pattern corresponds to the 'r' standard pattern. /// </remarks> /// <value>An invariant local date pattern which round trips values including the calendar system.</value> public static LocalDatePattern FullRoundtrip => Patterns.FullRoundtripPatternImpl; /// <summary> /// Class whose existence is solely to avoid type initialization order issues, most of which stem /// from needing NodaFormatInfo.InvariantInfo... /// </summary> internal static class Patterns { internal static readonly LocalDatePattern IsoPatternImpl = CreateWithInvariantCulture("uuuu'-'MM'-'dd"); internal static readonly LocalDatePattern FullRoundtripPatternImpl = CreateWithInvariantCulture("uuuu'-'MM'-'dd '('c')'"); } /// <summary> /// Returns the pattern that this object delegates to. Mostly useful to avoid this public class /// implementing an internal interface. /// </summary> internal IPartialPattern<LocalDate> UnderlyingPattern { get; } /// <summary> /// Gets the pattern text for this pattern, as supplied on creation. /// </summary> /// <value>The pattern text for this pattern, as supplied on creation.</value> public string PatternText { get; } /// <summary> /// Returns the localization information used in this pattern. /// </summary> private NodaFormatInfo FormatInfo { get; } /// <summary> /// Gets the value used as a template for parsing: any field values unspecified /// in the pattern are taken from the template. /// </summary> /// <value>The value used as a template for parsing.</value> public LocalDate TemplateValue { get; } private LocalDatePattern(string patternText, NodaFormatInfo formatInfo, LocalDate templateValue, IPartialPattern<LocalDate> pattern) { PatternText = patternText; FormatInfo = formatInfo; TemplateValue = templateValue; UnderlyingPattern = pattern; } /// <summary> /// Parses the given text value according to the rules of this pattern. /// </summary> /// <remarks> /// This method never throws an exception (barring a bug in Noda Time itself). Even errors such as /// the argument being null are wrapped in a parse result. /// </remarks> /// <param name="text">The text value to parse.</param> /// <returns>The result of parsing, which may be successful or unsuccessful.</returns> public ParseResult<LocalDate> Parse([SpecialNullHandling] string text) => UnderlyingPattern.Parse(text); /// <summary> /// Formats the given local date as text according to the rules of this pattern. /// </summary> /// <param name="value">The local date to format.</param> /// <returns>The local date formatted according to this pattern.</returns> public string Format(LocalDate value) => UnderlyingPattern.Format(value); /// <summary> /// Formats the given value as text according to the rules of this pattern, /// appending to the given <see cref="StringBuilder"/>. /// </summary> /// <param name="value">The value to format.</param> /// <param name="builder">The <c>StringBuilder</c> to append to.</param> /// <returns>The builder passed in as <paramref name="builder"/>.</returns> public StringBuilder AppendFormat(LocalDate value, StringBuilder builder) => UnderlyingPattern.AppendFormat(value, builder); /// <summary> /// Creates a pattern for the given pattern text, format info, and template value. /// </summary> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="formatInfo">The format info to use in the pattern</param> /// <param name="templateValue">Template value to use for unspecified fields</param> /// <returns>A pattern for parsing and formatting local dates.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> internal static LocalDatePattern Create(string patternText, NodaFormatInfo formatInfo, LocalDate templateValue) { Preconditions.CheckNotNull(patternText, nameof(patternText)); Preconditions.CheckNotNull(formatInfo, nameof(formatInfo)); // Use the "fixed" parser for the common case of the default template value. var pattern = templateValue == DefaultTemplateValue ? formatInfo.LocalDatePatternParser.ParsePattern(patternText) : new LocalDatePatternParser(templateValue).ParsePattern(patternText, formatInfo); // If ParsePattern returns a standard pattern instance, we need to get the underlying partial pattern. pattern = (pattern as LocalDatePattern)?.UnderlyingPattern ?? pattern; var partialPattern = (IPartialPattern<LocalDate>) pattern; return new LocalDatePattern(patternText, formatInfo, templateValue, partialPattern); } /// <summary> /// Creates a pattern for the given pattern text, culture, and template value. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="cultureInfo">The culture to use in the pattern</param> /// <param name="templateValue">Template value to use for unspecified fields</param> /// <returns>A pattern for parsing and formatting local dates.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static LocalDatePattern Create(string patternText, CultureInfo cultureInfo, LocalDate templateValue) => Create(patternText, NodaFormatInfo.GetFormatInfo(cultureInfo), templateValue); /// <summary> /// Creates a pattern for the given pattern text and culture, with a template value of 2000-01-01. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="cultureInfo">The culture to use in the pattern</param> /// <returns>A pattern for parsing and formatting local dates.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static LocalDatePattern Create(string patternText, CultureInfo cultureInfo) => Create(patternText, cultureInfo, DefaultTemplateValue); /// <summary> /// Creates a pattern for the given pattern text in the current thread's current culture. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. Note that the current culture /// is captured at the time this method is called - it is not captured at the point of parsing /// or formatting values. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <returns>A pattern for parsing and formatting local dates.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static LocalDatePattern CreateWithCurrentCulture(string patternText) => Create(patternText, NodaFormatInfo.CurrentInfo, DefaultTemplateValue); /// <summary> /// Creates a pattern for the given pattern text in the invariant culture. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. Note that the current culture /// is captured at the time this method is called - it is not captured at the point of parsing /// or formatting values. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <returns>A pattern for parsing and formatting local dates.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static LocalDatePattern CreateWithInvariantCulture(string patternText) => Create(patternText, NodaFormatInfo.InvariantInfo, DefaultTemplateValue); /// <summary> /// Creates a pattern for the same original pattern text as this pattern, but with the specified /// localization information. /// </summary> /// <param name="formatInfo">The localization information to use in the new pattern.</param> /// <returns>A new pattern with the given localization information.</returns> private LocalDatePattern WithFormatInfo(NodaFormatInfo formatInfo) => Create(PatternText, formatInfo, TemplateValue); /// <summary> /// Creates a pattern for the same original pattern text as this pattern, but with the specified /// culture. /// </summary> /// <param name="cultureInfo">The culture to use in the new pattern.</param> /// <returns>A new pattern with the given culture.</returns> public LocalDatePattern WithCulture(CultureInfo cultureInfo) => WithFormatInfo(NodaFormatInfo.GetFormatInfo(cultureInfo)); /// <summary> /// Creates a pattern like this one, but with the specified template value. /// </summary> /// <param name="newTemplateValue">The template value for the new pattern, used to fill in unspecified fields.</param> /// <returns>A new pattern with the given template value.</returns> public LocalDatePattern WithTemplateValue(LocalDate newTemplateValue) => Create(PatternText, FormatInfo, newTemplateValue); /// <summary> /// Creates a pattern like this one, but with the template value modified to use /// the specified calendar system. /// </summary> /// <remarks> /// <para> /// Care should be taken in two (relatively rare) scenarios. Although the default template value /// is supported by all Noda Time calendar systems, if a pattern is created with a different /// template value and then this method is called with a calendar system which doesn't support that /// date, an exception will be thrown. Additionally, if the pattern only specifies some date fields, /// it's possible that the new template value will not be suitable for all values. /// </para> /// </remarks> /// <param name="calendar">The calendar system to convert the template value into.</param> /// <returns>A new pattern with a template value in the specified calendar system.</returns> public LocalDatePattern WithCalendar(CalendarSystem calendar) => WithTemplateValue(TemplateValue.WithCalendar(calendar)); } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; namespace OpenQA.Selenium { [TestFixture] public class FormHandlingTests : DriverTestFixture { [Test] public void ShouldClickOnSubmitInputElements() { driver.Url = formsPage; driver.FindElement(By.Id("submitButton")).Click(); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ClickingOnUnclickableElementsDoesNothing() { driver.Url = formsPage; driver.FindElement(By.XPath("//body")).Click(); } [Test] public void ShouldBeAbleToClickImageButtons() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Click(); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldBeAbleToSubmitForms() { driver.Url = formsPage; driver.FindElement(By.Name("login")).Submit(); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldSubmitAFormWhenAnyInputElementWithinThatFormIsSubmitted() { driver.Url = formsPage; driver.FindElement(By.Id("checky")).Submit(); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldSubmitAFormWhenAnyElementWihinThatFormIsSubmitted() { driver.Url = formsPage; driver.FindElement(By.XPath("//form/p")).Submit(); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotBeAbleToSubmitAFormThatDoesNotExist() { driver.Url = formsPage; driver.FindElement(By.Name("there is no spoon")).Submit(); } [Test] public void ShouldBeAbleToEnterTextIntoATextAreaBySettingItsValue() { driver.Url = javascriptPage; IWebElement textarea = driver.FindElement(By.Id("keyUpArea")); String cheesey = "Brie and cheddar"; textarea.SendKeys(cheesey); Assert.AreEqual(textarea.Value, cheesey); } [Test] [IgnoreBrowser(Browser.ChromeNonWindows)] public void ShouldSubmitAFormUsingTheNewlineLiteral() { driver.Url = formsPage; IWebElement nestedForm = driver.FindElement(By.Id("nested_form")); IWebElement input = nestedForm.FindElement(By.Name("x")); input.SendKeys("\n"); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); Assert.AreEqual("We Arrive Here", driver.Title); Assert.IsTrue(driver.Url.EndsWith("?x=name")); } [Test] [IgnoreBrowser(Browser.ChromeNonWindows)] public void ShouldSubmitAFormUsingTheEnterKey() { driver.Url = formsPage; IWebElement nestedForm = driver.FindElement(By.Id("nested_form")); IWebElement input = nestedForm.FindElement(By.Name("x")); input.SendKeys(Keys.Enter); //TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented. System.Threading.Thread.Sleep(500); Assert.AreEqual("We Arrive Here", driver.Title); Assert.IsTrue(driver.Url.EndsWith("?x=name")); } [Test] public void ShouldEnterDataIntoFormFields() { driver.Url = xhtmlTestPage; IWebElement element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']")); String originalValue = element.Value; Assert.AreEqual(originalValue, "change"); element.Clear(); element.SendKeys("some text"); element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']")); String newFormValue = element.Value; Assert.AreEqual(newFormValue, "some text"); } [Test] public void ShouldBeAbleToSelectACheckBox() { driver.Url = formsPage; IWebElement checkbox = driver.FindElement(By.Id("checky")); Assert.AreEqual(checkbox.Selected, false); checkbox.Select(); Assert.AreEqual(checkbox.Selected, true); checkbox.Select(); Assert.AreEqual(checkbox.Selected, true); } [Test] public void ShouldToggleTheCheckedStateOfACheckbox() { driver.Url = formsPage; IWebElement checkbox = driver.FindElement(By.Id("checky")); Assert.AreEqual(checkbox.Selected, false); checkbox.Toggle(); Assert.AreEqual(checkbox.Selected, true); checkbox.Toggle(); Assert.AreEqual(checkbox.Selected, false); } [Test] public void TogglingACheckboxShouldReturnItsCurrentState() { driver.Url = formsPage; IWebElement checkbox = driver.FindElement(By.Id("checky")); Assert.AreEqual(checkbox.Selected, false); bool isChecked = checkbox.Toggle(); Assert.AreEqual(isChecked, true); isChecked = checkbox.Toggle(); Assert.AreEqual(isChecked, false); } [Test] [ExpectedException(typeof(NotSupportedException))] public void ShouldNotBeAbleToSelectSomethingThatIsDisabled() { driver.Url = formsPage; IWebElement radioButton = driver.FindElement(By.Id("nothing")); Assert.AreEqual(radioButton.Enabled, false); radioButton.Select(); } [Test] public void ShouldBeAbleToSelectARadioButton() { driver.Url = formsPage; IWebElement radioButton = driver.FindElement(By.Id("peas")); Assert.AreEqual(radioButton.Selected, false); radioButton.Select(); Assert.AreEqual(radioButton.Selected, true); } [Test] public void ShouldBeAbleToSelectARadioButtonByClickingOnIt() { driver.Url = formsPage; IWebElement radioButton = driver.FindElement(By.Id("peas")); Assert.AreEqual(radioButton.Selected, false); radioButton.Click(); Assert.AreEqual(radioButton.Selected, true); } [Test] public void ShouldReturnStateOfRadioButtonsBeforeInteration() { driver.Url = formsPage; IWebElement radioButton = driver.FindElement(By.Id("cheese_and_peas")); Assert.AreEqual(radioButton.Selected, true); radioButton = driver.FindElement(By.Id("cheese")); Assert.AreEqual(radioButton.Selected, false); } [Test] [ExpectedException(typeof(NotImplementedException))] public void ShouldThrowAnExceptionWhenTogglingTheStateOfARadioButton() { driver.Url = formsPage; IWebElement radioButton = driver.FindElement(By.Id("cheese")); radioButton.Toggle(); } [Test] [IgnoreBrowser(Browser.IE, "IE allows toggling of an option not in a multiselect")] [ExpectedException(typeof(NotImplementedException))] public void TogglingAnOptionShouldThrowAnExceptionIfTheOptionIsNotInAMultiSelect() { driver.Url = formsPage; IWebElement select = driver.FindElement(By.Name("selectomatic")); IWebElement option = select.FindElements(By.TagName("option"))[0]; option.Toggle(); } [Test] public void TogglingAnOptionShouldToggleOptionsInAMultiSelect() { driver.Url = formsPage; IWebElement select = driver.FindElement(By.Name("multi")); IWebElement option = select.FindElements(By.TagName("option"))[0]; bool selected = option.Selected; bool current = option.Toggle(); Assert.IsFalse(selected == current); current = option.Toggle(); Assert.IsTrue(selected == current); } [Test] [IgnoreBrowser(Browser.Chrome, "ChromeDriver does not yet support file uploads")] public void ShouldBeAbleToAlterTheContentsOfAFileUploadInputElement() { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.Value)); System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt"); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.Value); Assert.AreEqual(inputFile.FullName, outputFile.FullName); inputFile.Delete(); } [Test] [ExpectedException(typeof(NotSupportedException))] public void ShouldThrowAnExceptionWhenSelectingAnUnselectableElement() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.XPath("//title")); element.Select(); } [Test] public void SendingKeyboardEventsShouldAppendTextInInputs() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); element.SendKeys("Some"); String value = element.Value; Assert.AreEqual(value, "Some"); element.SendKeys(" text"); value = element.Value; Assert.AreEqual(value, "Some text"); } [Test] [IgnoreBrowser(Browser.IE, "Not implemented going to the end of the line first")] [IgnoreBrowser(Browser.HtmlUnit, "Not implemented going to the end of the line first")] [IgnoreBrowser(Browser.Chrome, "Not implemented going to the end of the line first")] public void SendingKeyboardEventsShouldAppendTextinTextAreas() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("withText")); element.SendKeys(". Some text"); String value = element.Value; Assert.AreEqual(value, "Example text. Some text"); } [Test] public void ShouldBeAbleToClearTextFromInputElements() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); element.SendKeys("Some text"); String value = element.Value; Assert.IsTrue(value.Length > 0); element.Clear(); value = element.Value; Assert.AreEqual(value.Length, 0); } [Test] public void EmptyTextBoxesShouldReturnAnEmptyStringNotNull() { driver.Url = formsPage; IWebElement emptyTextBox = driver.FindElement(By.Id("working")); Assert.AreEqual(emptyTextBox.Value, ""); IWebElement emptyTextArea = driver.FindElement(By.Id("emptyTextArea")); Assert.AreEqual(emptyTextBox.Value, ""); } [Test] public void ShouldBeAbleToClearTextFromTextAreas() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("withText")); element.SendKeys("Some text"); String value = element.Value; Assert.IsTrue(value.Length > 0); element.Clear(); value = element.Value; Assert.AreEqual(value.Length, 0); } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Egl { /// <summary> /// [EGL] Value of EGL_NO_STREAM_KHR symbol. /// </summary> [RequiredByFeature("EGL_KHR_stream")] public const int NO_STREAM_KHR = 0; /// <summary> /// [EGL] Value of EGL_PRODUCER_FRAME_KHR symbol. /// </summary> [RequiredByFeature("EGL_KHR_stream")] public const int PRODUCER_FRAME_KHR = 0x3212; /// <summary> /// [EGL] Value of EGL_CONSUMER_FRAME_KHR symbol. /// </summary> [RequiredByFeature("EGL_KHR_stream")] public const int CONSUMER_FRAME_KHR = 0x3213; /// <summary> /// [EGL] Value of EGL_STREAM_STATE_EMPTY_KHR symbol. /// </summary> [RequiredByFeature("EGL_KHR_stream")] public const int STREAM_STATE_EMPTY_KHR = 0x3217; /// <summary> /// [EGL] Value of EGL_STREAM_STATE_NEW_FRAME_AVAILABLE_KHR symbol. /// </summary> [RequiredByFeature("EGL_KHR_stream")] public const int STREAM_STATE_NEW_FRAME_AVAILABLE_KHR = 0x3218; /// <summary> /// [EGL] Value of EGL_STREAM_STATE_OLD_FRAME_AVAILABLE_KHR symbol. /// </summary> [RequiredByFeature("EGL_KHR_stream")] public const int STREAM_STATE_OLD_FRAME_AVAILABLE_KHR = 0x3219; /// <summary> /// [EGL] Value of EGL_STREAM_STATE_DISCONNECTED_KHR symbol. /// </summary> [RequiredByFeature("EGL_KHR_stream")] public const int STREAM_STATE_DISCONNECTED_KHR = 0x321A; /// <summary> /// [EGL] Value of EGL_BAD_STREAM_KHR symbol. /// </summary> [RequiredByFeature("EGL_KHR_stream")] public const int BAD_STREAM_KHR = 0x321B; /// <summary> /// [EGL] Value of EGL_BAD_STATE_KHR symbol. /// </summary> [RequiredByFeature("EGL_KHR_stream")] public const int BAD_STATE_KHR = 0x321C; /// <summary> /// [EGL] eglCreateStreamKHR: Binding for eglCreateStreamKHR. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attrib_list"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("EGL_KHR_stream")] public static IntPtr CreateStreamKHR(IntPtr dpy, int[] attrib_list) { IntPtr retValue; unsafe { fixed (int* p_attrib_list = attrib_list) { Debug.Assert(Delegates.peglCreateStreamKHR != null, "peglCreateStreamKHR not implemented"); retValue = Delegates.peglCreateStreamKHR(dpy, p_attrib_list); LogCommand("eglCreateStreamKHR", retValue, dpy, attrib_list ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglDestroyStreamKHR: Binding for eglDestroyStreamKHR. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="stream"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("EGL_KHR_stream")] public static bool DestroyStreamKHR(IntPtr dpy, IntPtr stream) { bool retValue; Debug.Assert(Delegates.peglDestroyStreamKHR != null, "peglDestroyStreamKHR not implemented"); retValue = Delegates.peglDestroyStreamKHR(dpy, stream); LogCommand("eglDestroyStreamKHR", retValue, dpy, stream ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglStreamAttribKHR: Binding for eglStreamAttribKHR. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="stream"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attribute"> /// A <see cref="T:uint"/>. /// </param> /// <param name="value"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("EGL_KHR_stream")] public static bool StreamAttribKHR(IntPtr dpy, IntPtr stream, uint attribute, int value) { bool retValue; Debug.Assert(Delegates.peglStreamAttribKHR != null, "peglStreamAttribKHR not implemented"); retValue = Delegates.peglStreamAttribKHR(dpy, stream, attribute, value); LogCommand("eglStreamAttribKHR", retValue, dpy, stream, attribute, value ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglQueryStreamKHR: Binding for eglQueryStreamKHR. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="stream"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attribute"> /// A <see cref="T:uint"/>. /// </param> /// <param name="value"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("EGL_KHR_stream")] public static bool QueryStreamKHR(IntPtr dpy, IntPtr stream, uint attribute, int[] value) { bool retValue; unsafe { fixed (int* p_value = value) { Debug.Assert(Delegates.peglQueryStreamKHR != null, "peglQueryStreamKHR not implemented"); retValue = Delegates.peglQueryStreamKHR(dpy, stream, attribute, p_value); LogCommand("eglQueryStreamKHR", retValue, dpy, stream, attribute, value ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglQueryStreamu64KHR: Binding for eglQueryStreamu64KHR. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="stream"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attribute"> /// A <see cref="T:uint"/>. /// </param> /// <param name="value"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("EGL_KHR_stream")] public static bool QueryStreamKHR(IntPtr dpy, IntPtr stream, uint attribute, ulong[] value) { bool retValue; unsafe { fixed (ulong* p_value = value) { Debug.Assert(Delegates.peglQueryStreamu64KHR != null, "peglQueryStreamu64KHR not implemented"); retValue = Delegates.peglQueryStreamu64KHR(dpy, stream, attribute, p_value); LogCommand("eglQueryStreamu64KHR", retValue, dpy, stream, attribute, value ); } } DebugCheckErrors(retValue); return (retValue); } internal static unsafe partial class Delegates { [RequiredByFeature("EGL_KHR_stream")] [SuppressUnmanagedCodeSecurity] internal delegate IntPtr eglCreateStreamKHR(IntPtr dpy, int* attrib_list); [RequiredByFeature("EGL_KHR_stream")] internal static eglCreateStreamKHR peglCreateStreamKHR; [RequiredByFeature("EGL_KHR_stream")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglDestroyStreamKHR(IntPtr dpy, IntPtr stream); [RequiredByFeature("EGL_KHR_stream")] internal static eglDestroyStreamKHR peglDestroyStreamKHR; [RequiredByFeature("EGL_KHR_stream")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglStreamAttribKHR(IntPtr dpy, IntPtr stream, uint attribute, int value); [RequiredByFeature("EGL_KHR_stream")] internal static eglStreamAttribKHR peglStreamAttribKHR; [RequiredByFeature("EGL_KHR_stream")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglQueryStreamKHR(IntPtr dpy, IntPtr stream, uint attribute, int* value); [RequiredByFeature("EGL_KHR_stream")] internal static eglQueryStreamKHR peglQueryStreamKHR; [RequiredByFeature("EGL_KHR_stream")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglQueryStreamu64KHR(IntPtr dpy, IntPtr stream, uint attribute, ulong* value); [RequiredByFeature("EGL_KHR_stream")] internal static eglQueryStreamu64KHR peglQueryStreamu64KHR; } } }
using System; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using Common.Logging; using Common.Logging.Simple; using Rhino.Mocks; using Rhino.Queues.Exceptions; using Rhino.Queues.Model; using Rhino.Queues.Protocol; using Xunit; namespace Rhino.Queues.Tests.Protocol { public class RecieverFailure { private readonly ManualResetEvent wait = new ManualResetEvent(false); private readonly IPEndPoint endpointToListenTo = new IPEndPoint(IPAddress.Loopback, 23456); private readonly CapturingLoggerFactoryAdapter adapter; public RecieverFailure() { adapter = new CapturingLoggerFactoryAdapter(); LogManager.Adapter = adapter; } [Fact] public void CanHandleClientConnectAndDisconnect() { using (var reciever = new Receiver(endpointToListenTo, messages => null)) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); } wait.WaitOne(); var warn = (from e in adapter.LoggerEvents where e.Level == LogLevel.Warn && e.RenderedMessage.StartsWith("Unable to read length data from") select e).FirstOrDefault(); Assert.NotNull(warn); } } [Fact] public void CanHandleClientSendingThreeBytesAndDisconnecting() { using (var reciever = new Receiver(endpointToListenTo, messages => null)) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); client.GetStream().Write(new byte[] { 1, 4, 6 }, 0, 3); } wait.WaitOne(); var warn = (from e in adapter.LoggerEvents where e.Level == LogLevel.Warn && e.RenderedMessage.StartsWith("Unable to read length data from") select e).FirstOrDefault(); Assert.NotNull(warn); } } [Fact] public void CanHandleClientSendingNegativeNumberForLength() { using (var reciever = new Receiver(endpointToListenTo, messages => null)) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); client.GetStream().Write(BitConverter.GetBytes(-2), 0, 4); } wait.WaitOne(); var warn = (from e in adapter.LoggerEvents where e.Level == LogLevel.Warn && e.RenderedMessage.StartsWith("Got invalid length -2") select e).FirstOrDefault(); Assert.NotNull(warn); } } [Fact] public void CanHandleClientSendingBadLengthOfData() { using (var reciever = new Receiver(endpointToListenTo, messages => null)) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); var stream = client.GetStream(); stream.Write(BitConverter.GetBytes(16), 0, 4); stream.Write(BitConverter.GetBytes(5), 0, 4); } wait.WaitOne(); var warn = (from e in adapter.LoggerEvents where e.Level == LogLevel.Warn && e.RenderedMessage.StartsWith("Unable to read message data") select e).FirstOrDefault(); Assert.NotNull(warn); } } [Fact] public void CanHandleClientSendingUnseriliazableData() { using (var reciever = new Receiver(endpointToListenTo, messages => null)) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); var stream = client.GetStream(); stream.Write(BitConverter.GetBytes(16), 0, 4); stream.Write(Guid.NewGuid().ToByteArray(), 0, 16); } wait.WaitOne(); var warn = (from e in adapter.LoggerEvents where e.Level == LogLevel.Warn && e.RenderedMessage.StartsWith("Failed to deserialize messages from") select e).FirstOrDefault(); Assert.NotNull(warn); } } [Fact] public void WillLetSenderKnowThatMessagesWereNotProcessed() { using (var reciever = new Receiver(endpointToListenTo, messages => { throw new InvalidOperationException(); })) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); var stream = client.GetStream(); var serialize = new Message[0].Serialize(); stream.Write(BitConverter.GetBytes(serialize.Length), 0, 4); stream.Write(serialize, 0, serialize.Length); var buffer = new byte[ProtocolConstants.ProcessingFailureBuffer.Length]; stream.Read(buffer, 0, buffer.Length); Assert.Equal(ProtocolConstants.ProcessingFailure, Encoding.Unicode.GetString(buffer)); } wait.WaitOne(); } } [Fact] public void WillLetSenderKnowThatMessagesWereSentToInvalidQueue() { using (var reciever = new Receiver(endpointToListenTo, messages => { throw new QueueDoesNotExistsException(); })) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); var stream = client.GetStream(); var serialize = new Message[0].Serialize(); stream.Write(BitConverter.GetBytes(serialize.Length), 0, 4); stream.Write(serialize, 0, serialize.Length); var buffer = new byte[ProtocolConstants.ProcessingFailureBuffer.Length]; stream.Read(buffer, 0, buffer.Length); Assert.Equal(ProtocolConstants.QueueDoesNotExists, Encoding.Unicode.GetString(buffer)); } wait.WaitOne(); } } [Fact] public void WillSendConfirmationForClient() { var acceptance = MockRepository.GenerateStub<IMessageAcceptance>(); using (var reciever = new Receiver(endpointToListenTo, messages => acceptance)) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); var stream = client.GetStream(); var serialize = new Message[0].Serialize(); stream.Write(BitConverter.GetBytes(serialize.Length), 0, 4); stream.Write(serialize, 0, serialize.Length); var buffer = new byte[ProtocolConstants.RecievedBuffer.Length]; stream.Read(buffer, 0, buffer.Length); Assert.Equal(ProtocolConstants.Recieved, Encoding.Unicode.GetString(buffer)); } wait.WaitOne(); } } [Fact] public void WillCallAbortAcceptanceIfSenderDoesNotConfirm() { var acceptance = MockRepository.GenerateStub<IMessageAcceptance>(); using (var reciever = new Receiver(endpointToListenTo, messages => acceptance)) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); var stream = client.GetStream(); var serialize = new Message[0].Serialize(); stream.Write(BitConverter.GetBytes(serialize.Length), 0, 4); stream.Write(serialize, 0, serialize.Length); var buffer = new byte[ProtocolConstants.RecievedBuffer.Length]; stream.Read(buffer, 0, buffer.Length); Assert.Equal(ProtocolConstants.Recieved, Encoding.Unicode.GetString(buffer)); } wait.WaitOne(); } acceptance.AssertWasCalled(x => x.Abort()); } [Fact] public void WillCallAbortAcceptanceIfSenderSendNonConfirmation() { var acceptance = MockRepository.GenerateStub<IMessageAcceptance>(); using (var reciever = new Receiver(endpointToListenTo, messages => acceptance)) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); var stream = client.GetStream(); var serialize = new Message[0].Serialize(); stream.Write(BitConverter.GetBytes(serialize.Length), 0, 4); stream.Write(serialize, 0, serialize.Length); var buffer = new byte[ProtocolConstants.RecievedBuffer.Length]; stream.Read(buffer, 0, buffer.Length); Assert.Equal(ProtocolConstants.Recieved, Encoding.Unicode.GetString(buffer)); var bytes = Encoding.Unicode.GetBytes("Unknowledged"); stream.Write(bytes, 0, bytes.Length); } wait.WaitOne(); } acceptance.AssertWasCalled(x => x.Abort()); } [Fact] public void WillCallCommitAcceptanceIfSenderSendConfirmation() { var acceptance = MockRepository.GenerateStub<IMessageAcceptance>(); using (var reciever = new Receiver(endpointToListenTo, messages => acceptance)) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); var stream = client.GetStream(); var serialize = new Message[0].Serialize(); stream.Write(BitConverter.GetBytes(serialize.Length), 0, 4); stream.Write(serialize, 0, serialize.Length); var buffer = new byte[ProtocolConstants.RecievedBuffer.Length]; stream.Read(buffer, 0, buffer.Length); Assert.Equal(ProtocolConstants.Recieved, Encoding.Unicode.GetString(buffer)); stream.Write(ProtocolConstants.AcknowledgedBuffer, 0, ProtocolConstants.AcknowledgedBuffer.Length); } wait.WaitOne(); } acceptance.AssertWasCalled(x => x.Commit()); } [Fact] public void WillTellSenderIfCommitFailed() { var acceptance = MockRepository.GenerateStub<IMessageAcceptance>(); acceptance.Stub(x => x.Commit()).Throw(new InvalidOperationException()); using (var reciever = new Receiver(endpointToListenTo, messages => acceptance)) { reciever.CompletedRecievingMessages += () => wait.Set(); reciever.Start(); using (var client = new TcpClient()) { client.Connect(endpointToListenTo); var stream = client.GetStream(); var serialize = new Message[0].Serialize(); stream.Write(BitConverter.GetBytes(serialize.Length), 0, 4); stream.Write(serialize, 0, serialize.Length); var buffer = new byte[ProtocolConstants.RecievedBuffer.Length]; stream.Read(buffer, 0, buffer.Length); Assert.Equal(ProtocolConstants.Recieved, Encoding.Unicode.GetString(buffer)); stream.Write(ProtocolConstants.AcknowledgedBuffer, 0, ProtocolConstants.AcknowledgedBuffer.Length); buffer = new byte[ProtocolConstants.RevertBuffer.Length]; stream.Read(buffer, 0, buffer.Length); Assert.Equal(ProtocolConstants.Revert, Encoding.Unicode.GetString(buffer)); } wait.WaitOne(); } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the importexport-2010-06-01.normal.json service model. */ using System; using System.Collections.Generic; using Amazon.ImportExport.Model; namespace Amazon.ImportExport { /// <summary> /// Interface for accessing ImportExport /// /// AWS Import/Export Service AWS Import/Export accelerates transferring large amounts /// of data between the AWS cloud and portable storage devices that you mail to us. AWS /// Import/Export transfers data directly onto and off of your storage devices using Amazon's /// high-speed internal network and bypassing the Internet. For large data sets, AWS Import/Export /// is often faster than Internet transfer and more cost effective than upgrading your /// connectivity. /// </summary> public partial interface IAmazonImportExport : IDisposable { #region CancelJob /// <summary> /// This operation cancels a specified job. Only the job owner can cancel it. The operation /// fails if the job has already started or is complete. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CancelJob service method.</param> /// /// <returns>The response from the CancelJob service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.CanceledJobIdException"> /// The specified job ID has been canceled and is no longer valid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.ExpiredJobIdException"> /// Indicates that the specified job has expired out of the system. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidJobIdException"> /// The JOBID was missing, not found, or not associated with the AWS account. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.UnableToCancelJobIdException"> /// AWS Import/Export cannot cancel the job /// </exception> CancelJobResponse CancelJob(CancelJobRequest request); /// <summary> /// Initiates the asynchronous execution of the CancelJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CancelJob operation on AmazonImportExportClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCancelJob /// operation.</returns> IAsyncResult BeginCancelJob(CancelJobRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CancelJob operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCancelJob.</param> /// /// <returns>Returns a CancelJobResult from ImportExport.</returns> CancelJobResponse EndCancelJob(IAsyncResult asyncResult); #endregion #region CreateJob /// <summary> /// This operation initiates the process of scheduling an upload or download of your data. /// You include in the request a manifest that describes the data transfer specifics. /// The response to the request includes a job ID, which you can use in other operations, /// a signature that you use to identify your storage device, and the address where you /// should ship your storage device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateJob service method.</param> /// /// <returns>The response from the CreateJob service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.BucketPermissionException"> /// The account specified does not have the appropriate bucket permissions. /// </exception> /// <exception cref="Amazon.ImportExport.Model.CreateJobQuotaExceededException"> /// Each account can create only a certain number of jobs per day. If you need to create /// more than this, please contact awsimportexport@amazon.com to explain your particular /// use case. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAddressException"> /// The address specified in the manifest is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidCustomsException"> /// One or more customs parameters was invalid. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidFileSystemException"> /// File system specified in export manifest is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidJobIdException"> /// The JOBID was missing, not found, or not associated with the AWS account. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidManifestFieldException"> /// One or more manifest fields was invalid. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MalformedManifestException"> /// Your manifest is not well-formed. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingCustomsException"> /// One or more required customs parameters was missing from the manifest. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingManifestFieldException"> /// One or more required fields were missing from the manifest file. Please correct and /// resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingParameterException"> /// One or more required parameters was missing from the request. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MultipleRegionsException"> /// Your manifest file contained buckets from multiple regions. A job is restricted to /// buckets from one region. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.NoSuchBucketException"> /// The specified bucket does not exist. Create the specified bucket or change the manifest's /// bucket, exportBucket, or logBucket field to a bucket that the account, as specified /// by the manifest's Access Key ID, has write permissions to. /// </exception> CreateJobResponse CreateJob(CreateJobRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateJob operation on AmazonImportExportClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateJob /// operation.</returns> IAsyncResult BeginCreateJob(CreateJobRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreateJob operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateJob.</param> /// /// <returns>Returns a CreateJobResult from ImportExport.</returns> CreateJobResponse EndCreateJob(IAsyncResult asyncResult); #endregion #region GetShippingLabel /// <summary> /// This operation returns information about a job, including where the job is in the /// processing pipeline, the status of the results, and the signature value associated /// with the job. You can only return information about jobs you own. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetShippingLabel service method.</param> /// /// <returns>The response from the GetShippingLabel service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.CanceledJobIdException"> /// The specified job ID has been canceled and is no longer valid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.ExpiredJobIdException"> /// Indicates that the specified job has expired out of the system. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAddressException"> /// The address specified in the manifest is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidJobIdException"> /// The JOBID was missing, not found, or not associated with the AWS account. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> GetShippingLabelResponse GetShippingLabel(GetShippingLabelRequest request); /// <summary> /// Initiates the asynchronous execution of the GetShippingLabel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetShippingLabel operation on AmazonImportExportClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetShippingLabel /// operation.</returns> IAsyncResult BeginGetShippingLabel(GetShippingLabelRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetShippingLabel operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetShippingLabel.</param> /// /// <returns>Returns a GetShippingLabelResult from ImportExport.</returns> GetShippingLabelResponse EndGetShippingLabel(IAsyncResult asyncResult); #endregion #region GetStatus /// <summary> /// This operation returns information about a job, including where the job is in the /// processing pipeline, the status of the results, and the signature value associated /// with the job. You can only return information about jobs you own. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetStatus service method.</param> /// /// <returns>The response from the GetStatus service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.CanceledJobIdException"> /// The specified job ID has been canceled and is no longer valid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.ExpiredJobIdException"> /// Indicates that the specified job has expired out of the system. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidJobIdException"> /// The JOBID was missing, not found, or not associated with the AWS account. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> GetStatusResponse GetStatus(GetStatusRequest request); /// <summary> /// Initiates the asynchronous execution of the GetStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetStatus operation on AmazonImportExportClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetStatus /// operation.</returns> IAsyncResult BeginGetStatus(GetStatusRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetStatus operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetStatus.</param> /// /// <returns>Returns a GetStatusResult from ImportExport.</returns> GetStatusResponse EndGetStatus(IAsyncResult asyncResult); #endregion #region ListJobs /// <summary> /// This operation returns the jobs associated with the requester. AWS Import/Export lists /// the jobs in reverse chronological order based on the date of creation. For example /// if Job Test1 was created 2009Dec30 and Test2 was created 2010Feb05, the ListJobs operation /// would return Test2 followed by Test1. /// </summary> /// /// <returns>The response from the ListJobs service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> ListJobsResponse ListJobs(); /// <summary> /// This operation returns the jobs associated with the requester. AWS Import/Export lists /// the jobs in reverse chronological order based on the date of creation. For example /// if Job Test1 was created 2009Dec30 and Test2 was created 2010Feb05, the ListJobs operation /// would return Test2 followed by Test1. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListJobs service method.</param> /// /// <returns>The response from the ListJobs service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> ListJobsResponse ListJobs(ListJobsRequest request); /// <summary> /// Initiates the asynchronous execution of the ListJobs operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListJobs operation on AmazonImportExportClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListJobs /// operation.</returns> IAsyncResult BeginListJobs(ListJobsRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListJobs operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListJobs.</param> /// /// <returns>Returns a ListJobsResult from ImportExport.</returns> ListJobsResponse EndListJobs(IAsyncResult asyncResult); #endregion #region UpdateJob /// <summary> /// You use this operation to change the parameters specified in the original manifest /// file by supplying a new manifest file. The manifest file attached to this request /// replaces the original manifest file. You can only use the operation after a CreateJob /// request but before the data transfer starts and you can only use it on jobs you own. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateJob service method.</param> /// /// <returns>The response from the UpdateJob service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.BucketPermissionException"> /// The account specified does not have the appropriate bucket permissions. /// </exception> /// <exception cref="Amazon.ImportExport.Model.CanceledJobIdException"> /// The specified job ID has been canceled and is no longer valid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.ExpiredJobIdException"> /// Indicates that the specified job has expired out of the system. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAddressException"> /// The address specified in the manifest is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidCustomsException"> /// One or more customs parameters was invalid. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidFileSystemException"> /// File system specified in export manifest is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidJobIdException"> /// The JOBID was missing, not found, or not associated with the AWS account. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidManifestFieldException"> /// One or more manifest fields was invalid. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MalformedManifestException"> /// Your manifest is not well-formed. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingCustomsException"> /// One or more required customs parameters was missing from the manifest. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingManifestFieldException"> /// One or more required fields were missing from the manifest file. Please correct and /// resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingParameterException"> /// One or more required parameters was missing from the request. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MultipleRegionsException"> /// Your manifest file contained buckets from multiple regions. A job is restricted to /// buckets from one region. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.NoSuchBucketException"> /// The specified bucket does not exist. Create the specified bucket or change the manifest's /// bucket, exportBucket, or logBucket field to a bucket that the account, as specified /// by the manifest's Access Key ID, has write permissions to. /// </exception> /// <exception cref="Amazon.ImportExport.Model.UnableToUpdateJobIdException"> /// AWS Import/Export cannot update the job /// </exception> UpdateJobResponse UpdateJob(UpdateJobRequest request); /// <summary> /// Initiates the asynchronous execution of the UpdateJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateJob operation on AmazonImportExportClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateJob /// operation.</returns> IAsyncResult BeginUpdateJob(UpdateJobRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the UpdateJob operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateJob.</param> /// /// <returns>Returns a UpdateJobResult from ImportExport.</returns> UpdateJobResponse EndUpdateJob(IAsyncResult asyncResult); #endregion } }
using System; using System.Collections.Generic; namespace NAudio.Wave { /// <summary> /// WaveStream that can mix together multiple 32 bit input streams /// (Normally used with stereo input channels) /// All channels must have the same number of inputs /// </summary> public class WaveMixerStream32 : WaveStream { private readonly List<WaveStream> inputStreams; private readonly object inputsLock; private WaveFormat waveFormat; private long length; private long position; private readonly int bytesPerSample; /// <summary> /// Creates a new 32 bit WaveMixerStream /// </summary> public WaveMixerStream32() { AutoStop = true; waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2); bytesPerSample = 4; inputStreams = new List<WaveStream>(); inputsLock = new object(); } /// <summary> /// Creates a new 32 bit WaveMixerStream /// </summary> /// <param name="inputStreams">An Array of WaveStreams - must all have the same format. /// Use WaveChannel is designed for this purpose.</param> /// <param name="autoStop">Automatically stop when all inputs have been read</param> /// <exception cref="ArgumentException">Thrown if the input streams are not 32 bit floating point, /// or if they have different formats to each other</exception> public WaveMixerStream32(IEnumerable<WaveStream> inputStreams, bool autoStop) : this() { AutoStop = autoStop; foreach (var inputStream in inputStreams) { AddInputStream(inputStream); } } /// <summary> /// Add a new input to the mixer /// </summary> /// <param name="waveStream">The wave input to add</param> public void AddInputStream(WaveStream waveStream) { if (waveStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat) throw new ArgumentException("Must be IEEE floating point", "waveStream"); if (waveStream.WaveFormat.BitsPerSample != 32) throw new ArgumentException("Only 32 bit audio currently supported", "waveStream"); if (inputStreams.Count == 0) { // first one - set the format int sampleRate = waveStream.WaveFormat.SampleRate; int channels = waveStream.WaveFormat.Channels; this.waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channels); } else { if (!waveStream.WaveFormat.Equals(waveFormat)) throw new ArgumentException("All incoming channels must have the same format", "waveStream"); } lock (inputsLock) { this.inputStreams.Add(waveStream); this.length = Math.Max(this.length, waveStream.Length); // get to the right point in this input file waveStream.Position = Position; } } /// <summary> /// Remove a WaveStream from the mixer /// </summary> /// <param name="waveStream">waveStream to remove</param> public void RemoveInputStream(WaveStream waveStream) { lock (inputsLock) { if (inputStreams.Remove(waveStream)) { // recalculate the length long newLength = 0; foreach (var inputStream in inputStreams) { newLength = Math.Max(newLength, inputStream.Length); } length = newLength; } } } /// <summary> /// The number of inputs to this mixer /// </summary> public int InputCount { get { return inputStreams.Count; } } /// <summary> /// Automatically stop when all inputs have been read /// </summary> public bool AutoStop { get; set; } /// <summary> /// Reads bytes from this wave stream /// </summary> /// <param name="buffer">buffer to read into</param> /// <param name="offset">offset into buffer</param> /// <param name="count">number of bytes required</param> /// <returns>Number of bytes read.</returns> /// <exception cref="ArgumentException">Thrown if an invalid number of bytes requested</exception> public override int Read(byte[] buffer, int offset, int count) { if (AutoStop) { if (position + count > length) count = (int)(length - position); // was a bug here, should be fixed now System.Diagnostics.Debug.Assert(count >= 0, "length and position mismatch"); } if (count % bytesPerSample != 0) throw new ArgumentException("Must read an whole number of samples", "count"); // blank the buffer Array.Clear(buffer, offset, count); int bytesRead = 0; // sum the channels in var readBuffer = new byte[count]; lock (inputsLock) { foreach (var inputStream in inputStreams) { if (inputStream.HasData(count)) { int readFromThisStream = inputStream.Read(readBuffer, 0, count); // don't worry if input stream returns less than we requested - may indicate we have got to the end bytesRead = Math.Max(bytesRead, readFromThisStream); if (readFromThisStream > 0) Sum32BitAudio(buffer, offset, readBuffer, readFromThisStream); } else { bytesRead = Math.Max(bytesRead, count); inputStream.Position += count; } } } position += count; return count; } /// <summary> /// Actually performs the mixing /// </summary> static unsafe void Sum32BitAudio(byte[] destBuffer, int offset, byte[] sourceBuffer, int bytesRead) { fixed (byte* pDestBuffer = &destBuffer[offset], pSourceBuffer = &sourceBuffer[0]) { float* pfDestBuffer = (float*)pDestBuffer; float* pfReadBuffer = (float*)pSourceBuffer; int samplesRead = bytesRead / 4; for (int n = 0; n < samplesRead; n++) { pfDestBuffer[n] += pfReadBuffer[n]; } } } /// <summary> /// <see cref="WaveStream.BlockAlign"/> /// </summary> public override int BlockAlign { get { return waveFormat.BlockAlign; // inputStreams[0].BlockAlign; } } /// <summary> /// Length of this Wave Stream (in bytes) /// <see cref="System.IO.Stream.Length"/> /// </summary> public override long Length { get { return length; } } /// <summary> /// Position within this Wave Stream (in bytes) /// <see cref="System.IO.Stream.Position"/> /// </summary> public override long Position { get { // all streams are at the same position return position; } set { lock (inputsLock) { value = Math.Min(value, Length); foreach (WaveStream inputStream in inputStreams) { inputStream.Position = Math.Min(value, inputStream.Length); } this.position = value; } } } /// <summary> /// <see cref="WaveStream.WaveFormat"/> /// </summary> public override WaveFormat WaveFormat { get { return waveFormat; } } /// <summary> /// Disposes this WaveStream /// </summary> protected override void Dispose(bool disposing) { if (disposing) { lock (inputsLock) { foreach (WaveStream inputStream in inputStreams) { inputStream.Dispose(); } } } else { System.Diagnostics.Debug.Assert(false, "WaveMixerStream32 was not disposed"); } base.Dispose(disposing); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading.Tasks; namespace System.Net.Sockets { public static class SocketTaskExtensions { public static Task<Socket> AcceptAsync(this Socket socket) { return Task<Socket>.Factory.FromAsync( (callback, state) => ((Socket)state).BeginAccept(callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndAccept(asyncResult), state: socket); } public static Task<Socket> AcceptAsync(this Socket socket, Socket acceptSocket) { const int ReceiveSize = 0; return Task<Socket>.Factory.FromAsync( (socketForAccept, receiveSize, callback, state) => ((Socket)state).BeginAccept(socketForAccept, receiveSize, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndAccept(asyncResult), acceptSocket, ReceiveSize, state: socket); } public static Task ConnectAsync(this Socket socket, EndPoint remoteEndPoint) { return Task.Factory.FromAsync( (targetEndPoint, callback, state) => ((Socket)state).BeginConnect(targetEndPoint, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndConnect(asyncResult), remoteEndPoint, state: socket); } public static Task ConnectAsync(this Socket socket, IPAddress address, int port) { return Task.Factory.FromAsync( (targetAddress, targetPort, callback, state) => ((Socket)state).BeginConnect(targetAddress, targetPort, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndConnect(asyncResult), address, port, state: socket); } public static Task ConnectAsync(this Socket socket, IPAddress[] addresses, int port) { return Task.Factory.FromAsync( (targetAddresses, targetPort, callback, state) => ((Socket)state).BeginConnect(targetAddresses, targetPort, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndConnect(asyncResult), addresses, port, state: socket); } public static Task ConnectAsync(this Socket socket, string host, int port) { return Task.Factory.FromAsync( (targetHost, targetPort, callback, state) => ((Socket)state).BeginConnect(targetHost, targetPort, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndConnect(asyncResult), host, port, state: socket); } public static Task<int> ReceiveAsync(this Socket socket, ArraySegment<byte> buffer, SocketFlags socketFlags) { return Task<int>.Factory.FromAsync( (targetBuffer, flags, callback, state) => ((Socket)state).BeginReceive( targetBuffer.Array, targetBuffer.Offset, targetBuffer.Count, flags, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndReceive(asyncResult), buffer, socketFlags, state: socket); } public static Task<int> ReceiveAsync( this Socket socket, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags) { return Task<int>.Factory.FromAsync( (targetBuffers, flags, callback, state) => ((Socket)state).BeginReceive(targetBuffers, flags, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndReceive(asyncResult), buffers, socketFlags, state: socket); } public static Task<SocketReceiveFromResult> ReceiveFromAsync( this Socket socket, ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint) { object[] packedArguments = new object[] { socket, remoteEndPoint }; return Task<SocketReceiveFromResult>.Factory.FromAsync( (targetBuffer, flags, callback, state) => { var arguments = (object[])state; var s = (Socket)arguments[0]; var e = (EndPoint)arguments[1]; IAsyncResult result = s.BeginReceiveFrom( targetBuffer.Array, targetBuffer.Offset, targetBuffer.Count, flags, ref e, callback, state); arguments[1] = e; return result; }, asyncResult => { var arguments = (object[])asyncResult.AsyncState; var s = (Socket)arguments[0]; var e = (EndPoint)arguments[1]; int bytesReceived = s.EndReceiveFrom(asyncResult, ref e); return new SocketReceiveFromResult() { ReceivedBytes = bytesReceived, RemoteEndPoint = e }; }, buffer, socketFlags, state: packedArguments); } public static Task<SocketReceiveMessageFromResult> ReceiveMessageFromAsync( this Socket socket, ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint) { object[] packedArguments = new object[] { socket, socketFlags, remoteEndPoint }; return Task<SocketReceiveMessageFromResult>.Factory.FromAsync( (targetBuffer, callback, state) => { var arguments = (object[])state; var s = (Socket)arguments[0]; var f = (SocketFlags)arguments[1]; var e = (EndPoint)arguments[2]; IAsyncResult result = s.BeginReceiveMessageFrom( targetBuffer.Array, targetBuffer.Offset, targetBuffer.Count, f, ref e, callback, state); arguments[2] = e; return result; }, asyncResult => { var arguments = (object[])asyncResult.AsyncState; var s = (Socket)arguments[0]; var f = (SocketFlags)arguments[1]; var e = (EndPoint)arguments[2]; IPPacketInformation ipPacket; int bytesReceived = s.EndReceiveMessageFrom( asyncResult, ref f, ref e, out ipPacket); return new SocketReceiveMessageFromResult() { PacketInformation = ipPacket, ReceivedBytes = bytesReceived, RemoteEndPoint = e, SocketFlags = f }; }, buffer, state: packedArguments); } public static Task<int> SendAsync(this Socket socket, ArraySegment<byte> buffer, SocketFlags socketFlags) { return Task<int>.Factory.FromAsync( (targetBuffer, flags, callback, state) => ((Socket)state).BeginSend( targetBuffer.Array, targetBuffer.Offset, targetBuffer.Count, flags, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndSend(asyncResult), buffer, socketFlags, state: socket); } public static Task<int> SendAsync( this Socket socket, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags) { return Task<int>.Factory.FromAsync( (targetBuffers, flags, callback, state) => ((Socket)state).BeginSend(targetBuffers, flags, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndSend(asyncResult), buffers, socketFlags, state: socket); } public static Task<int> SendToAsync( this Socket socket, ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint) { return Task<int>.Factory.FromAsync( (targetBuffer, flags, endPoint, callback, state) => ((Socket)state).BeginSendTo( targetBuffer.Array, targetBuffer.Offset, targetBuffer.Count, flags, endPoint, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndSendTo(asyncResult), buffer, socketFlags, remoteEndPoint, state: socket); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Text; namespace System { /* Customized format patterns: P.S. Format in the table below is the internal number format used to display the pattern. Patterns Format Description Example ========= ========== ===================================== ======== "h" "0" hour (12-hour clock)w/o leading zero 3 "hh" "00" hour (12-hour clock)with leading zero 03 "hh*" "00" hour (12-hour clock)with leading zero 03 "H" "0" hour (24-hour clock)w/o leading zero 8 "HH" "00" hour (24-hour clock)with leading zero 08 "HH*" "00" hour (24-hour clock) 08 "m" "0" minute w/o leading zero "mm" "00" minute with leading zero "mm*" "00" minute with leading zero "s" "0" second w/o leading zero "ss" "00" second with leading zero "ss*" "00" second with leading zero "f" "0" second fraction (1 digit) "ff" "00" second fraction (2 digit) "fff" "000" second fraction (3 digit) "ffff" "0000" second fraction (4 digit) "fffff" "00000" second fraction (5 digit) "ffffff" "000000" second fraction (6 digit) "fffffff" "0000000" second fraction (7 digit) "F" "0" second fraction (up to 1 digit) "FF" "00" second fraction (up to 2 digit) "FFF" "000" second fraction (up to 3 digit) "FFFF" "0000" second fraction (up to 4 digit) "FFFFF" "00000" second fraction (up to 5 digit) "FFFFFF" "000000" second fraction (up to 6 digit) "FFFFFFF" "0000000" second fraction (up to 7 digit) "t" first character of AM/PM designator A "tt" AM/PM designator AM "tt*" AM/PM designator PM "d" "0" day w/o leading zero 1 "dd" "00" day with leading zero 01 "ddd" short weekday name (abbreviation) Mon "dddd" full weekday name Monday "dddd*" full weekday name Monday "M" "0" month w/o leading zero 2 "MM" "00" month with leading zero 02 "MMM" short month name (abbreviation) Feb "MMMM" full month name Febuary "MMMM*" full month name Febuary "y" "0" two digit year (year % 100) w/o leading zero 0 "yy" "00" two digit year (year % 100) with leading zero 00 "yyy" "D3" year 2000 "yyyy" "D4" year 2000 "yyyyy" "D5" year 2000 ... "z" "+0;-0" timezone offset w/o leading zero -8 "zz" "+00;-00" timezone offset with leading zero -08 "zzz" "+00;-00" for hour offset, "00" for minute offset full timezone offset -07:30 "zzz*" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00 "K" -Local "zzz", e.g. -08:00 -Utc "'Z'", representing UTC -Unspecified "" -DateTimeOffset "zzzzz" e.g -07:30:15 "g*" the current era name A.D. ":" time separator : -- DEPRECATED - Insert separator directly into pattern (eg: "H.mm.ss") "/" date separator /-- DEPRECATED - Insert separator directly into pattern (eg: "M-dd-yyyy") "'" quoted string 'ABC' will insert ABC into the formatted string. '"' quoted string "ABC" will insert ABC into the formatted string. "%" used to quote a single pattern characters E.g.The format character "%y" is to print two digit year. "\" escaped character E.g. '\d' insert the character 'd' into the format string. other characters insert the character into the format string. Pre-defined format characters: (U) to indicate Universal time is used. (G) to indicate Gregorian calendar is used. Format Description Real format Example ========= ================================= ====================== ======================= "d" short date culture-specific 10/31/1999 "D" long data culture-specific Sunday, October 31, 1999 "f" full date (long date + short time) culture-specific Sunday, October 31, 1999 2:00 AM "F" full date (long date + long time) culture-specific Sunday, October 31, 1999 2:00:00 AM "g" general date (short date + short time) culture-specific 10/31/1999 2:00 AM "G" general date (short date + long time) culture-specific 10/31/1999 2:00:00 AM "m"/"M" Month/Day date culture-specific October 31 (G) "o"/"O" Round Trip XML "yyyy-MM-ddTHH:mm:ss.fffffffK" 1999-10-31 02:00:00.0000000Z (G) "r"/"R" RFC 1123 date, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" Sun, 31 Oct 1999 10:00:00 GMT (G) "s" Sortable format, based on ISO 8601. "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00 ('T' for local time) "t" short time culture-specific 2:00 AM "T" long time culture-specific 2:00:00 AM (G) "u" Universal time with sortable format, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 1999-10-31 10:00:00Z based on ISO 8601. (U) "U" Universal time with full culture-specific Sunday, October 31, 1999 10:00:00 AM (long date + long time) format "y"/"Y" Year/Month day culture-specific October, 1999 */ //This class contains only static members and does not require the serializable attribute. internal static class DateTimeFormat { internal const int MaxSecondsFractionDigits = 7; internal static readonly TimeSpan NullOffset = TimeSpan.MinValue; internal static char[] allStandardFormats = { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'o', 'O', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y', }; internal const String RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; internal const String RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz"; private const int DEFAULT_ALL_DATETIMES_SIZE = 132; internal static readonly DateTimeFormatInfo InvariantFormatInfo = CultureInfo.InvariantCulture.DateTimeFormat; internal static readonly string[] InvariantAbbreviatedMonthNames = InvariantFormatInfo.AbbreviatedMonthNames; internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames; internal const string Gmt = "GMT"; internal static String[] fixedNumberFormats = new String[] { "0", "00", "000", "0000", "00000", "000000", "0000000", }; //////////////////////////////////////////////////////////////////////////// // // Format the positive integer value to a string and perfix with assigned // length of leading zero. // // Parameters: // value: The value to format // len: The maximum length for leading zero. // If the digits of the value is greater than len, no leading zero is added. // // Notes: // The function can format to Int32.MaxValue. // //////////////////////////////////////////////////////////////////////////// internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) { Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); FormatDigits(outputBuffer, value, len, false); } internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) { Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); // Limit the use of this function to be two-digits, so that we have the same behavior // as RTM bits. if (!overrideLengthLimit && len > 2) { len = 2; } char* buffer = stackalloc char[16]; char* p = buffer + 16; int n = value; do { *--p = (char)(n % 10 + '0'); n /= 10; } while ((n != 0) && (p > buffer)); int digits = (int)(buffer + 16 - p); //If the repeat count is greater than 0, we're trying //to emulate the "00" format, so we have to prepend //a zero if the string only has one character. while ((digits < len) && (p > buffer)) { *--p = '0'; digits++; } outputBuffer.Append(p, digits); } private static void HebrewFormatDigits(StringBuilder outputBuffer, int digits) { outputBuffer.Append(HebrewNumber.ToString(digits)); } internal static int ParseRepeatPattern(String format, int pos, char patternChar) { int len = format.Length; int index = pos + 1; while ((index < len) && (format[index] == patternChar)) { index++; } return (index - pos); } private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi) { Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6"); if (repeat == 3) { return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek)); } // Call dtfi.GetDayName() here, instead of accessing DayNames property, because we don't // want a clone of DayNames, which will hurt perf. return (dtfi.GetDayName((DayOfWeek)dayOfWeek)); } private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) { Debug.Assert(month >= 1 && month <= 12, "month >=1 && month <= 12"); if (repeatCount == 3) { return (dtfi.GetAbbreviatedMonthName(month)); } // Call GetMonthName() here, instead of accessing MonthNames property, because we don't // want a clone of MonthNames, which will hurt perf. return (dtfi.GetMonthName(month)); } // // FormatHebrewMonthName // // Action: Return the Hebrew month name for the specified DateTime. // Returns: The month name string for the specified DateTime. // Arguments: // time the time to format // month The month is the value of HebrewCalendar.GetMonth(time). // repeat Return abbreviated month name if repeat=3, or full month name if repeat=4 // dtfi The DateTimeFormatInfo which uses the Hebrew calendars as its calendar. // Exceptions: None. // /* Note: If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this: 1 Hebrew 1st Month 2 Hebrew 2nd Month .. ... 6 Hebrew 6th Month 7 Hebrew 6th Month II (used only in a leap year) 8 Hebrew 7th Month 9 Hebrew 8th Month 10 Hebrew 9th Month 11 Hebrew 10th Month 12 Hebrew 11th Month 13 Hebrew 12th Month Therefore, if we are in a regular year, we have to increment the month name if moth is greater or eqaul to 7. */ private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4"); if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) { // This month is in a leap year return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3))); } // This is in a regular year. if (month >= 7) { month++; } if (repeatCount == 3) { return (dtfi.GetAbbreviatedMonthName(month)); } return (dtfi.GetMonthName(month)); } // // The pos should point to a quote character. This method will // append to the result StringBuilder the string encloed by the quote character. // internal static int ParseQuoteString(String format, int pos, StringBuilder result) { // // NOTE : pos will be the index of the quote character in the 'format' string. // int formatLen = format.Length; int beginPos = pos; char quoteChar = format[pos++]; // Get the character used to quote the following string. bool foundQuote = false; while (pos < formatLen) { char ch = format[pos++]; if (ch == quoteChar) { foundQuote = true; break; } else if (ch == '\\') { // The following are used to support escaped character. // Escaped character is also supported in the quoted string. // Therefore, someone can use a format like "'minute:' mm\"" to display: // minute: 45" // because the second double quote is escaped. if (pos < formatLen) { result.Append(format[pos++]); } else { // // This means that '\' is at the end of the formatting string. // throw new FormatException(SR.Format_InvalidString); } } else { result.Append(ch); } } if (!foundQuote) { // Here we can't find the matching quote. throw new FormatException( String.Format( CultureInfo.CurrentCulture, SR.Format_BadQuote, quoteChar)); } // // Return the character count including the begin/end quote characters and enclosed string. // return (pos - beginPos); } // // Get the next character at the index of 'pos' in the 'format' string. // Return value of -1 means 'pos' is already at the end of the 'format' string. // Otherwise, return value is the int value of the next character. // internal static int ParseNextChar(String format, int pos) { if (pos >= format.Length - 1) { return (-1); } return ((int)format[pos + 1]); } // // IsUseGenitiveForm // // Actions: Check the format to see if we should use genitive month in the formatting. // Starting at the position (index) in the (format) string, look back and look ahead to // see if there is "d" or "dd". In the case like "d MMMM" or "MMMM dd", we can use // genitive form. Genitive form is not used if there is more than two "d". // Arguments: // format The format string to be scanned. // index Where we should start the scanning. This is generally where "M" starts. // tokenLen The len of the current pattern character. This indicates how many "M" that we have. // patternToMatch The pattern that we want to search. This generally uses "d" // private static bool IsUseGenitiveForm(String format, int index, int tokenLen, char patternToMatch) { int i; int repeat = 0; // // Look back to see if we can find "d" or "ddd" // // Find first "d". for (i = index - 1; i >= 0 && format[i] != patternToMatch; i--) { /*Do nothing here */ }; if (i >= 0) { // Find a "d", so look back to see how many "d" that we can find. while (--i >= 0 && format[i] == patternToMatch) { repeat++; } // // repeat == 0 means that we have one (patternToMatch) // repeat == 1 means that we have two (patternToMatch) // if (repeat <= 1) { return (true); } // Note that we can't just stop here. We may find "ddd" while looking back, and we have to look // ahead to see if there is "d" or "dd". } // // If we can't find "d" or "dd" by looking back, try look ahead. // // Find first "d" for (i = index + tokenLen; i < format.Length && format[i] != patternToMatch; i++) { /* Do nothing here */ }; if (i < format.Length) { repeat = 0; // Find a "d", so contine the walk to see how may "d" that we can find. while (++i < format.Length && format[i] == patternToMatch) { repeat++; } // // repeat == 0 means that we have one (patternToMatch) // repeat == 1 means that we have two (patternToMatch) // if (repeat <= 1) { return (true); } } return (false); } // // FormatCustomized // // Actions: Format the DateTime instance using the specified format. // private static String FormatCustomized(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset) { Calendar cal = dtfi.Calendar; StringBuilder result = StringBuilderCache.Acquire(); // This is a flag to indicate if we are format the dates using Hebrew calendar. bool isHebrewCalendar = (cal.ID == CalendarId.HEBREW); // This is a flag to indicate if we are formating hour/minute/second only. bool bTimeOnly = true; int i = 0; int tokenLen, hour12; while (i < format.Length) { char ch = format[i]; int nextChar; switch (ch) { case 'g': tokenLen = ParseRepeatPattern(format, i, ch); result.Append(dtfi.GetEraName(cal.GetEra(dateTime))); break; case 'h': tokenLen = ParseRepeatPattern(format, i, ch); hour12 = dateTime.Hour % 12; if (hour12 == 0) { hour12 = 12; } FormatDigits(result, hour12, tokenLen); break; case 'H': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Hour, tokenLen); break; case 'm': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Minute, tokenLen); break; case 's': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Second, tokenLen); break; case 'f': case 'F': tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen <= MaxSecondsFractionDigits) { long fraction = (dateTime.Ticks % Calendar.TicksPerSecond); fraction = fraction / (long)Math.Pow(10, 7 - tokenLen); if (ch == 'f') { result.Append(((int)fraction).ToString(fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture)); } else { int effectiveDigits = tokenLen; while (effectiveDigits > 0) { if (fraction % 10 == 0) { fraction = fraction / 10; effectiveDigits--; } else { break; } } if (effectiveDigits > 0) { result.Append(((int)fraction).ToString(fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture)); } else { // No fraction to emit, so see if we should remove decimal also. if (result.Length > 0 && result[result.Length - 1] == '.') { result.Remove(result.Length - 1, 1); } } } } else { throw new FormatException(SR.Format_InvalidString); } break; case 't': tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen == 1) { if (dateTime.Hour < 12) { if (dtfi.AMDesignator.Length >= 1) { result.Append(dtfi.AMDesignator[0]); } } else { if (dtfi.PMDesignator.Length >= 1) { result.Append(dtfi.PMDesignator[0]); } } } else { result.Append((dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator)); } break; case 'd': // // tokenLen == 1 : Day of month as digits with no leading zero. // tokenLen == 2 : Day of month as digits with leading zero for single-digit months. // tokenLen == 3 : Day of week as a three-leter abbreviation. // tokenLen >= 4 : Day of week as its full name. // tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen <= 2) { int day = cal.GetDayOfMonth(dateTime); if (isHebrewCalendar) { // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. HebrewFormatDigits(result, day); } else { FormatDigits(result, day, tokenLen); } } else { int dayOfWeek = (int)cal.GetDayOfWeek(dateTime); result.Append(FormatDayOfWeek(dayOfWeek, tokenLen, dtfi)); } bTimeOnly = false; break; case 'M': // // tokenLen == 1 : Month as digits with no leading zero. // tokenLen == 2 : Month as digits with leading zero for single-digit months. // tokenLen == 3 : Month as a three-letter abbreviation. // tokenLen >= 4 : Month as its full name. // tokenLen = ParseRepeatPattern(format, i, ch); int month = cal.GetMonth(dateTime); if (tokenLen <= 2) { if (isHebrewCalendar) { // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. HebrewFormatDigits(result, month); } else { FormatDigits(result, month, tokenLen); } } else { if (isHebrewCalendar) { result.Append(FormatHebrewMonthName(dateTime, month, tokenLen, dtfi)); } else { if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4) { result.Append( dtfi.internalGetMonthName( month, IsUseGenitiveForm(format, i, tokenLen, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular, false)); } else { result.Append(FormatMonth(month, tokenLen, dtfi)); } } } bTimeOnly = false; break; case 'y': // Notes about OS behavior: // y: Always print (year % 100). No leading zero. // yy: Always print (year % 100) with leading zero. // yyy/yyyy/yyyyy/... : Print year value. No leading zero. int year = cal.GetYear(dateTime); tokenLen = ParseRepeatPattern(format, i, ch); if (dtfi.HasForceTwoDigitYears) { FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2); } else if (cal.ID == CalendarId.HEBREW) { HebrewFormatDigits(result, year); } else { if (tokenLen <= 2) { FormatDigits(result, year % 100, tokenLen); } else { String fmtPattern = "D" + tokenLen.ToString(); result.Append(year.ToString(fmtPattern, CultureInfo.InvariantCulture)); } } bTimeOnly = false; break; case 'z': tokenLen = ParseRepeatPattern(format, i, ch); FormatCustomizedTimeZone(dateTime, offset, format, tokenLen, bTimeOnly, result); break; case 'K': tokenLen = 1; FormatCustomizedRoundripTimeZone(dateTime, offset, result); break; case ':': result.Append(dtfi.TimeSeparator); tokenLen = 1; break; case '/': result.Append(dtfi.DateSeparator); tokenLen = 1; break; case '\'': case '\"': tokenLen = ParseQuoteString(format, i, result); break; case '%': // Optional format character. // For example, format string "%d" will print day of month // without leading zero. Most of the cases, "%" can be ignored. nextChar = ParseNextChar(format, i); // nextChar will be -1 if we already reach the end of the format string. // Besides, we will not allow "%%" appear in the pattern. if (nextChar >= 0 && nextChar != (int)'%') { result.Append(FormatCustomized(dateTime, ((char)nextChar).ToString(), dtfi, offset)); tokenLen = 2; } else { // // This means that '%' is at the end of the format string or // "%%" appears in the format string. // throw new FormatException(SR.Format_InvalidString); } break; case '\\': // Escaped character. Can be used to insert character into the format string. // For exmple, "\d" will insert the character 'd' into the string. // // NOTENOTE : we can remove this format character if we enforce the enforced quote // character rule. // That is, we ask everyone to use single quote or double quote to insert characters, // then we can remove this character. // nextChar = ParseNextChar(format, i); if (nextChar >= 0) { result.Append(((char)nextChar)); tokenLen = 2; } else { // // This means that '\' is at the end of the formatting string. // throw new FormatException(SR.Format_InvalidString); } break; default: // NOTENOTE : we can remove this rule if we enforce the enforced quote // character rule. // That is, if we ask everyone to use single quote or double quote to insert characters, // then we can remove this default block. result.Append(ch); tokenLen = 1; break; } i += tokenLen; } return StringBuilderCache.GetStringAndRelease(result); } // output the 'z' famliy of formats, which output a the offset from UTC, e.g. "-07:30" private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, String format, Int32 tokenLen, Boolean timeOnly, StringBuilder result) { // See if the instance already has an offset Boolean dateTimeFormat = (offset == NullOffset); if (dateTimeFormat) { // No offset. The instance is a DateTime and the output should be the local time zone if (timeOnly && dateTime.Ticks < Calendar.TicksPerDay) { // For time only format and a time only input, the time offset on 0001/01/01 is less // accurate than the system's current offset because of daylight saving time. offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else if (dateTime.Kind == DateTimeKind.Utc) { offset = TimeSpan.Zero; } else { offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } } if (offset >= TimeSpan.Zero) { result.Append('+'); } else { result.Append('-'); // get a positive offset, so that you don't need a separate code path for the negative numbers. offset = offset.Negate(); } if (tokenLen <= 1) { // 'z' format e.g "-7" result.AppendFormat(CultureInfo.InvariantCulture, "{0:0}", offset.Hours); } else { // 'zz' or longer format e.g "-07" result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}", offset.Hours); if (tokenLen >= 3) { // 'zzz*' or longer format e.g "-07:30" result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes); } } } // output the 'K' format, which is for round-tripping the data private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result) { // The objective of this format is to round trip the data in the type // For DateTime it should round-trip the Kind value and preserve the time zone. // DateTimeOffset instance, it should do so by using the internal time zone. if (offset == NullOffset) { // source is a date time, so behavior depends on the kind. switch (dateTime.Kind) { case DateTimeKind.Local: // This should output the local offset, e.g. "-07:30" offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); // fall through to shared time zone output code break; case DateTimeKind.Utc: // The 'Z' constant is a marker for a UTC date result.Append("Z"); return; default: // If the kind is unspecified, we output nothing here return; } } if (offset >= TimeSpan.Zero) { result.Append('+'); } else { result.Append('-'); // get a positive offset, so that you don't need a separate code path for the negative numbers. offset = offset.Negate(); } AppendNumber(result, offset.Hours, 2); result.Append(':'); AppendNumber(result, offset.Minutes, 2); } internal static String GetRealFormat(String format, DateTimeFormatInfo dtfi) { String realFormat = null; switch (format[0]) { case 'd': // Short Date realFormat = dtfi.ShortDatePattern; break; case 'D': // Long Date realFormat = dtfi.LongDatePattern; break; case 'f': // Full (long date + short time) realFormat = dtfi.LongDatePattern + " " + dtfi.ShortTimePattern; break; case 'F': // Full (long date + long time) realFormat = dtfi.FullDateTimePattern; break; case 'g': // General (short date + short time) realFormat = dtfi.GeneralShortTimePattern; break; case 'G': // General (short date + long time) realFormat = dtfi.GeneralLongTimePattern; break; case 'm': case 'M': // Month/Day Date realFormat = dtfi.MonthDayPattern; break; case 'o': case 'O': realFormat = RoundtripFormat; break; case 'r': case 'R': // RFC 1123 Standard realFormat = dtfi.RFC1123Pattern; break; case 's': // Sortable without Time Zone Info realFormat = dtfi.SortableDateTimePattern; break; case 't': // Short Time realFormat = dtfi.ShortTimePattern; break; case 'T': // Long Time realFormat = dtfi.LongTimePattern; break; case 'u': // Universal with Sortable format realFormat = dtfi.UniversalSortableDateTimePattern; break; case 'U': // Universal with Full (long date + long time) format realFormat = dtfi.FullDateTimePattern; break; case 'y': case 'Y': // Year/Month Date realFormat = dtfi.YearMonthPattern; break; default: throw new FormatException(SR.Format_InvalidString); } return (realFormat); } // Expand a pre-defined format string (like "D" for long date) to the real format that // we are going to use in the date time parsing. // This method also convert the dateTime if necessary (e.g. when the format is in Universal time), // and change dtfi if necessary (e.g. when the format should use invariant culture). // private static String ExpandPredefinedFormat(String format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, ref TimeSpan offset) { switch (format[0]) { case 'o': case 'O': // Round trip format dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'r': case 'R': // RFC 1123 Standard if (offset != NullOffset) { // Convert to UTC invariants mean this will be in range dateTime = dateTime - offset; } else if (dateTime.Kind == DateTimeKind.Local) { InvalidFormatForLocal(format, dateTime); } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 's': // Sortable without Time Zone Info dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'u': // Universal time in sortable format. if (offset != NullOffset) { // Convert to UTC invariants mean this will be in range dateTime = dateTime - offset; } else if (dateTime.Kind == DateTimeKind.Local) { InvalidFormatForLocal(format, dateTime); } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'U': // Universal time in culture dependent format. if (offset != NullOffset) { // This format is not supported by DateTimeOffset throw new FormatException(SR.Format_InvalidString); } // Universal time is always in Greogrian calendar. // // Change the Calendar to be Gregorian Calendar. // dtfi = (DateTimeFormatInfo)dtfi.Clone(); if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) { dtfi.Calendar = GregorianCalendar.GetDefaultInstance(); } dateTime = dateTime.ToUniversalTime(); break; } format = GetRealFormat(format, dtfi); return (format); } internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi) { return Format(dateTime, format, dtfi, NullOffset); } internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset) { Contract.Requires(dtfi != null); if (format == null || format.Length == 0) { Boolean timeOnlySpecialCase = false; if (dateTime.Ticks < Calendar.TicksPerDay) { // If the time is less than 1 day, consider it as time of day. // Just print out the short time format. // // This is a workaround for VB, since they use ticks less then one day to be // time of day. In cultures which use calendar other than Gregorian calendar, these // alternative calendar may not support ticks less than a day. // For example, Japanese calendar only supports date after 1868/9/8. // This will pose a problem when people in VB get the time of day, and use it // to call ToString(), which will use the general format (short date + long time). // Since Japanese calendar does not support Gregorian year 0001, an exception will be // thrown when we try to get the Japanese year for Gregorian year 0001. // Therefore, the workaround allows them to call ToString() for time of day from a DateTime by // formatting as ISO 8601 format. switch (dtfi.Calendar.ID) { case CalendarId.JAPAN: case CalendarId.TAIWAN: case CalendarId.HIJRI: case CalendarId.HEBREW: case CalendarId.JULIAN: case CalendarId.UMALQURA: case CalendarId.PERSIAN: timeOnlySpecialCase = true; dtfi = DateTimeFormatInfo.InvariantInfo; break; } } if (offset == NullOffset) { // Default DateTime.ToString case. if (timeOnlySpecialCase) { format = "s"; } else { format = "G"; } } else { // Default DateTimeOffset.ToString case. if (timeOnlySpecialCase) { format = RoundtripDateTimeUnfixed; } else { format = dtfi.DateTimeOffsetPattern; } } } if (format.Length == 1) { switch (format[0]) { case 'O': case 'o': return FastFormatRoundtrip(dateTime, offset); case 'R': case 'r': return FastFormatRfc1123(dateTime, offset, dtfi); } format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, ref offset); } return (FormatCustomized(dateTime, format, dtfi, offset)); } internal static string FastFormatRfc1123(DateTime dateTime, TimeSpan offset, DateTimeFormatInfo dtfi) { // ddd, dd MMM yyyy HH:mm:ss GMT const int Rfc1123FormatLength = 29; StringBuilder result = StringBuilderCache.Acquire(Rfc1123FormatLength); if (offset != NullOffset) { // Convert to UTC invariants dateTime = dateTime - offset; } dateTime.GetDatePart(out int year, out int month, out int day); result.Append(InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]); result.Append(','); result.Append(' '); AppendNumber(result, day, 2); result.Append(' '); result.Append(InvariantAbbreviatedMonthNames[month - 1]); result.Append(' '); AppendNumber(result, year, 4); result.Append(' '); AppendHHmmssTimeOfDay(result, dateTime); result.Append(' '); result.Append(Gmt); return StringBuilderCache.GetStringAndRelease(result); } internal static string FastFormatRoundtrip(DateTime dateTime, TimeSpan offset) { // yyyy-MM-ddTHH:mm:ss.fffffffK const int roundTripFormatLength = 28; StringBuilder result = StringBuilderCache.Acquire(roundTripFormatLength); dateTime.GetDatePart(out int year, out int month, out int day); AppendNumber(result, year, 4); result.Append('-'); AppendNumber(result, month, 2); result.Append('-'); AppendNumber(result, day, 2); result.Append('T'); AppendHHmmssTimeOfDay(result, dateTime); result.Append('.'); long fraction = dateTime.Ticks % TimeSpan.TicksPerSecond; AppendNumber(result, fraction, 7); FormatCustomizedRoundripTimeZone(dateTime, offset, result); return StringBuilderCache.GetStringAndRelease(result); } private static void AppendHHmmssTimeOfDay(StringBuilder result, DateTime dateTime) { // HH:mm:ss AppendNumber(result, dateTime.Hour, 2); result.Append(':'); AppendNumber(result, dateTime.Minute, 2); result.Append(':'); AppendNumber(result, dateTime.Second, 2); } internal static void AppendNumber(StringBuilder builder, long val, int digits) { for (int i = 0; i < digits; i++) { builder.Append('0'); } int index = 1; while (val > 0 && index <= digits) { builder[builder.Length - index] = (char)('0' + (val % 10)); val = val / 10; index++; } Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val"); } internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi) { Contract.Requires(dtfi != null); String[] allFormats = null; String[] results = null; switch (format) { case 'd': case 'D': case 'f': case 'F': case 'g': case 'G': case 'm': case 'M': case 't': case 'T': case 'y': case 'Y': allFormats = dtfi.GetAllDateTimePatterns(format); results = new String[allFormats.Length]; for (int i = 0; i < allFormats.Length; i++) { results[i] = Format(dateTime, allFormats[i], dtfi); } break; case 'U': DateTime universalTime = dateTime.ToUniversalTime(); allFormats = dtfi.GetAllDateTimePatterns(format); results = new String[allFormats.Length]; for (int i = 0; i < allFormats.Length; i++) { results[i] = Format(universalTime, allFormats[i], dtfi); } break; // // The following ones are special cases because these patterns are read-only in // DateTimeFormatInfo. // case 'r': case 'R': case 'o': case 'O': case 's': case 'u': results = new String[] { Format(dateTime, new String(format, 1), dtfi) }; break; default: throw new FormatException(SR.Format_InvalidString); } return (results); } internal static String[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo dtfi) { List<String> results = new List<String>(DEFAULT_ALL_DATETIMES_SIZE); for (int i = 0; i < allStandardFormats.Length; i++) { String[] strings = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi); for (int j = 0; j < strings.Length; j++) { results.Add(strings[j]); } } String[] value = new String[results.Count]; results.CopyTo(0, value, 0, results.Count); return (value); } // This is a placeholder for an MDA to detect when the user is using a // local DateTime with a format that will be interpreted as UTC. internal static void InvalidFormatForLocal(String format, DateTime dateTime) { } } }
// UpdateManager.cs, 10.06.2019 // Copyright (C) Dominic Beger 17.06.2019 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using nUpdate.Exceptions; using nUpdate.Internal.Core; using nUpdate.Internal.Core.Operations; using nUpdate.UpdateEventArgs; namespace nUpdate.Updating { // WITHOUT TAP /// <summary> /// Provides functionality to update .NET-applications. /// </summary> public partial class UpdateManager { /// <summary> /// Downloads the available update packages from the server. /// </summary> /// <seealso cref="DownloadPackagesAsync" /> public void DownloadPackages() { OnUpdateDownloadStarted(this, EventArgs.Empty); long received = 0; var total = PackageConfigurations.Select(config => GetUpdatePackageSize(config.UpdatePackageUri)) .Where(updatePackageSize => updatePackageSize != null) .Sum(updatePackageSize => updatePackageSize.Value); if (!Directory.Exists(_applicationUpdateDirectory)) Directory.CreateDirectory(_applicationUpdateDirectory); foreach (var updateConfiguration in PackageConfigurations) { WebResponse webResponse = null; try { var webRequest = WebRequestWrapper.Create(updateConfiguration.UpdatePackageUri); if (HttpAuthenticationCredentials != null) webRequest.Credentials = HttpAuthenticationCredentials; using (webResponse = webRequest.GetResponse()) { var buffer = new byte[1024]; _packageFilePaths.Add(new UpdateVersion(updateConfiguration.LiteralVersion), Path.Combine(_applicationUpdateDirectory, $"{updateConfiguration.LiteralVersion}.zip")); using (var fileStream = File.Create(Path.Combine(_applicationUpdateDirectory, $"{updateConfiguration.LiteralVersion}.zip"))) { using (var input = webResponse.GetResponseStream()) { if (input == null) throw new Exception("The response stream couldn't be read."); var size = input.Read(buffer, 0, buffer.Length); while (size > 0) { fileStream.Write(buffer, 0, size); received += size; OnUpdateDownloadProgressChanged(received, (long) total, (float) (received / total) * 100); size = input.Read(buffer, 0, buffer.Length); } if (_downloadCancellationTokenSource.IsCancellationRequested) return; if (!updateConfiguration.UseStatistics || !IncludeCurrentPcIntoStatistics) continue; var response = new WebClient {Credentials = HttpAuthenticationCredentials}.DownloadString( $"{updateConfiguration.UpdatePhpFileUri}?versionid={updateConfiguration.VersionId}&os={SystemInformation.OperatingSystemName}"); // Only for calling it if (string.IsNullOrEmpty(response)) return; OnStatisticsEntryFailed(new StatisticsException(string.Format( _lp.StatisticsScriptExceptionText, response))); } } } } finally { webResponse?.Close(); } } } /// <summary> /// Downloads the available update packages from the server, asynchronously. /// </summary> public void DownloadPackagesAsync() { OnUpdateDownloadStarted(this, EventArgs.Empty); Task.Factory.StartNew(() => { _downloadCancellationTokenSource?.Dispose(); _downloadCancellationTokenSource = new CancellationTokenSource(); long received = 0; var total = PackageConfigurations.Select(config => GetUpdatePackageSize(config.UpdatePackageUri)) .Where(updatePackageSize => updatePackageSize != null) .Sum(updatePackageSize => updatePackageSize.Value); if (!Directory.Exists(_applicationUpdateDirectory)) Directory.CreateDirectory(_applicationUpdateDirectory); foreach (var updateConfiguration in PackageConfigurations) { if (_downloadCancellationTokenSource.IsCancellationRequested) break; WebResponse webResponse = null; try { // TODO: Implement cancellation for this method in case of e.g. a timeout // Thread will currently continue until the timeout message is thrown and then cancel in the background var webRequest = WebRequestWrapper.Create(updateConfiguration.UpdatePackageUri); if (HttpAuthenticationCredentials != null) webRequest.Credentials = HttpAuthenticationCredentials; using (webResponse = webRequest.GetResponse()) { var buffer = new byte[1024]; _packageFilePaths.Add(new UpdateVersion(updateConfiguration.LiteralVersion), Path.Combine(_applicationUpdateDirectory, $"{updateConfiguration.LiteralVersion}.zip")); using (var fileStream = File.Create(Path.Combine(_applicationUpdateDirectory, $"{updateConfiguration.LiteralVersion}.zip"))) { using (var input = webResponse.GetResponseStream()) { if (input == null) throw new Exception("The response stream couldn't be read."); var size = input.Read(buffer, 0, buffer.Length); while (size > 0) { if (_downloadCancellationTokenSource.IsCancellationRequested) break; fileStream.Write(buffer, 0, size); received += size; OnUpdateDownloadProgressChanged(received, (long) total, (float) (received / total) * 100); size = input.Read(buffer, 0, buffer.Length); } if (_downloadCancellationTokenSource.IsCancellationRequested) return; if (!updateConfiguration.UseStatistics || !IncludeCurrentPcIntoStatistics) continue; var response = new WebClient {Credentials = HttpAuthenticationCredentials}.DownloadString( $"{updateConfiguration.UpdatePhpFileUri}?versionid={updateConfiguration.VersionId}&os={SystemInformation.OperatingSystemName}"); // Only for calling it if (string.IsNullOrEmpty(response)) return; OnStatisticsEntryFailed(new StatisticsException(string.Format( _lp.StatisticsScriptExceptionText, response))); } } } } finally { webResponse?.Close(); } } }).ContinueWith(DownloadTaskCompleted); } private void DownloadTaskCompleted(Task task) { if (_downloadCancellationTokenSource.IsCancellationRequested) return; var exception = task.Exception; if (exception != null) OnUpdateDownloadFailed(exception.InnerException ?? exception); else OnUpdateDownloadFinished(this, EventArgs.Empty); } protected virtual void OnStatisticsEntryFailed(Exception exception) { StatisticsEntryFailed?.Invoke(this, new FailedEventArgs(exception)); } protected virtual void OnUpdateDownloadFailed(Exception exception) { PackagesDownloadFailed?.Invoke(this, new FailedEventArgs(exception)); } protected virtual void OnUpdateDownloadFinished(object sender, EventArgs e) { PackagesDownloadFinished?.Invoke(sender, e); } protected virtual void OnUpdateDownloadProgressChanged(long bytesReceived, long totalBytesToReceive, float percentage) { PackagesDownloadProgressChanged?.Invoke(this, new UpdateDownloadProgressChangedEventArgs(bytesReceived, totalBytesToReceive, percentage)); } protected virtual void OnUpdateDownloadStarted(object sender, EventArgs e) { PackagesDownloadStarted?.Invoke(sender, e); } protected virtual void OnUpdateSearchFailed(Exception exception) { UpdateSearchFailed?.Invoke(this, new FailedEventArgs(exception)); } protected virtual void OnUpdateSearchFinished(bool updateAvailable) { UpdateSearchFinished?.Invoke(this, new UpdateSearchFinishedEventArgs(updateAvailable)); } protected virtual void OnUpdateSearchStarted(object sender, EventArgs e) { UpdateSearchStarted?.Invoke(sender, e); } /// <summary> /// Occurs when the download of the packages fails. /// </summary> public event EventHandler<FailedEventArgs> PackagesDownloadFailed; /// <summary> /// Occurs when the download of the packages has finished. /// </summary> public event EventHandler<EventArgs> PackagesDownloadFinished; /// <summary> /// Occurs when the download progress of the packages has changed. /// </summary> public event EventHandler<UpdateDownloadProgressChangedEventArgs> PackagesDownloadProgressChanged; /// <summary> /// Occurs when the download of the packages begins. /// </summary> public event EventHandler<EventArgs> PackagesDownloadStarted; /// <summary> /// Searches for updates. /// </summary> /// <returns>Returns <c>true</c> if updates were found; otherwise, <c>false</c>.</returns> public bool SearchForUpdates() { // It may be that this is not the first search call and previously saved data needs to be disposed. Cleanup(); OnUpdateSearchStarted(this, EventArgs.Empty); if (!ConnectionManager.IsConnectionAvailable()) return false; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; var configuration = UpdateConfiguration.Download(UpdateConfigurationFileUri, HttpAuthenticationCredentials, Proxy, SearchTimeout); var result = new UpdateResult(configuration, CurrentVersion, IncludeAlpha, IncludeBeta, Conditions); if (!result.UpdatesFound) return false; PackageConfigurations = result.NewestConfigurations; double updatePackageSize = 0; foreach (var updateConfiguration in PackageConfigurations) { updateConfiguration.UpdatePackageUri = ConvertPackageUri(updateConfiguration.UpdatePackageUri); updateConfiguration.UpdatePhpFileUri = ConvertStatisticsUri(updateConfiguration.UpdatePhpFileUri); var newPackageSize = GetUpdatePackageSize(updateConfiguration.UpdatePackageUri); if (newPackageSize == null) throw new SizeCalculationException(_lp.PackageSizeCalculationExceptionText); updatePackageSize += newPackageSize.Value; if (updateConfiguration.Operations == null) continue; if (_packageOperations == null) _packageOperations = new Dictionary<UpdateVersion, IEnumerable<Operation>>(); _packageOperations.Add(new UpdateVersion(updateConfiguration.LiteralVersion), updateConfiguration.Operations); } TotalSize = updatePackageSize; return true; } /// <summary> /// Searches for updates, asynchronously. /// </summary> /// <seealso cref="SearchForUpdates" /> public void SearchForUpdatesAsync() { OnUpdateSearchStarted(this, EventArgs.Empty); Task.Factory.StartNew(() => { // It may be that this is not the first search call and previously saved data needs to be disposed. Cleanup(); // Reinitialize the cancellation tokens and wait handles _searchCancellationTokenSource?.Dispose(); _searchCancellationTokenSource = new CancellationTokenSource(); _searchManualResetEvent.Reset(); if (!ConnectionManager.IsConnectionAvailable()) return false; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; IEnumerable<UpdateConfiguration> configurations = null; Exception exception = null; UpdateConfiguration.DownloadAsync(UpdateConfigurationFileUri, HttpAuthenticationCredentials, Proxy, (c, e) => { configurations = c; exception = e; _searchManualResetEvent.Set(); }, _searchCancellationTokenSource, SearchTimeout); _searchManualResetEvent.WaitOne(); // Check for cancellation before throwing any errors if (_searchCancellationTokenSource.IsCancellationRequested) return false; if (exception != null) throw exception; var result = new UpdateResult(configurations, CurrentVersion, IncludeAlpha, IncludeBeta, Conditions); if (!result.UpdatesFound) return false; PackageConfigurations = result.NewestConfigurations; double updatePackageSize = 0; foreach (var updateConfiguration in PackageConfigurations) { updateConfiguration.UpdatePackageUri = ConvertPackageUri(updateConfiguration.UpdatePackageUri); updateConfiguration.UpdatePhpFileUri = ConvertStatisticsUri(updateConfiguration.UpdatePhpFileUri); if (_searchCancellationTokenSource.IsCancellationRequested) return false; var newPackageSize = GetUpdatePackageSize(updateConfiguration.UpdatePackageUri); if (newPackageSize == null) throw new SizeCalculationException(_lp.PackageSizeCalculationExceptionText); updatePackageSize += newPackageSize.Value; if (updateConfiguration.Operations == null) continue; if (_packageOperations == null) _packageOperations = new Dictionary<UpdateVersion, IEnumerable<Operation>>(); _packageOperations.Add(new UpdateVersion(updateConfiguration.LiteralVersion), updateConfiguration.Operations); } TotalSize = updatePackageSize; return true; }).ContinueWith(SearchTaskCompleted); } private void SearchTaskCompleted(Task<bool> task) { if (_searchCancellationTokenSource.IsCancellationRequested) return; var exception = task.Exception; if (exception != null) OnUpdateSearchFailed(exception.InnerException ?? exception); OnUpdateSearchFinished(task.Result); } /// <summary> /// Occurs when the statistics entry failed. /// </summary> /// <remarks> /// This event is meant to provide the user with a warning, if the statistic server entry fails. The update process /// should not be canceled as this does not cause any problems that could affect it. /// </remarks> public event EventHandler<FailedEventArgs> StatisticsEntryFailed; /// <summary> /// Occurs when an update search has failed. /// </summary> public event EventHandler<FailedEventArgs> UpdateSearchFailed; /// <summary> /// Occurs when an active update search has finished. /// </summary> public event EventHandler<UpdateSearchFinishedEventArgs> UpdateSearchFinished; /// <summary> /// Occurs when an update search is started. /// </summary> public event EventHandler<EventArgs> UpdateSearchStarted; } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; using Newtonsoft.Json.Linq; namespace Microsoft.AzureStack.Management { /// <summary> /// Operations for delegated offers. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> internal partial class DelegatedOfferOperations : IServiceOperations<AzureStackClient>, IDelegatedOfferOperations { /// <summary> /// Initializes a new instance of the DelegatedOfferOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DelegatedOfferOperations(AzureStackClient client) { this._client = client; } private AzureStackClient _client; /// <summary> /// Gets a reference to the /// Microsoft.AzureStack.Management.AzureStackClient. /// </summary> public AzureStackClient Client { get { return this._client; } } /// <summary> /// Gets a delegated offer. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='offerName'> /// Required. the name of the delegated offer. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Delegated offer get result. /// </returns> public async Task<DelegatedOfferGetResult> GetAsync(string offerName, CancellationToken cancellationToken) { // Validate if (offerName == null) { throw new ArgumentNullException("offerName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("offerName", offerName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions/delegatedoffers/"; url = url + Uri.EscapeDataString(offerName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DelegatedOfferGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DelegatedOfferGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DelegatedOfferModel delegatedOfferInstance = new DelegatedOfferModel(); result.DelegatedOffer = delegatedOfferInstance; JToken offerNameValue = responseDoc["offerName"]; if (offerNameValue != null && offerNameValue.Type != JTokenType.Null) { string offerNameInstance = ((string)offerNameValue); delegatedOfferInstance.OfferName = offerNameInstance; } JToken externalReferenceIdValue = responseDoc["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); delegatedOfferInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken accessibilityStateValue = responseDoc["accessibilityState"]; if (accessibilityStateValue != null && accessibilityStateValue.Type != JTokenType.Null) { AccessibilityState accessibilityStateInstance = ((AccessibilityState)Enum.Parse(typeof(AccessibilityState), ((string)accessibilityStateValue), true)); delegatedOfferInstance.AccessibilityState = accessibilityStateInstance; } JToken decommissionedByParentProviderValue = responseDoc["decommissionedByParentProvider"]; if (decommissionedByParentProviderValue != null && decommissionedByParentProviderValue.Type != JTokenType.Null) { bool decommissionedByParentProviderInstance = ((bool)decommissionedByParentProviderValue); delegatedOfferInstance.DecommissionedByParentProvider = decommissionedByParentProviderInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get delegated offers for given subscription ID. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Your documentation here. /// </returns> public async Task<DelegatedOfferListResult> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions/delegatedoffers"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DelegatedOfferListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DelegatedOfferListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DelegatedOfferModel delegatedOfferModelInstance = new DelegatedOfferModel(); result.DelegatedOffers.Add(delegatedOfferModelInstance); JToken offerNameValue = valueValue["offerName"]; if (offerNameValue != null && offerNameValue.Type != JTokenType.Null) { string offerNameInstance = ((string)offerNameValue); delegatedOfferModelInstance.OfferName = offerNameInstance; } JToken externalReferenceIdValue = valueValue["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); delegatedOfferModelInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken accessibilityStateValue = valueValue["accessibilityState"]; if (accessibilityStateValue != null && accessibilityStateValue.Type != JTokenType.Null) { AccessibilityState accessibilityStateInstance = ((AccessibilityState)Enum.Parse(typeof(AccessibilityState), ((string)accessibilityStateValue), true)); delegatedOfferModelInstance.AccessibilityState = accessibilityStateInstance; } JToken decommissionedByParentProviderValue = valueValue["decommissionedByParentProvider"]; if (decommissionedByParentProviderValue != null && decommissionedByParentProviderValue.Type != JTokenType.Null) { bool decommissionedByParentProviderInstance = ((bool)decommissionedByParentProviderValue); delegatedOfferModelInstance.DecommissionedByParentProvider = decommissionedByParentProviderInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Next for get delegated offers for given subscription ID. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='nextLink'> /// Required. The next link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Your documentation here. /// </returns> public async Task<DelegatedOfferListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + Uri.EscapeDataString(nextLink); url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DelegatedOfferListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DelegatedOfferListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DelegatedOfferModel delegatedOfferModelInstance = new DelegatedOfferModel(); result.DelegatedOffers.Add(delegatedOfferModelInstance); JToken offerNameValue = valueValue["offerName"]; if (offerNameValue != null && offerNameValue.Type != JTokenType.Null) { string offerNameInstance = ((string)offerNameValue); delegatedOfferModelInstance.OfferName = offerNameInstance; } JToken externalReferenceIdValue = valueValue["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); delegatedOfferModelInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken accessibilityStateValue = valueValue["accessibilityState"]; if (accessibilityStateValue != null && accessibilityStateValue.Type != JTokenType.Null) { AccessibilityState accessibilityStateInstance = ((AccessibilityState)Enum.Parse(typeof(AccessibilityState), ((string)accessibilityStateValue), true)); delegatedOfferModelInstance.AccessibilityState = accessibilityStateInstance; } JToken decommissionedByParentProviderValue = valueValue["decommissionedByParentProvider"]; if (decommissionedByParentProviderValue != null && decommissionedByParentProviderValue.Type != JTokenType.Null) { bool decommissionedByParentProviderInstance = ((bool)decommissionedByParentProviderValue); delegatedOfferModelInstance.DecommissionedByParentProvider = decommissionedByParentProviderInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update a delegated offer. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters to update delegated offer. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Delegated offer update result. /// </returns> public async Task<DelegatedOfferUpdateResult> UpdateAsync(DelegatedOfferUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.DelegatedOffer == null) { throw new ArgumentNullException("parameters.DelegatedOffer"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions/delegatedoffers/"; if (parameters.DelegatedOffer.OfferName != null) { url = url + Uri.EscapeDataString(parameters.DelegatedOffer.OfferName); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject delegatedOfferUpdateParametersValue = new JObject(); requestDoc = delegatedOfferUpdateParametersValue; if (parameters.DelegatedOffer.OfferName != null) { delegatedOfferUpdateParametersValue["offerName"] = parameters.DelegatedOffer.OfferName; } if (parameters.DelegatedOffer.ExternalReferenceId != null) { delegatedOfferUpdateParametersValue["externalReferenceId"] = parameters.DelegatedOffer.ExternalReferenceId; } delegatedOfferUpdateParametersValue["accessibilityState"] = parameters.DelegatedOffer.AccessibilityState.ToString(); delegatedOfferUpdateParametersValue["decommissionedByParentProvider"] = parameters.DelegatedOffer.DecommissionedByParentProvider; requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DelegatedOfferUpdateResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DelegatedOfferUpdateResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DelegatedOfferModel delegatedOfferInstance = new DelegatedOfferModel(); result.DelegatedOffer = delegatedOfferInstance; JToken offerNameValue = responseDoc["offerName"]; if (offerNameValue != null && offerNameValue.Type != JTokenType.Null) { string offerNameInstance = ((string)offerNameValue); delegatedOfferInstance.OfferName = offerNameInstance; } JToken externalReferenceIdValue = responseDoc["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); delegatedOfferInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken accessibilityStateValue = responseDoc["accessibilityState"]; if (accessibilityStateValue != null && accessibilityStateValue.Type != JTokenType.Null) { AccessibilityState accessibilityStateInstance = ((AccessibilityState)Enum.Parse(typeof(AccessibilityState), ((string)accessibilityStateValue), true)); delegatedOfferInstance.AccessibilityState = accessibilityStateInstance; } JToken decommissionedByParentProviderValue = responseDoc["decommissionedByParentProvider"]; if (decommissionedByParentProviderValue != null && decommissionedByParentProviderValue.Type != JTokenType.Null) { bool decommissionedByParentProviderInstance = ((bool)decommissionedByParentProviderValue); delegatedOfferInstance.DecommissionedByParentProvider = decommissionedByParentProviderInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #define CONTRACTS_FULL using System; using System.Diagnostics.Contracts; using Microsoft.Research.ClousotRegression; namespace TestPostconditionInference { class Intervals { // Should infer result == 20 [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] private int Twenty() { int x = 20; return x; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 12, MethodILOffset = 0)] public int Test_Twenty_Explicit() { int z = Twenty(); Contract.Assert(z == 20); return z; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"Array creation : ok", PrimaryILOffset = 6, MethodILOffset = 0)] public int[] Test_Twenty_Implicit() { return new int[Twenty()]; } // Should infer result >= 0 [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] private long Positive(long x) { if (x > 0) return x; else return 0; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 16, MethodILOffset = 0)] public long Test_Positive(long var) { long pos_var = Positive(var); Contract.Assert(pos_var >= 0); return pos_var; } } class UsePostcondition { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] private void Error() { throw new System.Exception(); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 17, MethodILOffset = 0)] public void CheckGreaterThanZero(int val) { if (val < 0) { Error(); } Contract.Assert(val >= 0); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it",PrimaryILOffset=0,MethodILOffset=0)] #if false // The assert is false, but we generate a precondition out of it, so we mask it [RegressionOutcome(Outcome = ProofOutcome.False, Message = "assert is false", PrimaryILOffset = 14, MethodILOffset = 0)] #else [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 14, MethodILOffset = 0)] #endif public void CheckGreaterThanZero_ShouldFail(int val) { if (val < 0) { Error(); } Contract.Assert(val < 0); } } public class Pre { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 4, MethodILOffset = 0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=4,MethodILOffset=0)] private void Char(int[] array, char index) { // The upper bound is ok, because the proof obligation is pushed to the callers array[index] = 12; } [ClousotRegressionTest("clousot1")] // Fails on clousot2 // [ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 17, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 28, MethodILOffset = 0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=4,MethodILOffset=3)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=4,MethodILOffset=3)] public void TestChar(int[] array, char index) { // The preconditions are ok as they are pushed to the caller Char(array, index); // If we reach this point is because array.Length >= 1 and array.Length > index. // Otherwise we'd have thrown an exception before Contract.Assert(array.Length >= 1); Contract.Assert(array.Length > index); } } public class SymbolicBounds { // Should infer result <= M && result <= x [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] private static int AtMost(int x, int M) { if (x < M) return x; else return M; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 15, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 27, MethodILOffset = 0)] public static void Test_AtMost_OK(int x, int M) { int r = AtMost(x, M); Contract.Assert(r <= x); Contract.Assert(r <= M); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 15, MethodILOffset = 0)] public static void Test_AtMost_Wrong1(int x, int M) { int r = AtMost(x, M); Contract.Assert(r >= x); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 15, MethodILOffset = 0)] public static void Test_AtMost_Wrong2(int x, int M) { int r = AtMost(x, M); Contract.Assert(r >= M); } // Should infer -1 <= result < Max [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] private static int Rand(int Max, int k) { Contract.Requires(Max >= 0); for (int i = 0; i < Max; i++) { if (i == k) return i; } return -1; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 7, MethodILOffset = 14)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 27, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 36, MethodILOffset = 0)] public static void Test_Rand_OK(int Max, int k) { Contract.Requires(Max >= 0); int r = Rand(Max, k); Contract.Assert(r >= -1); Contract.Assert(r < Max); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 7, MethodILOffset = 14)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven. Is it an off-by-one? The static checker can prove r >= (0 - 1) instead", PrimaryILOffset = 27, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"assert is false", PrimaryILOffset = 36, MethodILOffset = 0)] #if CLOUSOT2 [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it",PrimaryILOffset=12,MethodILOffset=0)] #else [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it",PrimaryILOffset=14,MethodILOffset=0)] #endif public static void Test_Rand_Wrong(int Max, int k) { Contract.Requires(Max >= 0); int r = Rand(Max, k); Contract.Assert(r >= 0); Contract.Assert(r > Max); } } public class Old { // Should infer result == Old(x) + 1 [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] private int Incr(int x) { int z = x; x = 22; return z + 1; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 14, MethodILOffset = 0)] public void Test_Incr(int x) { int r = Incr(x); Contract.Assert(r == x + 1); } } public class Old_Wrong { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] public void Incr_Wrong(int x) { // We do not want Clousot to infer this postcondition, which is false // Contract.Ensures(x == Contract.OldValue<int>(x) + 1); x++; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"assert is false", PrimaryILOffset = 13, MethodILOffset = 0)] #if CLOUSOT2 [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it",PrimaryILOffset=0,MethodILOffset=0)] #else [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it",PrimaryILOffset=1,MethodILOffset=0)] #endif public void UseIncr() { int z = 0; Incr_Wrong(z); Contract.Assert(z == 1); } } public class OutRef { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] static void SetToFifty(out int x) { x = 50; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 12, MethodILOffset = 0)] public static void TestSetToFifty() { int z; SetToFifty(out z); Contract.Assert(z == 50); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] static void Incr(ref int x) { x++; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 15, MethodILOffset = 0)] public static void TestIncr_OK() { int z = 22; Incr(ref z); Contract.Assert(z == 23); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"assert is false", PrimaryILOffset = 15, MethodILOffset = 0)] #if CLOUSOT2 [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it",PrimaryILOffset=0,MethodILOffset=0)] #else [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it",PrimaryILOffset=2,MethodILOffset=0)] #endif public static void TestIncr_Wrong() { int z = 22; Incr(ref z); Contract.Assert(z == 22); } } public class Point { int x, y; [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] public Point(int x, int y) { this.x = x; this.y = y; } int X { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] get { return this.x; } } int Y { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] get { return this.y; } } int XPlusY { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] get { return x + y; } } int SquareDistance { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] get { return x * x + y * y; } } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] void Move(int k) { x += k; y += k; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 18, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 33, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 54, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 69, MethodILOffset = 0)] public static void Test_OK() { Point p = new Point(5, 10); Contract.Assert(p.X == 5); Contract.Assert(p.SquareDistance == 125); p.Move(2); Contract.Assert(p.X == 7); Contract.Assert(p.Y == 12); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 18, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 33, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"assert is false", PrimaryILOffset = 54, MethodILOffset = 0)] [RegressionOutcome(Outcome=ProofOutcome.Bottom,Message=@"assert unreachable",PrimaryILOffset=69,MethodILOffset=0)] #if CLOUSOT2 [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it",PrimaryILOffset=0,MethodILOffset=0)] #else [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it",PrimaryILOffset=3,MethodILOffset=0)] #endif public static void Test_Wrong() { Point p = new Point(5, 10); Contract.Assert(p.X == 5); Contract.Assert(p.SquareDistance == 125); p.Move(2); Contract.Assert(p.X == 5); Contract.Assert(p.Y == 11); // unreached } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 44, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 61, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 78, MethodILOffset = 0)] public static void Test(int x, int y) { Contract.Requires(x >= 0); Contract.Requires(y >= 0); Point p = new Point(x, y); Contract.Assert(p.X >= 0); Contract.Assert(p.Y >= 0); Contract.Assert(p.SquareDistance >= 0); } } public struct PointStruct { public int x; public int y; [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] public PointStruct(int x, int y) { this.x = x; this.y = y; } int X { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] get { return this.x; } } int Y { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] get { return this.y; } } int XPlusY { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] get { return x + y; } } int SquareDistance { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] get { return x * x + y * y; } } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] void Move(int k) { x += k; y += k; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 20, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 36, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 59, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 75, MethodILOffset = 0)] public static void Test_OK() { PointStruct p = new PointStruct(5, 10); Contract.Assert(p.X == 5); Contract.Assert(p.SquareDistance == 125); p.Move(2); Contract.Assert(p.X == 7); Contract.Assert(p.Y == 12); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 20, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 36, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"assert is false", PrimaryILOffset = 59, MethodILOffset = 0)] [RegressionOutcome(Outcome=ProofOutcome.Bottom,Message=@"assert unreachable",PrimaryILOffset=75,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it",PrimaryILOffset=0,MethodILOffset=0)] public static void Test_Wrong() { PointStruct p = new PointStruct(5, 10); Contract.Assert(p.X == 5); Contract.Assert(p.SquareDistance == 125); p.Move(2); Contract.Assert(p.X == 5); // False Contract.Assert(p.Y == 11); // Unreached } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 46, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 64, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 82, MethodILOffset = 0)] public static void Test(int x, int y) { Contract.Requires(x >= 0); Contract.Requires(y >= 0); PointStruct p = new PointStruct(x, y); Contract.Assert(p.X >= 0); Contract.Assert(p.Y >= 0); Contract.Assert(p.SquareDistance >= 0); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] public static void InferParamInvariant(PointStruct a) { Contract.Assume(a.X > 0); Contract.Assume(a.y > 0); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] // [RegressionOutcome(Outcome=ProofOutcome.Top,Message="requires unproven",PrimaryILOffset=0,MethodILOffset=10)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="requires unproven: 1 <= a.x",PrimaryILOffset=0,MethodILOffset=10)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="requires unproven: 1 <= a.y",PrimaryILOffset=0,MethodILOffset=10)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 25, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 40, MethodILOffset = 0)] public static void TestInferredParameter(int x, int y) { PointStruct p = new PointStruct(x, y); InferParamInvariant(p); Contract.Assert(p.X > 0); Contract.Assert(p.y > 0); } } public class Virtual { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] virtual public int GetConst() { return 15; } } public class SubVirtual : Virtual { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] public sealed override int GetConst() { return -12; } } public class TestVirtual { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 10, MethodILOffset = 0)] static public void Test(Virtual v) { // The warning here is ok, we do not know which instance is passed Contract.Assert(v.GetConst() == 15); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 10, MethodILOffset = 0)] static public void Test_Sub(SubVirtual sv) { // The analysis does not track types Contract.Assert(sv.GetConst() == -12); } } public class UnreachableCode_Bug_FromMscorlib { public bool isReadOnly; [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] private void VerifyWritable() { if (this.isReadOnly) { throw new InvalidOperationException(); } } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"Array creation : ok", PrimaryILOffset = 30, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"Lower bound access ok", PrimaryILOffset = 44, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"Upper bound access ok", PrimaryILOffset = 44, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"Lower bound access ok", PrimaryILOffset = 54, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"Upper bound access ok", PrimaryILOffset = 54, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 15, MethodILOffset = 0)] #if CLOUSOT2 [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=0,MethodILOffset=1)] #else [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=1,MethodILOffset=1)] #endif public object Set_CurrencyNegativePattern(int value) { this.VerifyWritable(); Contract.Assert(!this.isReadOnly); if ((value < 0) || (value > 15)) { object[] tmp = new object[] { 0, 15 }; return tmp; } return null; } } public class StaticField { public static int static_field; [ClousotRegressionTest("clousot1")] [ClousotRegressionTest("clousot2")] public void F(int k) { // infer: ensures( static_field == k+1 && static_field >= 1 && static_field <= 100) Contract.Requires(k >= 0); Contract.Requires(k < 100); static_field = k+1; } [ClousotRegressionTest("clousot1")] [ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 7, MethodILOffset = 2)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 17, MethodILOffset = 2)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 18, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 35, MethodILOffset = 0)] public void UseFWrong(int p) { F(p); Contract.Assert(static_field >= 1); Contract.Assert(static_field <= 10); } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 7, MethodILOffset = 2)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 17, MethodILOffset = 2)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 18, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 35, MethodILOffset = 0)] public void UseFOk(int p) { F(p); Contract.Assert(static_field >= 1); Contract.Assert(static_field <= 100); } } public class PropertyEnsuresInference { private ExceptionFileTable m_pipe; public PropertyEnsuresInference(ExceptionFileTable o) { this.m_pipe = o; } public bool IsConnected { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message="ensures is valid",PrimaryILOffset=29,MethodILOffset=53)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="ensures is valid",PrimaryILOffset=29,MethodILOffset=55)] get { Contract.Ensures(Contract.Result<bool>() == (m_pipe != null && m_pipe.IsConnected)); return m_pipe != null && m_pipe.IsConnected; } } public bool IsConnectedWithInferredContract { [ClousotRegressionTest] get { return m_pipe != null && m_pipe.IsConnected; } } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message="assert is valid",PrimaryILOffset=32,MethodILOffset=0)] public void Test(PropertyEnsuresInference p) { Contract.Requires(p != null); if(p.IsConnected) { // Use the contract Contract.Assert(p.m_pipe != null); } } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message="assert is valid",PrimaryILOffset=32,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="assert is valid",PrimaryILOffset=48,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="assert unproven. The static checker determined that the condition 'p.m_pipe.RandomBit' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add an explicit assumption at entry to document it: Contract.Assume(p.m_pipe.RandomBit);",PrimaryILOffset=64,MethodILOffset=0)] public void TestWithInferredContract(PropertyEnsuresInference p) { Contract.Requires(p != null); if(p.IsConnectedWithInferredContract) { Contract.Assert(p.m_pipe != null); Contract.Assert(p.m_pipe.IsConnected); Contract.Assert(p.m_pipe.RandomBit); // Should not prove this one } } } public class ExceptionFileTable { public ExceptionFileTable left, right; public bool IsConnected; public bool RandomBit; } } namespace ExtractedFromMscorlib { public class AuthorizationRule { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] protected internal AuthorizationRule(object identity, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { if ((inheritanceFlags < InheritanceFlags.None) || (inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit))) { throw new ArgumentOutOfRangeException(); } if ((propagationFlags < PropagationFlags.None) || (propagationFlags > (PropagationFlags.InheritOnly | PropagationFlags.NoPropagateInherit))) { throw new ArgumentOutOfRangeException(); } } [Flags] public enum InheritanceFlags { None, ContainerInherit, ObjectInherit } [Flags] public enum PropagationFlags { None, NoPropagateInherit, InheritOnly } } public class AccessRule : AuthorizationRule { public object tmp; [ClousotRegressionTest("clousot1"),ClousotRegressionTest("clousot2")] #if CLOUSOT2 [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=0,MethodILOffset=6)] #else [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=1,MethodILOffset=6)] #endif [RegressionOutcome(Outcome = ProofOutcome.Bottom, Message = @"This array creation is never executed", PrimaryILOffset = 21, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Bottom, Message = @"This array creation is never executed", PrimaryILOffset = 49, MethodILOffset = 0)] protected AccessRule(object identity, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) : base(identity, isInherited, inheritanceFlags, propagationFlags) { if ((inheritanceFlags < InheritanceFlags.None) || (inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit))) { tmp = new object[1]; throw new ArgumentOutOfRangeException(); } if ((propagationFlags < PropagationFlags.None) || (propagationFlags > (PropagationFlags.InheritOnly | PropagationFlags.NoPropagateInherit))) { tmp = new object[1]; throw new ArgumentOutOfRangeException(); } } } #if false public class AccessRule_ForClousot2 : AuthorizationRule { public object tmp; [ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 0, MethodILOffset = 6)] protected AccessRule_ForClousot2(object identity, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) : base(identity, isInherited, inheritanceFlags, propagationFlags) { if ((inheritanceFlags < InheritanceFlags.None) || (inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit))) { tmp = new object[1]; throw new ArgumentOutOfRangeException(); } if ((propagationFlags < PropagationFlags.None) || (propagationFlags > (PropagationFlags.InheritOnly | PropagationFlags.NoPropagateInherit))) { tmp = new object[1]; throw new ArgumentOutOfRangeException(); } } } #endif public class DuplicatedPreconditions { [ClousotRegressionTest] [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] private int F(int x) { // We want to avoid having also x >= 4 Contract.Requires(x > 3); return x + 3; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=4,MethodILOffset=3)] public int CallF() { // Should have just one pre-condition return F(15); } } } namespace Optimizations { class RedundantPostcondition { [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2"), RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 23, MethodILOffset = 29)] public int TwoPosts_Easy(int x) { Contract.Requires(x >= 0); Contract.Ensures(Contract.Result<int>() >= 0); // Should not infer *again* Contract.Ensures(Contract.Result<int>() >= 0); return x; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2"), RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 7, MethodILOffset = 14), RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 24, MethodILOffset = 0)] public void Test_TwoPosts_Easy(int x) { Contract.Requires(x >= 0); int z = TwoPosts_Easy(x); Contract.Assert(z == x); } } class RedundantPostcondition2 { private bool b; [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2"), RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 17, MethodILOffset = 30)] public int TwoPosts_Easy(int x) { Contract.Requires(x > 0); Contract.Ensures(Contract.Result<int>() > 0); this.b = true; // Should not infer *again* Contract.Ensures(Contract.Result<int>() >= 0); return x; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2"), RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 4, MethodILOffset = 11), RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 23, MethodILOffset = 0)] public void Test_TwoPosts(int x) { Contract.Requires(x > 0); int z = TwoPosts_Easy(x); Contract.Assert(this.b == true); } } public class Rational { //public int Numerator { get; protected set; } public int Denominator { get; protected set; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2"), RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 12, MethodILOffset = 25)] public Rational(int n, int d) { Contract.Requires(d != 0); //this.Numerator = n; this.Denominator = d; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2")] [ContractInvariantMethod] private void RationalInvariant() { Contract.Invariant(Denominator != 0); } } class RedundantPostcondition4 { private bool b; [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2"), RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 17, MethodILOffset = 34)] public int TwoPosts_Easy(int x) { Contract.Requires(x > 0); Contract.Ensures(Contract.Result<int>() > 0); this.b = x > 22; // Should not infer *again* Contract.Ensures(Contract.Result<int>() >= 0); return x; } [ClousotRegressionTest("clousot1")][ClousotRegressionTest("clousot2"), RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 4, MethodILOffset = 11), RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven", PrimaryILOffset = 30, MethodILOffset = 0)] public void Test_TwoPosts(int x) { Contract.Requires(x > 0); int z = TwoPosts_Easy(x); Contract.Assert(this.b == x > 22); } } } namespace ConstantEnsureInference { [ContractClass(typeof(IVectorContracts))] interface IVector { bool IsVector { get; } int Rank { get; } } [ContractClassFor(typeof(IVector))] abstract class IVectorContracts : IVector { public bool IsVector { get { Contract.Ensures(!Contract.Result<bool>() || this.Rank == 1); return default(bool); } } public int Rank { get { throw new Exception(); } } } public class Vector : IVector { public int Rank { [ClousotRegressionTest] get { // For some reason we are not attaching the inferred postcondition to the IsVector below //Contract.Ensures(Contract.Result<int>() == 1); return 1; } } public bool IsVector { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message="ensures is valid",PrimaryILOffset=19,MethodILOffset=1)] get { return true; } } } public class ScottRepro { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=50,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=50,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Array creation : ok",PrimaryILOffset=86,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=101,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=101,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=111,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=111,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=121,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=121,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Array creation : ok",PrimaryILOffset=246,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=263,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=263,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Array creation : ok",PrimaryILOffset=333,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=350,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=350,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=361,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=361,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Array creation : ok",PrimaryILOffset=431,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=448,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=448,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=459,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=459,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=470,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=470,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Array creation : ok",PrimaryILOffset=510,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=528,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=528,MethodILOffset=0)] public static object PingMethodPost(dynamic state, dynamic[] args) { /* Should *NOT* infer those two Contract.Ensures(ActorStressTests.PingPongActor.< PingMethodPost > o__SiteContainer0.<> p__Site1.Target != null); Contract.Ensures(ActorStressTests.PingPongActor.< PingMethodPost > o__SiteContainer0.<> p__Site2.Target != null); */ int remainingCount = args[0]; state.Publish("Status", remainingCount - 1); if (remainingCount > 0) { string otherActorName = state.otherActorName; dynamic proxy = state.GetActorProxy(otherActorName); proxy.Command("PingMethodPost", new object[] { remainingCount - 1 }); } return null; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Lucene.Net.Util; namespace Lucene.Net.Index { /// <summary> Allows you to iterate over the <see cref="TermPositions" /> for multiple <see cref="Term" />s as /// a single <see cref="TermPositions" />. /// /// </summary> public class MultipleTermPositions : TermPositions { private sealed class TermPositionsQueue : PriorityQueue<TermPositions> { internal TermPositionsQueue(LinkedList<TermPositions> termPositions) { Initialize(termPositions.Count); foreach(TermPositions tp in termPositions) if (tp.Next()) Add(tp); } internal TermPositions Peek() { return Top(); } public override bool LessThan(TermPositions a, TermPositions b) { return a.Doc < b.Doc; } } private sealed class IntQueue { public IntQueue() { InitBlock(); } private void InitBlock() { _array = new int[_arraySize]; } private int _arraySize = 16; private int _index = 0; private int _lastIndex = 0; private int[] _array; internal void add(int i) { if (_lastIndex == _arraySize) growArray(); _array[_lastIndex++] = i; } internal int next() { return _array[_index++]; } internal void sort() { System.Array.Sort(_array, _index, _lastIndex - _index); } internal void clear() { _index = 0; _lastIndex = 0; } internal int size() { return (_lastIndex - _index); } private void growArray() { int[] newArray = new int[_arraySize * 2]; Array.Copy(_array, 0, newArray, 0, _arraySize); _array = newArray; _arraySize *= 2; } } private int _doc; private int _freq; private TermPositionsQueue _termPositionsQueue; private IntQueue _posList; private bool isDisposed; /// <summary> Creates a new <c>MultipleTermPositions</c> instance. /// /// </summary> /// <exception cref="System.IO.IOException"> /// </exception> public MultipleTermPositions(IndexReader indexReader, Term[] terms) { var termPositions = new System.Collections.Generic.LinkedList<TermPositions>(); for (int i = 0; i < terms.Length; i++) termPositions.AddLast(indexReader.TermPositions(terms[i])); _termPositionsQueue = new TermPositionsQueue(termPositions); _posList = new IntQueue(); } public bool Next() { if (_termPositionsQueue.Size() == 0) return false; _posList.clear(); _doc = _termPositionsQueue.Peek().Doc; TermPositions tp; do { tp = _termPositionsQueue.Peek(); for (int i = 0; i < tp.Freq; i++) _posList.add(tp.NextPosition()); if (tp.Next()) _termPositionsQueue.UpdateTop(); else { _termPositionsQueue.Pop(); tp.Close(); } } while (_termPositionsQueue.Size() > 0 && _termPositionsQueue.Peek().Doc == _doc); _posList.sort(); _freq = _posList.size(); return true; } public int NextPosition() { return _posList.next(); } public bool SkipTo(int target) { while (_termPositionsQueue.Peek() != null && target > _termPositionsQueue.Peek().Doc) { TermPositions tp = _termPositionsQueue.Pop(); if (tp.SkipTo(target)) _termPositionsQueue.Add(tp); else tp.Close(); } return Next(); } public int Doc { get { return _doc; } } public int Freq { get { return _freq; } } [Obsolete("Use Dispose() instead")] public void Close() { Dispose(); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (isDisposed) return; if (disposing) { while (_termPositionsQueue.Size() > 0) _termPositionsQueue.Pop().Close(); } isDisposed = true; } /// <summary> Not implemented.</summary> /// <throws> UnsupportedOperationException </throws> public virtual void Seek(Term arg0) { throw new System.NotSupportedException(); } /// <summary> Not implemented.</summary> /// <throws> UnsupportedOperationException </throws> public virtual void Seek(TermEnum termEnum) { throw new System.NotSupportedException(); } /// <summary> Not implemented.</summary> /// <throws> UnsupportedOperationException </throws> public virtual int Read(int[] arg0, int[] arg1) { throw new System.NotSupportedException(); } /// <summary> Not implemented.</summary> /// <throws> UnsupportedOperationException </throws> public virtual int PayloadLength { get { throw new System.NotSupportedException(); } } /// <summary> Not implemented.</summary> /// <throws> UnsupportedOperationException </throws> public virtual byte[] GetPayload(byte[] data, int offset) { throw new System.NotSupportedException(); } /// <summary> </summary> /// <value> false </value> // TODO: Remove warning after API has been finalized public virtual bool IsPayloadAvailable { get { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using Assman.Configuration; using Assman.ContentFiltering; using Assman.DependencyManagement; using Assman.PreCompilation; namespace Assman { public class ResourceCompiler { private readonly ContentFilterPipelineMap _contentFilterPipelineMap; private readonly DependencyManager _dependencyManager; private readonly IResourceGroupManager _scriptGroups; private readonly IResourceGroupManager _styleGroups; private readonly IResourceFinder _finder; private readonly ResourceMode _resourceMode; public ResourceCompiler(ContentFilterPipelineMap contentFilterPipelineMap, DependencyManager dependencyManager, IResourceGroupManager scriptGroups, IResourceGroupManager styleGroups, IResourceFinder finder, ResourceMode resourceMode) { _contentFilterPipelineMap = contentFilterPipelineMap; _dependencyManager = dependencyManager; _scriptGroups = scriptGroups; _styleGroups = styleGroups; _finder = finder; _resourceMode = resourceMode; } public ICompiledResource CompileGroup(string groupConsolidatedUrl, GroupTemplateContext groupTemplateContext) { var group = groupTemplateContext.FindGroupOrDefault(_finder, groupConsolidatedUrl, _resourceMode); if (group == null) { throw new Exception("No group with consolidatedUrl '" + groupConsolidatedUrl + "' could be found."); } return CompileGroup(group); } public ICompiledResource CompileGroup(IResourceGroup group) { Func<IResource, string> getResourceContent = resource => { var contentFilterPipeline = _contentFilterPipelineMap.GetPipelineForExtension(resource.FileExtension); var contentFilterContext = new ContentFilterContext { Group = group, Minify = group.Minify, ResourceVirtualPath = resource.VirtualPath }; return contentFilterPipeline.FilterContent(resource.GetContent(), contentFilterContext); }; return group.GetResources() .SortByDependencies(_dependencyManager) .Consolidate(group, getResourceContent, group.ResourceType.Separator); } public PreCompilationReport CompileAll(Action<ICompiledResource> handleConsolidatedResource) { return new PreCompilationReport { Scripts = CompileAllResourcesOfType(ResourceType.Script, handleConsolidatedResource), Stylesheets = CompileAllResourcesOfType(ResourceType.Stylesheet, handleConsolidatedResource), Dependencies = GetAllDependencies().ToList() }; } public IEnumerable<ICompiledResource> CompileUnconsolidatedResources(ResourceType resourceType, Action<ICompiledResource> handleCompiledResource) { var resources = _finder.FindResources(resourceType).ToArray(); var groupManager = GroupManagerFor(resourceType); var unconsolidatedResources = (from resource in resources where !resource.IsExternallyCompiled() && !groupManager.IsPartOfGroup(resource.VirtualPath) && CanCompileIndividually(resource) select resource).ToList(); var compiledResources = new List<ICompiledResource>(); foreach (var unconsolidatedResource in unconsolidatedResources) { var compiledResource = CompileResource(unconsolidatedResource); handleCompiledResource(compiledResource); compiledResources.Add(compiledResource); } return compiledResources; } public ICompiledResource CompileResource(IResource resource) { var contentFilterPipeline = _contentFilterPipelineMap.GetPipelineForExtension(resource.FileExtension); var contentFilterContext = new ContentFilterContext { Minify = _resourceMode == ResourceMode.Release, //TODO: obey global Minify settings ResourceVirtualPath = resource.VirtualPath }; var compiledContent = contentFilterPipeline.FilterContent(resource.GetContent(), contentFilterContext); return new IndividuallyCompiledResource { Resource = resource, Mode = _resourceMode, CompiledContent = compiledContent }; } private bool CanCompileIndividually(IResource resource) { //currently we only know how to compile file resources. In order to compile other resources (e.g. embedded resources) //we would need to figure out how to generate a unique file path to compile it to //this seems like low priority, but will reconsider later return resource.VirtualPath.StartsWith("~/"); } private PreCompiledResourceReport CompileAllResourcesOfType(ResourceType resourceType, Action<ICompiledResource> onCompiled) { var groupManager = GroupManagerFor(resourceType); return new PreCompiledResourceReport { Groups = ConsolidateGroupsInternal(resourceType, groupManager, onCompiled).ToList(), SingleResources = CompileUnconsolidatedResources(resourceType, onCompiled) .Select(r => new PreCompiledSingleResource { OriginalPath = r.Resources.Single().VirtualPath, CompiledPath = r.CompiledPath }).ToList() }; } private IEnumerable<PreCompiledResourceGroup> ConsolidateGroupsInternal(ResourceType resourceType, IResourceGroupManager groupTemplates, Action<ICompiledResource> onCompiled) { if (!groupTemplates.Any()) return Enumerable.Empty<PreCompiledResourceGroup>(); var allResources = _finder.FindResources(resourceType).ToArray(); var preConsolidatedGroups = new List<PreCompiledResourceGroup>(); groupTemplates.EachGroup(allResources, group => { var consolidatedResource = CompileGroup(group); onCompiled(consolidatedResource); var preConsolidatedGroup = new PreCompiledResourceGroup { ConsolidatedUrl = group.ConsolidatedUrl, Resources = consolidatedResource.Resources.Select(resource => resource.VirtualPath).ToList() }; preConsolidatedGroups.Add(preConsolidatedGroup); }); return preConsolidatedGroups; } private IEnumerable<PreCompiledResourceDependencies> GetAllDependencies() { var allResources = _finder.FindResources(ResourceType.Script) .Union(_finder.FindResources(ResourceType.Stylesheet)) .ToArray(); //we must gather the dependencies for the consolidated url's before we gather them for specific url's //because the consolidated url's could actually exist on disk if pre-consolidation was run before. //In that case, if we did the specific resources first, it would use the IDependencyProvider against the //content of the consolidated resource, which is not what we want. Then that value is cached and prevents us from finding //the dependencies for the group. var scriptDependenciesByConsolidatedUrl = GetDependenciesForConsolidatedUrls(_scriptGroups, allResources); var styleDependenciesByConsolidatedUrl = GetDependenciesForConsolidatedUrls(_styleGroups, allResources); var specificResourceDependencies = from resource in allResources let dependencies = _dependencyManager.GetDependencies(resource) where dependencies.Any() select new PreCompiledResourceDependencies { ResourcePath = resource.VirtualPath, Dependencies = dependencies.ToList() }; return scriptDependenciesByConsolidatedUrl.Union(styleDependenciesByConsolidatedUrl).Union( specificResourceDependencies); } private IResourceGroupManager GroupManagerFor(ResourceType resourceType) { if (resourceType == ResourceType.Stylesheet) return _styleGroups; else return _scriptGroups; } private IEnumerable<PreCompiledResourceDependencies> GetDependenciesForConsolidatedUrls( IResourceGroupManager groupManager, IEnumerable<IResource> allResources) { var preConsolidatedDependencies = new List<PreCompiledResourceDependencies>(); groupManager.EachGroup(allResources, @group => { var dependencies = _dependencyManager.GetDependencies(@group.ConsolidatedUrl); if (dependencies.Any()) { preConsolidatedDependencies.Add(new PreCompiledResourceDependencies { ResourcePath = @group.ConsolidatedUrl, Dependencies = dependencies.ToList() }); } }); return preConsolidatedDependencies; } } }
// // XmlTextReaderTests.cs // // Authors: // Jason Diamond (jason@injektilo.org) // Martin Willemoes Hansen (mwh@sysrq.dk) // // (C) 2001, 2002 Jason Diamond http://injektilo.org/ // using System; using System.IO; using System.Xml; using System.Text; using NUnit.Framework; namespace MonoTests.System.Xml { [TestFixture] public class XmlTextReaderTests { private void AssertStartDocument (XmlReader xmlReader) { Assert.IsTrue (xmlReader.ReadState == ReadState.Initial); Assert.IsTrue (xmlReader.NodeType == XmlNodeType.None); Assert.IsTrue (xmlReader.Depth == 0); Assert.IsTrue (!xmlReader.EOF); } private void AssertNode ( XmlReader xmlReader, XmlNodeType nodeType, int depth, bool isEmptyElement, string name, string prefix, string localName, string namespaceURI, string value, int attributeCount) { Assert.IsTrue (xmlReader.Read (), "#Read"); Assert.IsTrue (xmlReader.ReadState == ReadState.Interactive, "#ReadState"); Assert.IsTrue (!xmlReader.EOF); AssertNodeValues (xmlReader, nodeType, depth, isEmptyElement, name, prefix, localName, namespaceURI, value, attributeCount); } private void AssertNodeValues ( XmlReader xmlReader, XmlNodeType nodeType, int depth, bool isEmptyElement, string name, string prefix, string localName, string namespaceURI, string value, int attributeCount) { Assert.AreEqual (nodeType, xmlReader.NodeType, "NodeType"); Assert.AreEqual (depth, xmlReader.Depth, "Depth"); Assert.AreEqual (isEmptyElement, xmlReader.IsEmptyElement, "IsEmptyElement"); Assert.AreEqual (name, xmlReader.Name, "name"); Assert.AreEqual (prefix, xmlReader.Prefix, "prefix"); Assert.AreEqual (localName, xmlReader.LocalName, "localName"); Assert.AreEqual (namespaceURI, xmlReader.NamespaceURI, "namespaceURI"); Assert.AreEqual ((value != String.Empty), xmlReader.HasValue, "hasValue"); Assert.AreEqual (value, xmlReader.Value, "Value"); Assert.AreEqual (attributeCount > 0, xmlReader.HasAttributes, "hasAttributes"); Assert.AreEqual (attributeCount, xmlReader.AttributeCount, "attributeCount"); } private void AssertAttribute ( XmlReader xmlReader, string name, string prefix, string localName, string namespaceURI, string value) { Assert.AreEqual (value, xmlReader [name], "value.Indexer"); Assert.AreEqual (value, xmlReader.GetAttribute (name), "value.GetAttribute"); if (namespaceURI != String.Empty) { Assert.IsTrue (xmlReader[localName, namespaceURI] == value); Assert.IsTrue (xmlReader.GetAttribute (localName, namespaceURI) == value); } } private void AssertEndDocument (XmlReader xmlReader) { Assert.IsTrue (!xmlReader.Read (), "could read"); Assert.AreEqual (XmlNodeType.None, xmlReader.NodeType, "NodeType is not XmlNodeType.None"); Assert.AreEqual (0, xmlReader.Depth, "Depth is not 0"); Assert.AreEqual (ReadState.EndOfFile, xmlReader.ReadState, "ReadState is not ReadState.EndOfFile"); Assert.IsTrue (xmlReader.EOF, "not EOF"); xmlReader.Close (); Assert.AreEqual (ReadState.Closed, xmlReader.ReadState, "ReadState is not ReadState.Cosed"); } [Test] public void StartAndEndTagWithAttribute () { string xml = @"<foo bar='baz'></foo>"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); AssertStartDocument (xmlReader); AssertNode ( xmlReader, // xmlReader XmlNodeType.Element, // nodeType 0, //depth false, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 1 // attributeCount ); AssertAttribute ( xmlReader, // xmlReader "bar", // name String.Empty, // prefix "bar", // localName String.Empty, // namespaceURI "baz" // value ); AssertNode ( xmlReader, // xmlReader XmlNodeType.EndElement, // nodeType 0, //depth false, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertEndDocument (xmlReader); } // expecting parser error [Test] public void EmptyElementWithBadName () { string xml = "<1foo/>"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); bool caughtXmlException = false; try { xmlReader.Read(); } catch (XmlException) { caughtXmlException = true; } Assert.IsTrue (caughtXmlException); } [Test] public void EmptyElementWithStartAndEndTag () { string xml = "<foo></foo>"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); AssertStartDocument (xmlReader); AssertNode ( xmlReader, // xmlReader XmlNodeType.Element, // nodeType 0, //depth false, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertNode ( xmlReader, // xmlReader XmlNodeType.EndElement, // nodeType 0, //depth false, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertEndDocument (xmlReader); } // checking parser [Test] public void EmptyElementWithStartAndEndTagWithWhitespace () { string xml = "<foo ></foo >"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); AssertStartDocument (xmlReader); AssertNode ( xmlReader, // xmlReader XmlNodeType.Element, // nodeType 0, //depth false, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertNode ( xmlReader, // xmlReader XmlNodeType.EndElement, // nodeType 0, //depth false, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertEndDocument (xmlReader); } [Test] public void EmptyElementWithAttribute () { string xml = @"<foo bar=""baz""/>"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); AssertStartDocument (xmlReader); AssertNode ( xmlReader, // xmlReader XmlNodeType.Element, // nodeType 0, //depth true, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 1 // attributeCount ); AssertAttribute ( xmlReader, // xmlReader "bar", // name String.Empty, // prefix "bar", // localName String.Empty, // namespaceURI "baz" // value ); AssertEndDocument (xmlReader); } [Test] public void EmptyElementInNamespace () { string xml = @"<foo:bar xmlns:foo='http://foo/' />"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); AssertStartDocument (xmlReader); AssertNode ( xmlReader, // xmlReader XmlNodeType.Element, // nodeType 0, // depth true, // isEmptyElement "foo:bar", // name "foo", // prefix "bar", // localName "http://foo/", // namespaceURI String.Empty, // value 1 // attributeCount ); AssertAttribute ( xmlReader, // xmlReader "xmlns:foo", // name "xmlns", // prefix "foo", // localName "http://www.w3.org/2000/xmlns/", // namespaceURI "http://foo/" // value ); Assert.AreEqual ("http://foo/", xmlReader.LookupNamespace ("foo")); AssertEndDocument (xmlReader); } [Test] public void EntityReferenceInAttribute () { string xml = "<foo bar='&baz;'/>"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); AssertStartDocument (xmlReader); AssertNode ( xmlReader, // xmlReader XmlNodeType.Element, // nodeType 0, //depth true, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 1 // attributeCount ); AssertAttribute ( xmlReader, // xmlReader "bar", // name String.Empty, // prefix "bar", // localName String.Empty, // namespaceURI "&baz;" // value ); AssertEndDocument (xmlReader); } [Test] public void IsName () { Assert.IsTrue (XmlReader.IsName ("foo")); Assert.IsTrue (!XmlReader.IsName ("1foo")); Assert.IsTrue (!XmlReader.IsName (" foo")); } [Test] public void IsNameToken () { Assert.IsTrue (XmlReader.IsNameToken ("foo")); Assert.IsTrue (XmlReader.IsNameToken ("1foo")); Assert.IsTrue (!XmlReader.IsNameToken (" foo")); } [Test] public void FragmentConstructor() { XmlDocument doc = new XmlDocument(); // doc.LoadXml("<root/>"); string xml = @"<foo><bar xmlns=""NSURI"">TEXT NODE</bar></foo>"; MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(xml)); XmlParserContext ctx = new XmlParserContext(doc.NameTable, new XmlNamespaceManager(doc.NameTable), "", "", "", "", doc.BaseURI, "", XmlSpace.Default, Encoding.Default); XmlTextReader xmlReader = new XmlTextReader(ms, XmlNodeType.Element, ctx); AssertNode(xmlReader, XmlNodeType.Element, 0, false, "foo", "", "foo", "", "", 0); AssertNode(xmlReader, XmlNodeType.Element, 1, false, "bar", "", "bar", "NSURI", "", 1); AssertNode(xmlReader, XmlNodeType.Text, 2, false, "", "", "", "", "TEXT NODE", 0); AssertNode(xmlReader, XmlNodeType.EndElement, 1, false, "bar", "", "bar", "NSURI", "", 0); AssertNode(xmlReader, XmlNodeType.EndElement, 0, false, "foo", "", "foo", "", "", 0); AssertEndDocument (xmlReader); } [Test] public void AttributeWithCharacterReference () { string xml = @"<a value='hello &amp; world' />"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); xmlReader.Read (); Assert.AreEqual ("hello & world", xmlReader ["value"]); } [Test] public void AttributeWithEntityReference () { string xml = @"<a value='hello &ent; world' />"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); xmlReader.Read (); xmlReader.MoveToFirstAttribute (); xmlReader.ReadAttributeValue (); Assert.AreEqual ("hello ", xmlReader.Value); Assert.IsTrue (xmlReader.ReadAttributeValue ()); Assert.AreEqual (XmlNodeType.EntityReference, xmlReader.NodeType); Assert.AreEqual ("ent", xmlReader.Name); Assert.AreEqual (XmlNodeType.EntityReference, xmlReader.NodeType); Assert.IsTrue (xmlReader.ReadAttributeValue ()); Assert.AreEqual (" world", xmlReader.Value); Assert.AreEqual (XmlNodeType.Text, xmlReader.NodeType); Assert.IsTrue (!xmlReader.ReadAttributeValue ()); Assert.AreEqual (" world", xmlReader.Value); // remains Assert.AreEqual (XmlNodeType.Text, xmlReader.NodeType); xmlReader.ReadAttributeValue (); Assert.AreEqual (XmlNodeType.Text, xmlReader.NodeType); } [Test] public void QuoteChar () { string xml = @"<a value='hello &amp; world' value2="""" />"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); xmlReader.Read (); xmlReader.MoveToFirstAttribute (); Assert.AreEqual ('\'', xmlReader.QuoteChar, "First"); xmlReader.MoveToNextAttribute (); Assert.AreEqual ('"', xmlReader.QuoteChar, "Next"); xmlReader.MoveToFirstAttribute (); Assert.AreEqual ('\'', xmlReader.QuoteChar, "First.Again"); } [Test] public void ReadInnerXmlWrongInit () { // This behavior is different from XmlNodeReader. XmlReader reader = new XmlTextReader (new StringReader ("<root>test of <b>mixed</b> string.</root>")); reader.ReadInnerXml (); Assert.AreEqual (ReadState.Initial, reader.ReadState, "initial.ReadState"); Assert.AreEqual (false, reader.EOF, "initial.EOF"); Assert.AreEqual (XmlNodeType.None, reader.NodeType, "initial.NodeType"); } [Test] public void EntityReference () { string xml = "<foo>&bar;</foo>"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); AssertNode ( xmlReader, // xmlReader XmlNodeType.Element, // nodeType 0, //depth false, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertNode ( xmlReader, // xmlReader XmlNodeType.EntityReference, // nodeType 1, //depth false, // isEmptyElement "bar", // name String.Empty, // prefix "bar", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertNode ( xmlReader, // xmlReader XmlNodeType.EndElement, // nodeType 0, //depth false, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertEndDocument (xmlReader); } [Test] public void EntityReferenceInsideText () { string xml = "<foo>bar&baz;quux</foo>"; XmlReader xmlReader = new XmlTextReader (new StringReader (xml)); AssertNode ( xmlReader, // xmlReader XmlNodeType.Element, // nodeType 0, //depth false, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertNode ( xmlReader, // xmlReader XmlNodeType.Text, // nodeType 1, //depth false, // isEmptyElement String.Empty, // name String.Empty, // prefix String.Empty, // localName String.Empty, // namespaceURI "bar", // value 0 // attributeCount ); AssertNode ( xmlReader, // xmlReader XmlNodeType.EntityReference, // nodeType 1, //depth false, // isEmptyElement "baz", // name String.Empty, // prefix "baz", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertNode ( xmlReader, // xmlReader XmlNodeType.Text, // nodeType 1, //depth false, // isEmptyElement String.Empty, // name String.Empty, // prefix String.Empty, // localName String.Empty, // namespaceURI "quux", // value 0 // attributeCount ); AssertNode ( xmlReader, // xmlReader XmlNodeType.EndElement, // nodeType 0, //depth false, // isEmptyElement "foo", // name String.Empty, // prefix "foo", // localName String.Empty, // namespaceURI String.Empty, // value 0 // attributeCount ); AssertEndDocument (xmlReader); } [Test] [ExpectedException (typeof (XmlException))] public void XmlDeclAfterWhitespace () { XmlTextReader xtr = new XmlTextReader ( " <?xml version='1.0' ?><root />", XmlNodeType.Document, null); xtr.Read (); // ws xtr.Read (); // not-wf xmldecl xtr.Close (); } [Test] [ExpectedException (typeof (XmlException))] public void XmlDeclAfterComment () { XmlTextReader xtr = new XmlTextReader ( "<!-- comment --><?xml version='1.0' ?><root />", XmlNodeType.Document, null); xtr.Read (); // comment xtr.Read (); // not-wf xmldecl xtr.Close (); } [Test] [ExpectedException (typeof (XmlException))] public void XmlDeclAfterProcessingInstruction () { XmlTextReader xtr = new XmlTextReader ( "<?myPI let it go ?><?xml version='1.0' ?><root />", XmlNodeType.Document, null); xtr.Read (); // PI xtr.Read (); // not-wf xmldecl xtr.Close (); } [Test] [ExpectedException (typeof (XmlException))] public void StartsFromEndElement () { XmlTextReader xtr = new XmlTextReader ( "</root>", XmlNodeType.Document, null); xtr.Read (); xtr.Close (); } [Test] public void ReadAsElementContent () { XmlTextReader xtr = new XmlTextReader ( "<foo /><bar />", XmlNodeType.Element, null); xtr.Read (); xtr.Close (); } [Test] public void ReadAsAttributeContent () { XmlTextReader xtr = new XmlTextReader ( "test", XmlNodeType.Attribute, null); xtr.Read (); xtr.Close (); } [Test] public void ExternalDocument () { XmlDocument doc = new XmlDocument (); doc.Load ("Test/XmlFiles/nested-dtd-test.xml"); } [Test] [ExpectedException (typeof (XmlException))] public void NotAllowedCharRef () { string xml = "<root>&#0;</root>"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); xtr.Normalization = true; xtr.Read (); xtr.Read (); xtr.Close (); } [Test] public void NotAllowedCharRefButPassNormalizationFalse () { string xml = "<root>&#0;</root>"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); xtr.Read (); xtr.Read (); xtr.Close (); } [Test] [ExpectedException (typeof (XmlException))] [Ignore ("MS.NET 1.0 does not pass this test. The related spec is XML rec. 4.1")] public void UndeclaredEntityInIntSubsetOnlyXml () { string ent2 = "<!ENTITY ent2 '<foo/><foo/>'>]>"; string dtd = "<!DOCTYPE root[<!ELEMENT root (#PCDATA|foo)*>" + ent2; string xml = dtd + "<root>&ent;&ent2;</root>"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); while (!xtr.EOF) xtr.Read (); xtr.Close (); } [Test] [ExpectedException (typeof (XmlException))] [Ignore ("MS.NET 1.0 does not pass this test. The related spec is XML rec. 4.1")] public void UndeclaredEntityInStandaloneXml () { string ent2 = "<!ENTITY ent2 '<foo/><foo/>'>]>"; string dtd = "<!DOCTYPE root[<!ELEMENT root (#PCDATA|foo)*>" + ent2; string xml = "<?xml version='1.0' standalone='yes' ?>" + dtd + "<root>&ent;</root>"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); while (!xtr.EOF) xtr.Read (); xtr.Close (); } [Test] public void ExpandParameterEntity () { string ent = "<!ENTITY foo \"foo-def\">"; string pe = "<!ENTITY % pe '" + ent + "'>"; string eldecl = "<!ELEMENT root ANY>"; string dtd = "<!DOCTYPE root[" + eldecl + pe + "%pe;]>"; string xml = dtd + "<root/>"; XmlDocument doc = new XmlDocument (); doc.LoadXml (xml); XmlEntity foo = doc.DocumentType.Entities.GetNamedItem ("foo") as XmlEntity; Assert.IsNotNull (foo); Assert.AreEqual ("foo-def", foo.InnerText); } [Test] public void IfNamespacesThenProhibitedAttributes () { string xml = @"<foo _1='1' xmlns:x='urn:x' x:_1='1' />"; XmlDocument doc = new XmlDocument (); doc.LoadXml (xml); } [Test] public void ReadBase64 () { byte [] bytes = new byte [] {4,14,54,114,134,184,254,255}; string base64 = "<root><foo>BA42coa44</foo></root>"; XmlTextReader xtr = new XmlTextReader (base64, XmlNodeType.Document, null); byte [] bytes2 = new byte [10]; xtr.Read (); // root xtr.Read (); // foo this.AssertNodeValues (xtr, XmlNodeType.Element, 1, false, "foo", String.Empty, "foo", String.Empty, String.Empty, 0); Assert.AreEqual (6, xtr.ReadBase64 (bytes2, 0, 10)); this.AssertNodeValues (xtr, XmlNodeType.EndElement, 0, false, "root", String.Empty, "root", String.Empty, String.Empty, 0); Assert.IsTrue (!xtr.Read ()); Assert.AreEqual (4, bytes2 [0]); Assert.AreEqual (14, bytes2 [1]); Assert.AreEqual (54, bytes2 [2]); Assert.AreEqual (114, bytes2 [3]); Assert.AreEqual (134, bytes2 [4]); Assert.AreEqual (184, bytes2 [5]); Assert.AreEqual (0, bytes2 [6]); xtr.Close (); xtr = new XmlTextReader (base64, XmlNodeType.Document, null); bytes2 = new byte [10]; xtr.Read (); // root xtr.Read (); // foo this.AssertNodeValues (xtr, XmlNodeType.Element, 1, false, "foo", String.Empty, "foo", String.Empty, String.Empty, 0); // Read less than 4 (i.e. one Base64 block) Assert.AreEqual (1, xtr.ReadBase64 (bytes2, 0, 1)); this.AssertNodeValues (xtr, XmlNodeType.Element, 1, false, "foo", String.Empty, "foo", String.Empty, String.Empty, 0); Assert.AreEqual (4, bytes2 [0]); Assert.AreEqual (5, xtr.ReadBase64 (bytes2, 0, 10)); this.AssertNodeValues (xtr, XmlNodeType.EndElement, 0, false, "root", String.Empty, "root", String.Empty, String.Empty, 0); Assert.IsTrue (!xtr.Read ()); Assert.AreEqual (14, bytes2 [0]); Assert.AreEqual (54, bytes2 [1]); Assert.AreEqual (114, bytes2 [2]); Assert.AreEqual (134, bytes2 [3]); Assert.AreEqual (184, bytes2 [4]); Assert.AreEqual (0, bytes2 [5]); while (!xtr.EOF) xtr.Read (); xtr.Close (); } [Test] public void ReadBase64Test2 () { string xml = "<root/>"; XmlTextReader xtr = new XmlTextReader (new StringReader (xml)); xtr.Read (); byte [] data = new byte [1]; xtr.ReadBase64 (data, 0, 1); while (!xtr.EOF) xtr.Read (); xml = "<root></root>"; xtr = new XmlTextReader (new StringReader (xml)); xtr.Read (); xtr.ReadBase64 (data, 0, 1); while (!xtr.EOF) xtr.Read (); } [Test] [ExpectedException (typeof (XmlException))] public void CheckNamespaceValidity1 () { string xml = "<x:root />"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); xtr.Read (); } [Test] [ExpectedException (typeof (XmlException))] public void CheckNamespaceValidity2 () { string xml = "<root x:attr='val' />"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); xtr.Read (); } [Test] public void NamespaceFalse () { string xml = "<x:root />"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); xtr.Namespaces = false; xtr.Read (); } [Test] public void NormalizationLineEnd () { string s = "One\rtwo\nthree\r\nfour"; string t = "<hi><![CDATA[" + s + "]]></hi>"; XmlTextReader r = new XmlTextReader (new StringReader (t)); r.WhitespaceHandling = WhitespaceHandling.Significant; r.Normalization = true; s = r.ReadElementString ("hi"); Assert.AreEqual ("One\ntwo\nthree\nfour", s); } [Test] public void NormalizationAttributes () { // does not normalize attribute values. StringReader sr = new StringReader ("<!DOCTYPE root [<!ELEMENT root EMPTY><!ATTLIST root attr ID #IMPLIED>]><root attr=' value '/>"); XmlTextReader xtr = new XmlTextReader (sr); xtr.Normalization = true; xtr.Read (); xtr.Read (); xtr.MoveToFirstAttribute (); Assert.AreEqual (" value ", xtr.Value); } [Test] public void CloseIsNotAlwaysEOF () { // See bug #63505 XmlTextReader xtr = new XmlTextReader ( new StringReader ("<a></a><b></b>")); xtr.Close (); Assert.IsTrue (!xtr.EOF); // Close() != EOF } [Test] public void CloseIsNotAlwaysEOF2 () { XmlTextReader xtr = new XmlTextReader ("Test/XmlFiles/simple.xml"); xtr.Close (); Assert.IsTrue (!xtr.EOF); // Close() != EOF } [Test] public void IXmlLineInfo () { // See bug #63507 XmlTextReader aux = new XmlTextReader ( new StringReader ("<all><hello></hello><bug></bug></all>")); Assert.AreEqual (0, aux.LineNumber); Assert.AreEqual (0, aux.LinePosition); aux.MoveToContent(); Assert.AreEqual (1, aux.LineNumber); Assert.AreEqual (2, aux.LinePosition); aux.Read(); Assert.AreEqual (1, aux.LineNumber); Assert.AreEqual (7, aux.LinePosition); aux.ReadOuterXml(); Assert.AreEqual (1, aux.LineNumber); Assert.AreEqual (22, aux.LinePosition); aux.ReadInnerXml(); Assert.AreEqual (1, aux.LineNumber); Assert.AreEqual (34, aux.LinePosition); aux.Read(); Assert.AreEqual (1, aux.LineNumber); Assert.AreEqual (38, aux.LinePosition); aux.Close(); Assert.AreEqual (0, aux.LineNumber); Assert.AreEqual (0, aux.LinePosition); } [Test] public void AttributeNormalizationWrapped () { // When XmlValidatingReader there used to be a problem. string xml = "<root attr=' value\nstring' />"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); xtr.Normalization = true; XmlValidatingReader xvr = new XmlValidatingReader (xtr); xvr.Read (); xvr.MoveToFirstAttribute (); Assert.AreEqual (" value string", xvr.Value); } [Test] [ExpectedException (typeof (XmlException))] public void ProhibitDtd () { XmlTextReader xtr = new XmlTextReader ("<!DOCTYPE root []><root/>", XmlNodeType.Document, null); xtr.ProhibitDtd = true; while (!xtr.EOF) xtr.Read (); } #if NET_2_0 [Test] public void Settings () { XmlTextReader xtr = new XmlTextReader ("<root/>", XmlNodeType.Document, null); Assert.IsNull (xtr.Settings); } // Copied from XmlValidatingReaderTests.cs [Test] public void ExpandEntity () { string intSubset = "<!ELEMENT root (#PCDATA)><!ATTLIST root foo CDATA 'foo-def' bar CDATA 'bar-def'><!ENTITY ent 'entity string'>"; string dtd = "<!DOCTYPE root [" + intSubset + "]>"; string xml = dtd + "<root foo='&ent;' bar='internal &ent; value'>&ent;</root>"; XmlTextReader dvr = new XmlTextReader (xml, XmlNodeType.Document, null); dvr.EntityHandling = EntityHandling.ExpandEntities; dvr.Read (); // DTD dvr.Read (); Assert.AreEqual (XmlNodeType.Element, dvr.NodeType); Assert.AreEqual ("root", dvr.Name); Assert.IsTrue (dvr.MoveToFirstAttribute ()); Assert.AreEqual ("foo", dvr.Name); Assert.AreEqual ("entity string", dvr.Value); Assert.IsTrue (dvr.MoveToNextAttribute ()); Assert.AreEqual ("bar", dvr.Name); Assert.AreEqual ("internal entity string value", dvr.Value); Assert.AreEqual ("entity string", dvr.ReadString ()); } [Test] public void PreserveEntity () { string intSubset = "<!ELEMENT root EMPTY><!ATTLIST root foo CDATA 'foo-def' bar CDATA 'bar-def'><!ENTITY ent 'entity string'>"; string dtd = "<!DOCTYPE root [" + intSubset + "]>"; string xml = dtd + "<root foo='&ent;' bar='internal &ent; value' />"; XmlTextReader dvr = new XmlTextReader (xml, XmlNodeType.Document, null); dvr.EntityHandling = EntityHandling.ExpandCharEntities; dvr.Read (); // DTD dvr.Read (); Assert.AreEqual (XmlNodeType.Element, dvr.NodeType); Assert.AreEqual ("root", dvr.Name); Assert.IsTrue (dvr.MoveToFirstAttribute ()); Assert.AreEqual ("foo", dvr.Name); // MS BUG: it returns "entity string", however, entity should not be exanded. Assert.AreEqual ("&ent;", dvr.Value); // ReadAttributeValue() Assert.IsTrue (dvr.ReadAttributeValue ()); Assert.AreEqual (XmlNodeType.EntityReference, dvr.NodeType); Assert.AreEqual ("ent", dvr.Name); Assert.AreEqual ("", dvr.Value); Assert.IsTrue (!dvr.ReadAttributeValue ()); // bar Assert.IsTrue (dvr.MoveToNextAttribute ()); Assert.AreEqual ("bar", dvr.Name); Assert.AreEqual ("internal &ent; value", dvr.Value); // ReadAttributeValue() Assert.IsTrue (dvr.ReadAttributeValue ()); Assert.AreEqual (XmlNodeType.Text, dvr.NodeType); Assert.AreEqual ("", dvr.Name); Assert.AreEqual ("internal ", dvr.Value); Assert.IsTrue (dvr.ReadAttributeValue ()); Assert.AreEqual (XmlNodeType.EntityReference, dvr.NodeType); Assert.AreEqual ("ent", dvr.Name); Assert.AreEqual ("", dvr.Value); Assert.IsTrue (dvr.ReadAttributeValue ()); Assert.AreEqual (XmlNodeType.Text, dvr.NodeType); Assert.AreEqual ("", dvr.Name); Assert.AreEqual (" value", dvr.Value); } [Test] [ExpectedException (typeof (XmlException))] public void ExpandEntityRejectsUndeclaredEntityAttr () { XmlTextReader xtr = new XmlTextReader ("<!DOCTYPE root SYSTEM 'foo.dtd'><root attr='&rnt;'>&rnt;</root>", XmlNodeType.Document, null); xtr.EntityHandling = EntityHandling.ExpandEntities; xtr.XmlResolver = null; xtr.Read (); xtr.Read (); // attribute entity 'rnt' is undeclared } [Test] [ExpectedException (typeof (XmlException))] public void ExpandEntityRejectsUndeclaredEntityContent () { XmlTextReader xtr = new XmlTextReader ("<!DOCTYPE root SYSTEM 'foo.dtd'><root>&rnt;</root>", XmlNodeType.Document, null); xtr.EntityHandling = EntityHandling.ExpandEntities; xtr.XmlResolver = null; xtr.Read (); xtr.Read (); xtr.Read (); // content entity 'rnt' is undeclared } // mostly copied from XmlValidatingReaderTests. [Test] public void ResolveEntity () { string ent1 = "<!ENTITY ent 'entity string'>"; string ent2 = "<!ENTITY ent2 '<foo/><foo/>'>]>"; string dtd = "<!DOCTYPE root[<!ELEMENT root (#PCDATA|foo)*>" + ent1 + ent2; string xml = dtd + "<root>&ent;&ent2;</root>"; XmlTextReader dvr = new XmlTextReader (xml, XmlNodeType.Document, null); dvr.EntityHandling = EntityHandling.ExpandCharEntities; dvr.Read (); // DTD dvr.Read (); // root dvr.Read (); // &ent; Assert.AreEqual (XmlNodeType.EntityReference, dvr.NodeType); Assert.AreEqual (1, dvr.Depth); dvr.ResolveEntity (); // It is still entity reference. Assert.AreEqual (XmlNodeType.EntityReference, dvr.NodeType); dvr.Read (); Assert.AreEqual (XmlNodeType.Text, dvr.NodeType); Assert.AreEqual (2, dvr.Depth); Assert.AreEqual ("entity string", dvr.Value); dvr.Read (); Assert.AreEqual (XmlNodeType.EndEntity, dvr.NodeType); Assert.AreEqual (1, dvr.Depth); Assert.AreEqual ("", dvr.Value); dvr.Read (); // &ent2; Assert.AreEqual (XmlNodeType.EntityReference, dvr.NodeType); Assert.AreEqual (1, dvr.Depth); dvr.ResolveEntity (); // It is still entity reference. Assert.AreEqual (XmlNodeType.EntityReference, dvr.NodeType); // It now became element node. dvr.Read (); Assert.AreEqual (XmlNodeType.Element, dvr.NodeType); Assert.AreEqual (2, dvr.Depth); } // mostly copied from XmlValidatingReaderTests. [Test] public void ResolveEntity2 () { string ent1 = "<!ENTITY ent 'entity string'>"; string ent2 = "<!ENTITY ent2 '<foo/><foo/>'>]>"; string dtd = "<!DOCTYPE root[<!ELEMENT root (#PCDATA|foo)*>" + ent1 + ent2; string xml = dtd + "<root>&ent3;&ent2;</root>"; XmlTextReader dvr = new XmlTextReader (xml, XmlNodeType.Document, null); dvr.EntityHandling = EntityHandling.ExpandCharEntities; dvr.Read (); // DTD dvr.Read (); // root dvr.Read (); // &ent3; Assert.AreEqual (XmlNodeType.EntityReference, dvr.NodeType); // ent3 does not exists in this dtd. Assert.AreEqual (XmlNodeType.EntityReference, dvr.NodeType); try { dvr.ResolveEntity (); Assert.Fail ("Attempt to resolve undeclared entity should fail."); } catch (XmlException) { } } #endif [Test] public void SurrogatePair () { string xml = @"<!DOCTYPE test [<!ELEMENT test ANY> <!ENTITY % a '<!ENTITY ref " + "\"\uF090\u8080\"" + @">'> %a; ]> <test>&ref;</test>"; XmlValidatingReader r = new XmlValidatingReader (xml, XmlNodeType.Document, null); r.Read (); r.Read (); r.Read (); r.Read (); Assert.AreEqual (0xf090, (int) r.Value [0], "#1"); Assert.AreEqual (0x8080, (int) r.Value [1], "#1"); } [Test] [ExpectedException (typeof (XmlException))] public void EntityDeclarationNotWF () { string xml = @"<!DOCTYPE doc [ <!ELEMENT doc (#PCDATA)> <!ENTITY e ''> <!ENTITY e '<foo&>'> ]> <doc>&e;</doc> "; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); xtr.Read (); } [Test] // bug #76102 public void SurrogateAtReaderByteCache () { XmlTextReader xtr = null; try { xtr = new XmlTextReader (File.OpenText ("Test/XmlFiles/76102.xml")); while (!xtr.EOF) xtr.Read (); } finally { if (xtr != null) xtr.Close (); } } [Test] // bug #76247 public void SurrogateRoundtrip () { byte [] data = new byte [] {0x3c, 0x61, 0x3e, 0xf0, 0xa8, 0xa7, 0x80, 0x3c, 0x2f, 0x61, 0x3e}; XmlTextReader xtr = new XmlTextReader ( new MemoryStream (data)); xtr.Read (); string line = xtr.ReadString (); int [] arr = new int [line.Length]; for (int i = 0; i < line.Length; i++) arr [i] = (int) line [i]; Assert.AreEqual (new int [] {0xd862, 0xddc0}, arr); } [Test] [ExpectedException (typeof (XmlException))] public void RejectEmptyNamespaceWithNonEmptyPrefix () { XmlTextReader xtr = new XmlTextReader ("<root xmlns:my='' />", XmlNodeType.Document, null); xtr.Read (); } [Test] public void EncodingProperty () { string xml = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<root>\n<node>\nvalue\n</node>\n</root>"; XmlTextReader xr = new XmlTextReader (xml, XmlNodeType.Document, null); Assert.IsNull (xr.Encoding, "#1"); xr.Read (); Assert.AreEqual (Encoding.Unicode, xr.Encoding, "#2"); } [Test] public void WhitespaceHandlingSignificant () { XmlTextReader xtr = new XmlTextReader ("<root> <child xml:space='preserve'> <descendant xml:space='default'> </descendant> </child><child xml:space='default'> </child> </root>", XmlNodeType.Document, null); xtr.WhitespaceHandling = WhitespaceHandling.Significant; xtr.Read (); // root xtr.Read (); // child. skip whitespaces Assert.AreEqual (XmlNodeType.Element, xtr.NodeType, "#1"); xtr.Read (); // significant whitespaces Assert.AreEqual (XmlNodeType.SignificantWhitespace, xtr.NodeType, "#2"); xtr.Read (); Assert.AreEqual ("descendant", xtr.LocalName, "#3"); xtr.Read (); // end of descendant. skip whitespaces Assert.AreEqual (XmlNodeType.EndElement, xtr.NodeType, "#4"); xtr.Read (); // significant whitespaces Assert.AreEqual (XmlNodeType.SignificantWhitespace, xtr.NodeType, "#5"); xtr.Read (); // end of child xtr.Read (); // child xtr.Read (); // end of child. skip whitespaces Assert.AreEqual (XmlNodeType.EndElement, xtr.NodeType, "#6"); xtr.Read (); // end of root. skip whitespaces Assert.AreEqual (XmlNodeType.EndElement, xtr.NodeType, "#7"); } [Test] public void WhitespaceHandlingNone () { XmlTextReader xtr = new XmlTextReader ("<root> <child xml:space='preserve'> <descendant xml:space='default'> </descendant> </child><child xml:space='default'> </child> </root>", XmlNodeType.Document, null); xtr.WhitespaceHandling = WhitespaceHandling.None; xtr.Read (); // root xtr.Read (); // child. skip whitespaces Assert.AreEqual (XmlNodeType.Element, xtr.NodeType, "#1"); xtr.Read (); // descendant. skip significant whitespaces Assert.AreEqual ("descendant", xtr.LocalName, "#2"); xtr.Read (); // end of descendant. skip whitespaces Assert.AreEqual (XmlNodeType.EndElement, xtr.NodeType, "#3"); xtr.Read (); // end of child. skip significant whitespaces xtr.Read (); // child xtr.Read (); // end of child. skip whitespaces Assert.AreEqual (XmlNodeType.EndElement, xtr.NodeType, "#6"); xtr.Read (); // end of root. skip whitespaces Assert.AreEqual (XmlNodeType.EndElement, xtr.NodeType, "#7"); } [Test] public void WhitespacesAfterTextDeclaration () { XmlTextReader xtr = new XmlTextReader ( "<?xml version='1.0' encoding='utf-8' ?> <x/>", XmlNodeType.Element, null); xtr.Read (); Assert.AreEqual (XmlNodeType.Whitespace, xtr.NodeType, "#1"); Assert.AreEqual (" ", xtr.Value, "#2"); } // bug #79683 [Test] public void NotationPERef () { string xml = "<!DOCTYPE root SYSTEM 'Test/XmlFiles/79683.dtd'><root/>"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); while (!xtr.EOF) xtr.Read (); } [Test] // bug #80308 public void ReadCharsNested () { char[] buf = new char [4]; string xml = "<root><text>AAAA</text></root>"; string [] strings = new string [] { "<tex", "t>AA", "AA</", "text", ">"}; XmlTextReader r = new XmlTextReader ( xml, XmlNodeType.Document, null); int c, n = 0; while (r.Read ()) if (r.NodeType == XmlNodeType.Element) while ((c = r.ReadChars (buf, 0, buf.Length)) > 0) Assert.AreEqual (strings [n++], new string (buf, 0, c), "at " + n); Assert.AreEqual (5, n, "total lines"); } [Test] // bug #81294 public void DtdCommentContainsCloseBracket () { string xml = @"<!DOCTYPE kanjidic2 [<!ELEMENT kanjidic2 EMPTY> <!-- ] --> ]><kanjidic2 />"; XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null); while (!xtr.EOF) xtr.Read (); } [Test] public void CloseTagAfterTextWithTrailingCRNormalized () // bug #398374 { string xml = "<root><foo>some text\r</foo></root>"; XmlTextReader r = new XmlTextReader (xml, XmlNodeType.Document, null); r.Normalization = true; while (!r.EOF) r.Read (); } [Test] public void Bug412657 () { string s = "<Verifier id='SimpleIntVerifier'/>"; MemoryStream stream = new MemoryStream (Encoding.UTF8.GetBytes(s)); XmlParserContext ctx = new XmlParserContext (null, null, null, XmlSpace.Default); Assert.IsNull (ctx.NamespaceManager, "#1"); Assert.IsNull (ctx.NameTable, "#2"); XmlReader reader = new XmlTextReader (stream, XmlNodeType.Element, ctx); Assert.IsNull (ctx.NamespaceManager, "#1"); reader.Read (); // should not raise NRE. } [Test] [ExpectedException (typeof (XmlException))] public void InvalidUTF () { byte [] data = new byte [] {0x4d, 0x53, 0x43, 0x46, 0x00, 0x00, 0x00, 0x00, 0xab, 0x0a}; XmlTextReader xtr = new XmlTextReader ( new MemoryStream (data)); xtr.Read (); } [Test] public void ParserContextNullNameTable () { string input = "<?xml version='1.0' encoding='UTF-8'?><plist version='1.0'></plist>"; XmlParserContext context = new XmlParserContext (null, null, null, XmlSpace.None); // null NameTable XmlTextReader xtr = new XmlTextReader (input, XmlNodeType.Document, context); while (!xtr.EOF) xtr.Read (); } [Test] public void ParsingWithNSMgrSubclass () { XmlNamespaceManager nsMgr = new XmlNamespaceManager (new NameTable ()); nsMgr.AddNamespace ("foo", "bar"); XmlParserContext inputContext = new XmlParserContext (null, nsMgr, null, XmlSpace.None); XmlReader xr = XmlReader.Create (new StringReader ("<empty/>"), new XmlReaderSettings (), inputContext); XmlNamespaceManager aMgr = new MyNS (xr); XmlParserContext inputContext2 = new XmlParserContext(null, aMgr, null, XmlSpace.None); XmlReader xr2 = XmlReader.Create (new StringReader ("<foo:haha>namespace test</foo:haha>"), new XmlReaderSettings (), inputContext2); while (xr2.Read ()) {} } // The MyNS subclass chains namespace lookups class MyNS : XmlNamespaceManager { private XmlReader xr; public MyNS (XmlReader xr) : base (xr.NameTable) { this.xr = xr; } public override string LookupNamespace (string prefix) { string str = base.LookupNamespace (prefix); if (!string.IsNullOrEmpty (str)) return str; if (xr != null) return xr.LookupNamespace (prefix); return String.Empty; } } [Test] public void EmptyXmlBase () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<root xml:base='' />"); } [Test] public void GetAttribute () { StringReader sr = new StringReader("<rootElement myAttribute=\"the value\"></rootElement>"); using (XmlReader reader = XmlReader.Create(sr)) { reader.Read (); Assert.AreEqual (reader.GetAttribute("myAttribute", null), "the value", "#1"); } } [Test] // bug #675384 public void ReadCharsWithVeryLimitedBuffer () { var r = new XmlTextReader ("<root><child>a</child></root>", XmlNodeType.Document, null); r.MoveToContent (); char [] buff = new char [1]; int read = 0; var sb = new StringBuilder (); do { read = r.ReadChars (buff, 0, buff.Length); if (read > 0) sb.Append (buff [0]); } while (read > 0); Assert.AreEqual ("<child>a</child>", sb.ToString (), "#1"); } [Test] public void BOMLessUTF16Detection () // bug #674580 { var ms = new MemoryStream (Encoding.Unicode.GetBytes ("<root />")); var xtr = new XmlTextReader (ms); xtr.Read (); } } }
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.Services.Agent { [ServiceLocator(Default = typeof(JobServerQueue))] public interface IJobServerQueue : IAgentService { Task ShutdownAsync(); void Start(JobRequestMessage jobRequest); void QueueWebConsoleLine(string line); void QueueFileUpload(Guid timelineId, Guid timelineRecordId, string type, string name, string path, bool deleteSource); void QueueTimelineRecordUpdate(Guid timelineId, TimelineRecord timelineRecord); } public sealed class JobServerQueue : AgentService, IJobServerQueue { // Default delay for Dequeue process private static readonly TimeSpan _delayForWebConsoleLineDequeue = TimeSpan.FromMilliseconds(200); private static readonly TimeSpan _delayForTimelineUpdateDequeue = TimeSpan.FromMilliseconds(500); private static readonly TimeSpan _delayForFileUploadDequeue = TimeSpan.FromMilliseconds(1000); // Job message information private Guid _scopeIdentifier; private string _hubName; private Guid _planId; private Guid _jobTimelineId; private Guid _jobTimelineRecordId; // queue for web console line private readonly ConcurrentQueue<string> _webConsoleLineQueue = new ConcurrentQueue<string>(); // queue for file upload (log file or attachment) private readonly ConcurrentQueue<UploadFileInfo> _fileUploadQueue = new ConcurrentQueue<UploadFileInfo>(); // queue for timeline or timeline record update (one queue per timeline) private readonly ConcurrentDictionary<Guid, ConcurrentQueue<TimelineRecord>> _timelineUpdateQueue = new ConcurrentDictionary<Guid, ConcurrentQueue<TimelineRecord>>(); // indicate how many timelines we have, we will process _timelineUpdateQueue base on the order of timeline in this list private readonly List<Guid> _allTimelines = new List<Guid>(); // bufferd timeline records that fail to update private readonly Dictionary<Guid, List<TimelineRecord>> _bufferedRetryRecords = new Dictionary<Guid, List<TimelineRecord>>(); // Task for each queue's dequeue process private Task _webConsoleLineDequeueTask; private Task _fileUploadDequeueTask; private Task _timelineUpdateDequeueTask; // common private IJobServer _jobServer; private Task[] _allDequeueTasks; private readonly TaskCompletionSource<int> _jobCompletionSource = new TaskCompletionSource<int>(); private bool _queueInProcess = false; public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _jobServer = hostContext.GetService<IJobServer>(); } public void Start(JobRequestMessage jobRequest) { Trace.Entering(); if (_queueInProcess) { Trace.Info("No-opt, all queue process tasks are running."); return; } ArgUtil.NotNull(jobRequest, nameof(jobRequest)); ArgUtil.NotNull(jobRequest.Plan, nameof(jobRequest.Plan)); ArgUtil.NotNull(jobRequest.Timeline, nameof(jobRequest.Timeline)); _scopeIdentifier = jobRequest.Plan.ScopeIdentifier; _hubName = jobRequest.Plan.PlanType; _planId = jobRequest.Plan.PlanId; _jobTimelineId = jobRequest.Timeline.Id; _jobTimelineRecordId = jobRequest.JobId; // Server already create the job timeline _timelineUpdateQueue[_jobTimelineId] = new ConcurrentQueue<TimelineRecord>(); _allTimelines.Add(_jobTimelineId); // Start three dequeue task Trace.Info("Start process web console line queue."); _webConsoleLineDequeueTask = ProcessWebConsoleLinesQueueAsync(); Trace.Info("Start process file upload queue."); _fileUploadDequeueTask = ProcessFilesUploadQueueAsync(); Trace.Info("Start process timeline update queue."); _timelineUpdateDequeueTask = ProcessTimelinesUpdateQueueAsync(); _allDequeueTasks = new Task[] { _webConsoleLineDequeueTask, _fileUploadDequeueTask, _timelineUpdateDequeueTask }; _queueInProcess = true; } public async Task ShutdownAsync() { if (!_queueInProcess) { Trace.Info("No-opt, all queue process tasks have been stopped."); } Trace.Info("Fire signal to shutdown all queues."); _jobCompletionSource.TrySetResult(0); await Task.WhenAll(_allDequeueTasks); _queueInProcess = false; Trace.Info("All queue process task stopped."); //Drain the queue List<Exception> queueShutdownExceptions = new List<Exception>(); try { Trace.Verbose("Draining web console line queue."); await ProcessWebConsoleLinesQueueAsync(runOnce: true); Trace.Info("Web console line queue drained."); } catch (Exception ex) { Trace.Error("Drain web console line queue fail with: {0}", ex.Message); queueShutdownExceptions.Add(ex); } try { Trace.Verbose("Draining file upload queue."); await ProcessFilesUploadQueueAsync(runOnce: true); Trace.Info("File upload queue drained."); } catch (Exception ex) { Trace.Error("Drain file upload queue fail with: {0}", ex.Message); queueShutdownExceptions.Add(ex); } try { Trace.Verbose("Draining timeline update queue."); await ProcessTimelinesUpdateQueueAsync(runOnce: true); Trace.Info("Timeline update queue drained."); } catch (Exception ex) { Trace.Error("Drain timeline update queue fail with: {0}", ex.Message); queueShutdownExceptions.Add(ex); } if (queueShutdownExceptions.Count > 0) { throw new AggregateException("Catch exceptions during queue shutdown.", queueShutdownExceptions); } else { Trace.Info("All queue process tasks have been stopped, and all queues are drained."); } } public void QueueWebConsoleLine(string line) { Trace.Verbose("Enqueue web console line queue: {0}", line); _webConsoleLineQueue.Enqueue(line); } public void QueueFileUpload(Guid timelineId, Guid timelineRecordId, string type, string name, string path, bool deleteSource) { ArgUtil.NotEmpty(timelineId, nameof(timelineId)); ArgUtil.NotEmpty(timelineRecordId, nameof(timelineRecordId)); // all parameter not null, file path exist. var newFile = new UploadFileInfo() { TimelineId = timelineId, TimelineRecordId = timelineRecordId, Type = type, Name = name, Path = path, DeleteSource = deleteSource }; Trace.Verbose("Enqueue file upload queue: file '{0}' attach to record {1}", newFile.Path, timelineRecordId); _fileUploadQueue.Enqueue(newFile); } public void QueueTimelineRecordUpdate(Guid timelineId, TimelineRecord timelineRecord) { ArgUtil.NotEmpty(timelineId, nameof(timelineId)); ArgUtil.NotNull(timelineRecord, nameof(timelineRecord)); ArgUtil.NotEmpty(timelineRecord.Id, nameof(timelineRecord.Id)); _timelineUpdateQueue.TryAdd(timelineId, new ConcurrentQueue<TimelineRecord>()); Trace.Verbose("Enqueue timeline {0} update queue: {1}", timelineId, timelineRecord.Id); _timelineUpdateQueue[timelineId].Enqueue(timelineRecord.Clone()); } private async Task ProcessWebConsoleLinesQueueAsync(bool runOnce = false) { while (!_jobCompletionSource.Task.IsCompleted || runOnce) { List<List<string>> batchedLines = new List<List<string>>(); List<string> currentBatch = new List<string>(); string line; while (_webConsoleLineQueue.TryDequeue(out line)) { if (!string.IsNullOrEmpty(line) && line.Length > 1024) { Trace.Verbose("Web console line is more than 1024 chars, truncate to first 1024 chars"); line = $"{line.Substring(0, 1024)}..."; } currentBatch.Add(line); // choose 100 lines since the whole web console UI will only shows about 40 lines in a 15" monitor. if (currentBatch.Count > 100) { batchedLines.Add(currentBatch.ToList()); currentBatch.Clear(); } // process at most about 500 lines of web console line during regular timer dequeue task. if (!runOnce && batchedLines.Count > 5) { break; } } if (currentBatch.Count > 0) { batchedLines.Add(currentBatch.ToList()); currentBatch.Clear(); } if (batchedLines.Count > 0) { List<Exception> webConsoleLinePostExceptions = new List<Exception>(); foreach (var batch in batchedLines) { try { // we will not requeue failed batch, since the web console lines are time sensitive. await _jobServer.AppendTimelineRecordFeedAsync(_scopeIdentifier, _hubName, _planId, _jobTimelineId, _jobTimelineRecordId, batch, default(CancellationToken)); } catch (Exception ex) { Trace.Info("Catch exception during append web console line, keep going since the process is best effort. Due with exception when all batches finish."); webConsoleLinePostExceptions.Add(ex); } } Trace.Info("Try to append {0} batches web console lines, success rate: {1}/{0}.", batchedLines.Count, batchedLines.Count - webConsoleLinePostExceptions.Count); if (webConsoleLinePostExceptions.Count > 0) { AggregateException ex = new AggregateException("Catch exception during append web console line.", webConsoleLinePostExceptions); if (!runOnce) { Trace.Verbose("Catch exception during process web console line queue, keep going since the process is best effort."); Trace.Error(ex); } else { Trace.Error("Catch exception during drain web console line queue. throw aggregate exception to caller."); throw ex; } } } if (runOnce) { break; } else { await Task.Delay(_delayForWebConsoleLineDequeue); } } } private async Task ProcessFilesUploadQueueAsync(bool runOnce = false) { while (!_jobCompletionSource.Task.IsCompleted || runOnce) { List<UploadFileInfo> filesToUpload = new List<UploadFileInfo>(); UploadFileInfo dequeueFile; while (_fileUploadQueue.TryDequeue(out dequeueFile)) { filesToUpload.Add(dequeueFile); // process at most 10 file upload. if (!runOnce && filesToUpload.Count > 10) { break; } } if (filesToUpload.Count > 0) { // TODO: upload all file in parallel List<Exception> fileUploadExceptions = new List<Exception>(); foreach (var file in filesToUpload) { try { await UploadFile(file); } catch (Exception ex) { Trace.Info("Catch exception during log or attachment file upload, keep going since the process is best effort. Due with exception when all files upload."); fileUploadExceptions.Add(ex); // put the failed upload file back to queue. // TODO: figure out how should we retry paging log upload. //lock (_fileUploadQueueLock) //{ // _fileUploadQueue.Enqueue(file); //} } } Trace.Info("Try to upload {0} log files or attachments, success rate: {1}/{0}.", filesToUpload.Count, filesToUpload.Count - fileUploadExceptions.Count); if (fileUploadExceptions.Count > 0) { AggregateException ex = new AggregateException("Catch exception during upload log file or attachment.", fileUploadExceptions); if (!runOnce) { Trace.Verbose("Catch exception during process file upload queue, keep going since the process is best effort."); Trace.Error(ex); } else { Trace.Error("Catch exception during drain file upload queue queue. throw aggregate exception to caller."); throw ex; } } } if (runOnce) { break; } else { await Task.Delay(_delayForFileUploadDequeue); } } } private async Task ProcessTimelinesUpdateQueueAsync(bool runOnce = false) { while (!_jobCompletionSource.Task.IsCompleted || runOnce) { List<PendingTimelineRecord> pendingUpdates = new List<PendingTimelineRecord>(); foreach (var timeline in _allTimelines) { ConcurrentQueue<TimelineRecord> recordQueue; if (_timelineUpdateQueue.TryGetValue(timeline, out recordQueue)) { List<TimelineRecord> records = new List<TimelineRecord>(); TimelineRecord record; while (recordQueue.TryDequeue(out record)) { records.Add(record); // process at most 25 timeline records update for each timeline. if (!runOnce && records.Count > 25) { break; } } if (records.Count > 0) { pendingUpdates.Add(new PendingTimelineRecord() { TimelineId = timeline, PendingRecords = records.ToList() }); } } } if (pendingUpdates.Count > 0) { foreach (var update in pendingUpdates) { List<TimelineRecord> bufferedRecords; if (_bufferedRetryRecords.TryGetValue(update.TimelineId, out bufferedRecords)) { update.PendingRecords.InsertRange(0, bufferedRecords); } update.PendingRecords = MergeTimelineRecords(update.PendingRecords); foreach (var detailTimeline in update.PendingRecords.Where(r => r.Details != null)) { if (!_allTimelines.Contains(detailTimeline.Details.Id)) { try { Timeline newTimeline = await _jobServer.CreateTimelineAsync(_scopeIdentifier, _hubName, _planId, detailTimeline.Details.Id, default(CancellationToken)); _allTimelines.Add(newTimeline.Id); } catch (TimelineExistsException) { Trace.Info("Catch TimelineExistsException during timeline creation. Ignore the error since server already had this timeline."); _allTimelines.Add(detailTimeline.Details.Id); } catch (Exception ex) { Trace.Error(ex); } } } try { await _jobServer.UpdateTimelineRecordsAsync(_scopeIdentifier, _hubName, _planId, update.TimelineId, update.PendingRecords, default(CancellationToken)); if (_bufferedRetryRecords.Remove(update.TimelineId)) { Trace.Verbose("Cleanup buffered timeline record for timeline: {0}.", update.TimelineId); } } catch (Exception ex) { Trace.Info("Catch exception during update timeline records, try to update these timeline records next time."); Trace.Error(ex); _bufferedRetryRecords[update.TimelineId] = update.PendingRecords.ToList(); } } } if (runOnce) { break; } else { await Task.Delay(_delayForTimelineUpdateDequeue); } } } private List<TimelineRecord> MergeTimelineRecords(List<TimelineRecord> timelineRecords) { if (timelineRecords == null || timelineRecords.Count <= 1) { return timelineRecords; } Dictionary<Guid, TimelineRecord> dict = new Dictionary<Guid, TimelineRecord>(); foreach (TimelineRecord rec in timelineRecords) { if (rec == null) { continue; } TimelineRecord timelineRecord; if (dict.TryGetValue(rec.Id, out timelineRecord)) { // Merge rec into timelineRecord timelineRecord.CurrentOperation = rec.CurrentOperation ?? timelineRecord.CurrentOperation; timelineRecord.Details = rec.Details ?? timelineRecord.Details; timelineRecord.FinishTime = rec.FinishTime ?? timelineRecord.FinishTime; timelineRecord.Log = rec.Log ?? timelineRecord.Log; timelineRecord.Name = rec.Name ?? timelineRecord.Name; timelineRecord.PercentComplete = rec.PercentComplete ?? timelineRecord.PercentComplete; timelineRecord.RecordType = rec.RecordType ?? timelineRecord.RecordType; timelineRecord.Result = rec.Result ?? timelineRecord.Result; timelineRecord.ResultCode = rec.ResultCode ?? timelineRecord.ResultCode; timelineRecord.StartTime = rec.StartTime ?? timelineRecord.StartTime; timelineRecord.State = rec.State ?? timelineRecord.State; timelineRecord.WorkerName = rec.WorkerName ?? timelineRecord.WorkerName; if (rec.ErrorCount != null && rec.ErrorCount > 0) { timelineRecord.ErrorCount = rec.ErrorCount; } if (rec.WarningCount != null && rec.WarningCount > 0) { timelineRecord.WarningCount = rec.WarningCount; } if (rec.Issues.Count > 0) { timelineRecord.Issues.Clear(); timelineRecord.Issues.AddRange(rec.Issues.Select(i => i.Clone())); } } else { dict.Add(rec.Id, rec); } } var mergedRecords = dict.Values.ToList(); Trace.Verbose("Merged Timeline records"); foreach (var record in mergedRecords) { Trace.Verbose($" Record: t={record.RecordType}, n={record.Name}, s={record.State}, st={record.StartTime}, {record.PercentComplete}%, ft={record.FinishTime}, r={record.Result}: {record.CurrentOperation}"); if (record.Issues != null && record.Issues.Count > 0) { foreach (var issue in record.Issues) { String source; issue.Data.TryGetValue("sourcepath", out source); Trace.Verbose($" Issue: c={issue.Category}, t={issue.Type}, s={source ?? string.Empty}, m={issue.Message}"); } } } return mergedRecords; } private async Task UploadFile(UploadFileInfo file) { bool uploadSucceed = false; try { if (String.Equals(file.Type, CoreAttachmentType.Log, StringComparison.OrdinalIgnoreCase)) { // Create the log var taskLog = await _jobServer.CreateLogAsync(_scopeIdentifier, _hubName, _planId, new TaskLog(String.Format(@"logs\{0:D}", file.TimelineRecordId)), default(CancellationToken)); // Upload the contents using (FileStream fs = File.OpenRead(file.Path)) { var logUploaded = await _jobServer.AppendLogContentAsync(_scopeIdentifier, _hubName, _planId, taskLog.Id, fs, default(CancellationToken)); } // Create a new record and only set the Log field var attachmentUpdataRecord = new TimelineRecord() { Id = file.TimelineRecordId, Log = taskLog }; QueueTimelineRecordUpdate(file.TimelineId, attachmentUpdataRecord); } else { // Create attachment using (FileStream fs = File.OpenRead(file.Path)) { var result = await _jobServer.CreateAttachmentAsync(_scopeIdentifier, _hubName, _planId, file.TimelineId, file.TimelineRecordId, file.Type, file.Name, fs, default(CancellationToken)); } } uploadSucceed = true; } finally { if (uploadSucceed && file.DeleteSource) { try { File.Delete(file.Path); } catch (Exception ex) { Trace.Info("Catch exception during delete success uploaded file."); Trace.Error(ex); } } } } } internal class PendingTimelineRecord { public Guid TimelineId { get; set; } public List<TimelineRecord> PendingRecords { get; set; } } internal class UploadFileInfo { public Guid TimelineId { get; set; } public Guid TimelineRecordId { get; set; } public string Type { get; set; } public string Name { get; set; } public string Path { get; set; } public bool DeleteSource { get; set; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Avatar.Lure { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LureModule")] public class LureModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private readonly List<Scene> m_scenes = new List<Scene>(); private IMessageTransferModule m_TransferModule = null; private bool m_Enabled = false; public void Initialise(IConfigSource config) { if (config.Configs["Messaging"] != null) { if (config.Configs["Messaging"].GetString( "LureModule", "LureModule") == "LureModule") { m_Enabled = true; m_log.DebugFormat("[LURE MODULE]: {0} enabled", Name); } } } public void AddRegion(Scene scene) { if (!m_Enabled) return; lock (m_scenes) { m_scenes.Add(scene); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; } } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_TransferModule == null) { m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); if (m_TransferModule == null) { m_log.Error("[INSTANT MESSAGE]: No message transfer module, "+ "lures will not work!"); m_Enabled = false; m_scenes.Clear(); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; } } } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; lock (m_scenes) { m_scenes.Remove(scene); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; } } void OnNewClient(IClientAPI client) { client.OnInstantMessage += OnInstantMessage; client.OnStartLure += OnStartLure; client.OnTeleportLureRequest += OnTeleportLureRequest; } public void PostInitialise() { } public void Close() { } public string Name { get { return "LureModule"; } } public Type ReplaceableInterface { get { return null; } } public void OnInstantMessage(IClientAPI client, GridInstantMessage im) { } public void OnStartLure(byte lureType, string message, UUID targetid, IClientAPI client) { if (!(client.Scene is Scene)) return; Scene scene = (Scene)(client.Scene); ScenePresence presence = scene.GetScenePresence(client.AgentId); // Round up Z co-ordinate rather than round-down by casting. This stops tall avatars from being given // a teleport Z co-ordinate by short avatars that drops them through or embeds them in thin floors on // arrival. // // Ideally we would give the exact float position adjusting for the relative height of the two avatars // but it looks like a float component isn't possible with a parcel ID. UUID dest = Util.BuildFakeParcelID( scene.RegionInfo.RegionHandle, (uint)presence.AbsolutePosition.X, (uint)presence.AbsolutePosition.Y, (uint)Math.Ceiling(presence.AbsolutePosition.Z)); m_log.DebugFormat("TP invite with message {0}", message); GridInstantMessage m = new GridInstantMessage(scene, client.AgentId, client.FirstName+" "+client.LastName, targetid, (byte)InstantMessageDialog.RequestTeleport, false, message, dest, false, presence.AbsolutePosition, new Byte[0], true); if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(m, delegate(bool success) { }); } } public void OnTeleportLureRequest(UUID lureID, uint teleportFlags, IClientAPI client) { if (!(client.Scene is Scene)) return; Scene scene = (Scene)(client.Scene); ulong handle = 0; uint x = 128; uint y = 128; uint z = 70; Util.ParseFakeParcelID(lureID, out handle, out x, out y, out z); Vector3 position = new Vector3(); position.X = (float)x; position.Y = (float)y; position.Z = (float)z; scene.RequestTeleportLocation(client, handle, position, Vector3.Zero, teleportFlags); } private void OnGridInstantMessage(GridInstantMessage msg) { // Forward remote teleport requests // if (msg.dialog != 22) return; if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(msg, delegate(bool success) { }); } } } }
//********************************************************* // // 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 System; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { /// <summary> /// UI for the LoggingSession sample. /// </summary> public sealed partial class Scenario2 { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() MainPage rootPage = MainPage.Current; internal LoggingSessionScenario LoggingSessionScenario { get { return LoggingSessionScenario.Instance; } } public Scenario2() { // This sample UI is interested in events from // the LoggingSessionScenario class so the UI can be updated. LoggingSessionScenario.StatusChanged += LoggingSessionScenario_StatusChanged; this.InitializeComponent(); } async void LoggingSessionScenario_StatusChanged(object sender, LoggingScenarioEventArgs e) { if (e.Type == LoggingScenarioEventType.BusyStatusChanged) { UpdateControls(); } else if (e.Type == LoggingScenarioEventType.LogFileGenerated) { await AddLogFileMessageDispatch("LogFileGenerated", e.LogFilePath); } else if (e.Type == LoggingScenarioEventType.LoggingEnabledDisabled) { await AddMessageDispatch(string.Format("Logging has been {0}.", e.Enabled ? "enabled" : "disabled")); } } ScrollViewer FindScrollViewer(DependencyObject depObject) { if (depObject == null) { return null; } int countThisLevel = Windows.UI.Xaml.Media.VisualTreeHelper.GetChildrenCount(depObject); if (countThisLevel <= 0) { return null; } for (int childIndex = 0; childIndex < countThisLevel; childIndex++) { DependencyObject childDepObject = Windows.UI.Xaml.Media.VisualTreeHelper.GetChild(depObject, childIndex); if (childDepObject is ScrollViewer) { return (ScrollViewer)childDepObject; } ScrollViewer svFromChild = FindScrollViewer(childDepObject); if (svFromChild != null) { return svFromChild; } } return null; } /// <summary> /// Add a message to the UI control which displays status while the sample is running. /// </summary> /// <param name="message">The message to append to the UI log.</param> public void AddMessage(string message) { StatusMessageList.Text += message + "\r\n"; StatusMessageList.Select(StatusMessageList.Text.Length, 0); ScrollViewer svFind = FindScrollViewer(StatusMessageList); if (svFind != null) { svFind.ChangeView(null, StatusMessageList.ActualHeight, null); } } /// <summary> /// Dispatch to the UI thread and add a message to the UI control which displays status while the sample is running. /// </summary> /// <param name="message">The message to append to the UI log.</param> public async Task AddLogFileMessageDispatch(string message, string path) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => { string finalMessage; if (path != null && path.Length > 0) { var fileName = System.IO.Path.GetFileName(path); var directoryName = System.IO.Path.GetDirectoryName(path); finalMessage = message + ": " + fileName; ViewLogInfo.Text = $"Log folder: \"{directoryName}\"\r\n" + $"- To view with tracerpt: tracerpt.exe \"{path}\" -of XML -o LogFile.xml\r\n" + $"- To view with Windows Performance Toolkit (WPT):\r\n" + $" xperf -merge \"{path}\" merged.etl\r\n" + $" wpa.exe merged.etl"; } else { finalMessage = string.Format("{0}: none, nothing logged since saving the last file.", message); } AddMessage(finalMessage); }).AsTask(); } /// <summary> /// Dispatch to the UI thread and add a message to the UI log. /// </summary> /// <param name="message">The message to appened to the UI log.</param> /// <returns>The task.</returns> public async Task AddMessageDispatch(string message) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => { AddMessage(message); }).AsTask(); } /// <summary> /// Adjust UI controls based on what the sample is doing. /// </summary> private void UpdateControls() { if (LoggingSessionScenario.Instance.IsLoggingEnabled) { InputTextBlock1.Text = "Logging is enabled. Click 'Disable Logging' to disable logging. With logging enabled, you can click 'Log Messages' to use the logging API to generate log files."; EnableDisableLoggingButton.Content = "Disable Logging"; if (LoggingSessionScenario.Instance.IsBusy) { DoScenarioButton.IsEnabled = false; EnableDisableLoggingButton.IsEnabled = false; } else { DoScenarioButton.IsEnabled = true; EnableDisableLoggingButton.IsEnabled = true; } } else { InputTextBlock1.Text = "Logging is disabled. Click 'Enable Logging' to enable logging. After you enable logging you can click 'Log Messages' to use the logging API to generate log files."; EnableDisableLoggingButton.Content = "Enable Logging"; DoScenarioButton.IsEnabled = false; if (LoggingSessionScenario.Instance.IsBusy) { EnableDisableLoggingButton.IsEnabled = false; } else { EnableDisableLoggingButton.IsEnabled = true; } } } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { UpdateControls(); } /// <summary> /// Enabled/disabled logging. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event arguments.</param> private void EnableDisableLogging(object sender, RoutedEventArgs e) { LoggingSessionScenario loggingSessionScenario = LoggingSessionScenario.Instance; if (loggingSessionScenario.IsLoggingEnabled) { rootPage.NotifyUser("Disabling logging...", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Enabling logging...", NotifyType.StatusMessage); } LoggingSessionScenario.Instance.ToggleLoggingEnabledDisabled(); if (loggingSessionScenario.IsLoggingEnabled) { rootPage.NotifyUser("Logging enabled.", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Logging disabled.", NotifyType.StatusMessage); } UpdateControls(); } /// <summary> /// Run a sample scenario which logs lots of messages to produce several log files. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private async void DoScenario(object sender, RoutedEventArgs e) { DoScenarioButton.IsEnabled = false; rootPage.NotifyUser("Scenario running...", NotifyType.StatusMessage); await LoggingSessionScenario.DoScenarioAsync(); rootPage.NotifyUser("Scenario finished.", NotifyType.StatusMessage); DoScenarioButton.IsEnabled = true; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; 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 StudentSystem.Api.Areas.HelpPage.ModelDescriptions; using StudentSystem.Api.Areas.HelpPage.Models; namespace StudentSystem.Api.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; } if (complexTypeDescription != null) { 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 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); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using CultureInfo = System.Globalization.CultureInfo; using System.Security; using System.IO; using StringBuilder = System.Text.StringBuilder; using System.Configuration.Assemblies; using StackCrawlMark = System.Threading.StackCrawlMark; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; using System.Diagnostics.Contracts; namespace System.Reflection { internal class RuntimeAssembly : Assembly { internal RuntimeAssembly() { throw new NotSupportedException(); } #region private data members private event ModuleResolveEventHandler _ModuleResolve; private string m_fullname; private object m_syncRoot; // Used to keep collectible types alive and as the syncroot for reflection.emit private IntPtr m_assembly; // slack for ptr datum on unmanaged side #endregion internal object SyncRoot { get { if (m_syncRoot == null) { Interlocked.CompareExchange<object>(ref m_syncRoot, new object(), null); } return m_syncRoot; } } public override event ModuleResolveEventHandler ModuleResolve { add { _ModuleResolve += value; } remove { _ModuleResolve -= value; } } private const String s_localFilePrefix = "file:"; [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetCodeBase(RuntimeAssembly assembly, bool copiedName, StringHandleOnStack retString); internal String GetCodeBase(bool copiedName) { String codeBase = null; GetCodeBase(GetNativeHandle(), copiedName, JitHelpers.GetStringHandleOnStack(ref codeBase)); return codeBase; } public override String CodeBase { get { String codeBase = GetCodeBase(false); return codeBase; } } internal RuntimeAssembly GetNativeHandle() { return this; } // If the assembly is copied before it is loaded, the codebase will be set to the // actual file loaded if copiedName is true. If it is false, then the original code base // is returned. public override AssemblyName GetName(bool copiedName) { AssemblyName an = new AssemblyName(); String codeBase = GetCodeBase(copiedName); an.Init(GetSimpleName(), GetPublicKey(), null, // public key token GetVersion(), GetLocale(), GetHashAlgorithm(), AssemblyVersionCompatibility.SameMachine, codeBase, GetFlags() | AssemblyNameFlags.PublicKey, null); // strong name key pair PortableExecutableKinds pek; ImageFileMachine ifm; Module manifestModule = ManifestModule; if (manifestModule != null) { if (manifestModule.MDStreamVersion > 0x10000) { ManifestModule.GetPEKind(out pek, out ifm); an.SetProcArchIndex(pek, ifm); } } return an; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetFullName(RuntimeAssembly assembly, StringHandleOnStack retString); public override String FullName { get { // If called by Object.ToString(), return val may be NULL. if (m_fullname == null) { string s = null; GetFullName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); Interlocked.CompareExchange<string>(ref m_fullname, s, null); } return m_fullname; } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetEntryPoint(RuntimeAssembly assembly, ObjectHandleOnStack retMethod); public override MethodInfo EntryPoint { get { IRuntimeMethodInfo methodHandle = null; GetEntryPoint(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref methodHandle)); if (methodHandle == null) return null; return (MethodInfo)RuntimeType.GetMethodBase(methodHandle); } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetType(RuntimeAssembly assembly, String name, bool throwOnError, bool ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive); public override Type GetType(String name, bool throwOnError, bool ignoreCase) { // throw on null strings regardless of the value of "throwOnError" if (name == null) throw new ArgumentNullException(nameof(name)); RuntimeType type = null; Object keepAlive = null; GetType(GetNativeHandle(), name, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive)); GC.KeepAlive(keepAlive); return type; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes); public override Type[] GetExportedTypes() { Type[] types = null; GetExportedTypes(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types)); return types; } public override IEnumerable<TypeInfo> DefinedTypes { get { List<RuntimeType> rtTypes = new List<RuntimeType>(); RuntimeModule[] modules = GetModulesInternal(true, false); for (int i = 0; i < modules.Length; i++) { rtTypes.AddRange(modules[i].GetDefinedTypes()); } return rtTypes.ToArray(); } } // Load a resource based on the NameSpace of the type. [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Stream GetManifestResourceStream(Type type, String name) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return GetManifestResourceStream(type, name, false, ref stackMark); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Stream GetManifestResourceStream(String name) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return GetManifestResourceStream(name, ref stackMark, false); } // ISerializable implementation public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public override Module ManifestModule { get { // We don't need to return the "external" ModuleBuilder because // it is meant to be read-only return RuntimeAssembly.GetManifestModule(GetNativeHandle()); } } public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } // Wrapper function to wrap the typical use of InternalLoad. internal static RuntimeAssembly InternalLoad(String assemblyString, ref StackCrawlMark stackMark) { return InternalLoad(assemblyString, ref stackMark, IntPtr.Zero); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal static RuntimeAssembly InternalLoad(String assemblyString, ref StackCrawlMark stackMark, IntPtr pPrivHostBinder) { RuntimeAssembly assembly; AssemblyName an = CreateAssemblyName(assemblyString, out assembly); if (assembly != null) { // The assembly was returned from ResolveAssemblyEvent return assembly; } return InternalLoadAssemblyName(an, null, ref stackMark, pPrivHostBinder, true /*thrownOnFileNotFound*/); } // Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised. internal static AssemblyName CreateAssemblyName( String assemblyString, out RuntimeAssembly assemblyFromResolveEvent) { if (assemblyString == null) throw new ArgumentNullException(nameof(assemblyString)); Contract.EndContractBlock(); if ((assemblyString.Length == 0) || (assemblyString[0] == '\0')) throw new ArgumentException(SR.Format_StringZeroLength); AssemblyName an = new AssemblyName(); an.Name = assemblyString; an.nInit(out assemblyFromResolveEvent, true); return an; } // Wrapper function to wrap the typical use of InternalLoadAssemblyName. internal static RuntimeAssembly InternalLoadAssemblyName( AssemblyName assemblyRef, RuntimeAssembly reqAssembly, ref StackCrawlMark stackMark, bool throwOnFileNotFound, IntPtr ptrLoadContextBinder = default(IntPtr)) { return InternalLoadAssemblyName(assemblyRef, reqAssembly, ref stackMark, IntPtr.Zero, true /*throwOnError*/, ptrLoadContextBinder); } internal static RuntimeAssembly InternalLoadAssemblyName( AssemblyName assemblyRef, RuntimeAssembly reqAssembly, ref StackCrawlMark stackMark, IntPtr pPrivHostBinder, bool throwOnFileNotFound, IntPtr ptrLoadContextBinder = default(IntPtr)) { if (assemblyRef == null) throw new ArgumentNullException(nameof(assemblyRef)); Contract.EndContractBlock(); if (assemblyRef.CodeBase != null) { AppDomain.CheckLoadFromSupported(); } assemblyRef = (AssemblyName)assemblyRef.Clone(); if (assemblyRef.ProcessorArchitecture != ProcessorArchitecture.None) { // PA does not have a semantics for by-name binds for execution assemblyRef.ProcessorArchitecture = ProcessorArchitecture.None; } String codeBase = VerifyCodeBase(assemblyRef.CodeBase); return nLoad(assemblyRef, codeBase, reqAssembly, ref stackMark, pPrivHostBinder, throwOnFileNotFound, ptrLoadContextBinder); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern RuntimeAssembly nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly locationHint, ref StackCrawlMark stackMark, IntPtr pPrivHostBinder, bool throwOnFileNotFound, IntPtr ptrLoadContextBinder = default(IntPtr)); public override bool ReflectionOnly { get { return false; } } // Returns the module in this assembly with name 'name' [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetModule(RuntimeAssembly assembly, String name, ObjectHandleOnStack retModule); public override Module GetModule(String name) { Module retModule = null; GetModule(GetNativeHandle(), name, JitHelpers.GetObjectHandleOnStack(ref retModule)); return retModule; } // Returns the file in the File table of the manifest that matches the // given name. (Name should not include path.) public override FileStream GetFile(String name) { RuntimeModule m = (RuntimeModule)GetModule(name); if (m == null) return null; return new FileStream(m.GetFullyQualifiedName(), FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false); } public override FileStream[] GetFiles(bool getResourceModules) { Module[] m = GetModules(getResourceModules); FileStream[] fs = new FileStream[m.Length]; for (int i = 0; i < fs.Length; i++) { fs[i] = new FileStream(((RuntimeModule)m[i]).GetFullyQualifiedName(), FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false); } return fs; } // Returns the names of all the resources [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern String[] GetManifestResourceNames(RuntimeAssembly assembly); // Returns the names of all the resources public override String[] GetManifestResourceNames() { return GetManifestResourceNames(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetExecutingAssembly(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retAssembly); internal static RuntimeAssembly GetExecutingAssembly(ref StackCrawlMark stackMark) { RuntimeAssembly retAssembly = null; GetExecutingAssembly(JitHelpers.GetStackCrawlMarkHandle(ref stackMark), JitHelpers.GetObjectHandleOnStack(ref retAssembly)); return retAssembly; } // Returns the names of all the resources [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern AssemblyName[] GetReferencedAssemblies(RuntimeAssembly assembly); public override AssemblyName[] GetReferencedAssemblies() { return GetReferencedAssemblies(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern int GetManifestResourceInfo(RuntimeAssembly assembly, String resourceName, ObjectHandleOnStack assemblyRef, StringHandleOnStack retFileName, StackCrawlMarkHandle stackMark); [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override ManifestResourceInfo GetManifestResourceInfo(String resourceName) { RuntimeAssembly retAssembly = null; String fileName = null; StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; int location = GetManifestResourceInfo(GetNativeHandle(), resourceName, JitHelpers.GetObjectHandleOnStack(ref retAssembly), JitHelpers.GetStringHandleOnStack(ref fileName), JitHelpers.GetStackCrawlMarkHandle(ref stackMark)); if (location == -1) return null; return new ManifestResourceInfo(retAssembly, fileName, (ResourceLocation)location); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetLocation(RuntimeAssembly assembly, StringHandleOnStack retString); public override String Location { get { String location = null; GetLocation(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref location)); return location; } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetImageRuntimeVersion(RuntimeAssembly assembly, StringHandleOnStack retString); public override String ImageRuntimeVersion { get { String s = null; GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); return s; } } public override bool GlobalAssemblyCache { get { return false; } } public override Int64 HostContext { get { return 0; } } private static String VerifyCodeBase(String codebase) { if (codebase == null) return null; int len = codebase.Length; if (len == 0) return null; int j = codebase.IndexOf(':'); // Check to see if the url has a prefix if ((j != -1) && (j + 2 < len) && ((codebase[j + 1] == '/') || (codebase[j + 1] == '\\')) && ((codebase[j + 2] == '/') || (codebase[j + 2] == '\\'))) return codebase; #if PLATFORM_WINDOWS else if ((len > 2) && (codebase[0] == '\\') && (codebase[1] == '\\')) return "file://" + codebase; else return "file:///" + Path.GetFullPath(codebase); #else else return "file://" + Path.GetFullPath(codebase); #endif // PLATFORM_WINDOWS } internal Stream GetManifestResourceStream( Type type, String name, bool skipSecurityCheck, ref StackCrawlMark stackMark) { StringBuilder sb = new StringBuilder(); if (type == null) { if (name == null) throw new ArgumentNullException(nameof(type)); } else { String nameSpace = type.Namespace; if (nameSpace != null) { sb.Append(nameSpace); if (name != null) sb.Append(Type.Delimiter); } } if (name != null) sb.Append(name); return GetManifestResourceStream(sb.ToString(), ref stackMark, skipSecurityCheck); } // GetResource will return a pointer to the resources in memory. [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static unsafe extern byte* GetResource(RuntimeAssembly assembly, String resourceName, out ulong length, StackCrawlMarkHandle stackMark, bool skipSecurityCheck); internal unsafe Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck) { ulong length = 0; byte* pbInMemoryResource = GetResource(GetNativeHandle(), name, out length, JitHelpers.GetStackCrawlMarkHandle(ref stackMark), skipSecurityCheck); if (pbInMemoryResource != null) { //Console.WriteLine("Creating an unmanaged memory stream of length "+length); if (length > Int64.MaxValue) throw new NotImplementedException(SR.NotImplemented_ResourcesLongerThanInt64Max); return new UnmanagedMemoryStream(pbInMemoryResource, (long)length, (long)length, FileAccess.Read); } //Console.WriteLine("GetManifestResourceStream: Blob "+name+" not found..."); return null; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetVersion(RuntimeAssembly assembly, out int majVer, out int minVer, out int buildNum, out int revNum); internal Version GetVersion() { int majorVer, minorVer, build, revision; GetVersion(GetNativeHandle(), out majorVer, out minorVer, out build, out revision); return new Version(majorVer, minorVer, build, revision); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetLocale(RuntimeAssembly assembly, StringHandleOnStack retString); internal CultureInfo GetLocale() { String locale = null; GetLocale(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref locale)); if (locale == null) return CultureInfo.InvariantCulture; return new CultureInfo(locale); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool FCallIsDynamic(RuntimeAssembly assembly); public override bool IsDynamic { get { return FCallIsDynamic(GetNativeHandle()); } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetSimpleName(RuntimeAssembly assembly, StringHandleOnStack retSimpleName); internal String GetSimpleName() { string name = null; GetSimpleName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref name)); return name; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static AssemblyHashAlgorithm GetHashAlgorithm(RuntimeAssembly assembly); private AssemblyHashAlgorithm GetHashAlgorithm() { return GetHashAlgorithm(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static AssemblyNameFlags GetFlags(RuntimeAssembly assembly); private AssemblyNameFlags GetFlags() { return GetFlags(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetPublicKey(RuntimeAssembly assembly, ObjectHandleOnStack retPublicKey); internal byte[] GetPublicKey() { byte[] publicKey = null; GetPublicKey(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref publicKey)); return publicKey; } // This method is called by the VM. private RuntimeModule OnModuleResolveEvent(String moduleName) { ModuleResolveEventHandler moduleResolve = _ModuleResolve; if (moduleResolve == null) return null; Delegate[] ds = moduleResolve.GetInvocationList(); int len = ds.Length; for (int i = 0; i < len; i++) { RuntimeModule ret = (RuntimeModule)((ModuleResolveEventHandler)ds[i])(this, new ResolveEventArgs(moduleName, this)); if (ret != null) return ret; } return null; } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Assembly GetSatelliteAssembly(CultureInfo culture) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalGetSatelliteAssembly(culture, null, ref stackMark); } // Useful for binding to a very specific version of a satellite assembly [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalGetSatelliteAssembly(culture, version, ref stackMark); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal Assembly InternalGetSatelliteAssembly(CultureInfo culture, Version version, ref StackCrawlMark stackMark) { if (culture == null) throw new ArgumentNullException(nameof(culture)); Contract.EndContractBlock(); String name = GetSimpleName() + ".resources"; return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal RuntimeAssembly InternalGetSatelliteAssembly(String name, CultureInfo culture, Version version, bool throwOnFileNotFound, ref StackCrawlMark stackMark) { AssemblyName an = new AssemblyName(); an.SetPublicKey(GetPublicKey()); an.Flags = GetFlags() | AssemblyNameFlags.PublicKey; if (version == null) an.Version = GetVersion(); else an.Version = version; an.CultureInfo = culture; an.Name = name; RuntimeAssembly retAssembly = nLoad(an, null, this, ref stackMark, IntPtr.Zero, throwOnFileNotFound); if (retAssembly == this || (retAssembly == null && throwOnFileNotFound)) { throw new FileNotFoundException(String.Format(culture, SR.IO_FileNotFound_FileName, an.Name)); } return retAssembly; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetModules(RuntimeAssembly assembly, bool loadIfNotFound, bool getResourceModules, ObjectHandleOnStack retModuleHandles); private RuntimeModule[] GetModulesInternal(bool loadIfNotFound, bool getResourceModules) { RuntimeModule[] modules = null; GetModules(GetNativeHandle(), loadIfNotFound, getResourceModules, JitHelpers.GetObjectHandleOnStack(ref modules)); return modules; } public override Module[] GetModules(bool getResourceModules) { return GetModulesInternal(true, getResourceModules); } public override Module[] GetLoadedModules(bool getResourceModules) { return GetModulesInternal(false, getResourceModules); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeModule GetManifestModule(RuntimeAssembly assembly); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int GetToken(RuntimeAssembly assembly); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Testing; using Xunit; namespace Microsoft.AspNetCore.Mvc.IntegrationTests { public class BinderTypeBasedModelBinderIntegrationTest { [Fact] public async Task BindParameter_WithModelBinderType_NullData_ReturnsNull() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo() { BinderType = typeof(NullModelBinder) }, ParameterType = typeof(string) }; // No data is passed. var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); Assert.Null(modelBindingResult.Model); // ModelState (not set unless inner binder sets it) Assert.True(modelState.IsValid); Assert.Empty(modelState); } [Fact] public async Task BindParameter_WithModelBinderType_NoData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo() { BinderType = typeof(NullModelNotSetModelBinder) }, ParameterType = typeof(string) }; // No data is passed. var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.False(modelBindingResult.IsModelSet); // ModelState (not set unless inner binder sets it) Assert.True(modelState.IsValid); Assert.Empty(modelState); } private class Person2 { } // Ensures that prefix is part of the result returned back. [Fact] [ReplaceCulture] public async Task BindParameter_WithData_WithPrefix_GetsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo() { BinderType = typeof(SuccessModelBinder), BinderModelName = "CustomParameter" }, ParameterType = typeof(Person2) }; var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); Assert.Equal("Success", modelBindingResult.Model); // ModelState Assert.True(modelState.IsValid); var key = Assert.Single(modelState.Keys); Assert.Equal("CustomParameter", key); Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState); Assert.NotNull(modelState[key].RawValue); // Value is set by test model binder, no need to validate it. } private class Person { public Address Address { get; set; } } [ModelBinder(BinderType = typeof(AddressModelBinder))] private class Address { public string Street { get; set; } } public static TheoryData<BindingInfo> NullAndEmptyBindingInfo { get { return new TheoryData<BindingInfo> { null, new BindingInfo(), }; } } // Make sure the metadata is honored when a [ModelBinder] attribute is associated with an action parameter's // type. This should behave identically to such an attribute on an action parameter. (Tests such as // BindParameter_WithData_WithPrefix_GetsBound cover associating [ModelBinder] with an action parameter.) // // This is a regression test for aspnet/Mvc#4652 and aspnet/Mvc#7595 [Theory] [MemberData(nameof(NullAndEmptyBindingInfo))] public async Task BinderTypeOnParameterType_WithData_EmptyPrefix_GetsBound(BindingInfo bindingInfo) { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameters = typeof(TestController).GetMethod(nameof(TestController.Action)).GetParameters(); var parameter = new ControllerParameterDescriptor { Name = "Parameter1", BindingInfo = bindingInfo, ParameterInfo = parameters[0], ParameterType = typeof(Address), }; var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var address = Assert.IsType<Address>(modelBindingResult.Model); Assert.Equal("SomeStreet", address.Street); // ModelState Assert.True(modelState.IsValid); var kvp = Assert.Single(modelState); Assert.Equal("Street", kvp.Key); var entry = kvp.Value; Assert.NotNull(entry); Assert.Equal(ModelValidationState.Valid, entry.ValidationState); Assert.NotNull(entry.RawValue); // Value is set by test model binder, no need to validate it. } private class Person3 { [ModelBinder(BinderType = typeof(Address3ModelBinder))] public Address3 Address { get; set; } } private class Address3 { public string Street { get; set; } } // Make sure the metadata is honored when a [ModelBinder] attribute is associated with a property in the type // hierarchy of an action parameter. (Tests such as BindProperty_WithData_EmptyPrefix_GetsBound cover // associating [ModelBinder] with a class somewhere in the type hierarchy of an action parameter.) [Theory] [MemberData(nameof(NullAndEmptyBindingInfo))] public async Task BinderTypeOnProperty_WithData_EmptyPrefix_GetsBound(BindingInfo bindingInfo) { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "Parameter1", BindingInfo = bindingInfo, ParameterType = typeof(Person3), }; var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var person = Assert.IsType<Person3>(modelBindingResult.Model); Assert.NotNull(person.Address); Assert.Equal("SomeStreet", person.Address.Street); // ModelState Assert.True(modelState.IsValid); var kvp = Assert.Single(modelState); Assert.Equal("Address.Street", kvp.Key); var entry = kvp.Value; Assert.NotNull(entry); Assert.Equal(ModelValidationState.Valid, entry.ValidationState); Assert.NotNull(entry.RawValue); // Value is set by test model binder, no need to validate it. } [Fact] public async Task BindProperty_WithData_EmptyPrefix_GetsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo(), ParameterType = typeof(Person) }; var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var boundPerson = Assert.IsType<Person>(modelBindingResult.Model); Assert.NotNull(boundPerson.Address); Assert.Equal("SomeStreet", boundPerson.Address.Street); // ModelState Assert.True(modelState.IsValid); var key = Assert.Single(modelState.Keys); Assert.Equal("Address.Street", key); Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState); Assert.NotNull(modelState[key].RawValue); // Value is set by test model binder, no need to validate it. } [Fact] public async Task BindProperty_WithData_WithPrefix_GetsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo() { BinderModelName = "CustomParameter" }, ParameterType = typeof(Person) }; var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var boundPerson = Assert.IsType<Person>(modelBindingResult.Model); Assert.NotNull(boundPerson.Address); Assert.Equal("SomeStreet", boundPerson.Address.Street); // ModelState Assert.True(modelState.IsValid); var key = Assert.Single(modelState.Keys); Assert.Equal("CustomParameter.Address.Street", key); Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState); Assert.NotNull(modelState[key].RawValue); // Value is set by test model binder, no need to validate it. } private class AddressModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); if (bindingContext.ModelType != typeof(Address)) { return Task.CompletedTask; } var address = new Address() { Street = "SomeStreet" }; bindingContext.ModelState.SetModelValue( ModelNames.CreatePropertyModelName(bindingContext.ModelName, "Street"), new string[] { address.Street }, address.Street); bindingContext.Result = ModelBindingResult.Success(address); return Task.CompletedTask; } } private class Address3ModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); if (bindingContext.ModelType != typeof(Address3)) { return Task.CompletedTask; } var address = new Address3 { Street = "SomeStreet" }; bindingContext.ModelState.SetModelValue( ModelNames.CreatePropertyModelName(bindingContext.ModelName, "Street"), new string[] { address.Street }, address.Street); bindingContext.Result = ModelBindingResult.Success(address); return Task.CompletedTask; } } private class SuccessModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); var model = "Success"; bindingContext.ModelState.SetModelValue( bindingContext.ModelName, new string[] { model }, model); bindingContext.Result =ModelBindingResult.Success(model); return Task.CompletedTask; } } private class NullModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); bindingContext.Result = ModelBindingResult.Success(model: null); return Task.CompletedTask; } } private class NullModelNotSetModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); bindingContext.Result = ModelBindingResult.Failed(); return Task.CompletedTask; } } private class TestController { public void Action(Address address) { } } } }
using System; using System.Globalization; using System.IO; using CommandLine; using DereTore.Common.StarlightStage; using DereTore.Exchange.Archive.ACB; using DereTore.Exchange.Audio.HCA; namespace DereTore.Apps.Acb2Wavs { internal static class Program { private static int Main(string[] args) { var r = ParseOptions(args, out var options); if (r < 0) { return r; } if (!File.Exists(options.InputFileName)) { Console.Error.WriteLine("File not found: {0}", options.InputFileName); return DefaultExitCodeFail; } r = CreateDecodeParams(options, out var decodeParams); if (r < 0) { return r; } r = DoWork(options, decodeParams); return r; } private static int ParseOptions(string[] args, out Options options) { var parser = new Parser(settings => { settings.IgnoreUnknownArguments = true; }); var parsedResult = parser.ParseArguments<Options>(args); var succeeded = parsedResult.Tag == ParserResultType.Parsed; options = null; if (succeeded) { options = ((Parsed<Options>)parsedResult).Value; } if (succeeded) { if (string.IsNullOrWhiteSpace(options.InputFileName)) { succeeded = false; } } if (!succeeded) { var helpText = CommandLine.Text.HelpText.AutoBuild(parsedResult, null, null); helpText.AddPreOptionsLine(" "); helpText.AddPreOptionsLine("Usage: acb2wavs <input ACB> [options]"); Console.Error.WriteLine(helpText); return DefaultExitCodeFail; } return 0; } private static int CreateDecodeParams(Options options, out DecodeParams decodeParams) { uint key1, key2; var formatProvider = new NumberFormatInfo(); decodeParams = DecodeParams.Default; if (!string.IsNullOrWhiteSpace(options.Key1)) { if (!uint.TryParse(options.Key1, NumberStyles.HexNumber, formatProvider, out key1)) { Console.WriteLine("ERROR: key 1 is in wrong format. It should look like \"a1b2c3d4\"."); return DefaultExitCodeFail; } } else { key1 = CgssCipher.Key1; } if (!string.IsNullOrWhiteSpace(options.Key2)) { if (!uint.TryParse(options.Key2, NumberStyles.HexNumber, formatProvider, out key2)) { Console.WriteLine("ERROR: key 2 is in wrong format. It should look like \"a1b2c3d4\"."); return DefaultExitCodeFail; } } else { key2 = CgssCipher.Key2; } decodeParams = DecodeParams.CreateDefault(key1, key2); return 0; } private static int DoWork(Options options, DecodeParams baseDecodeParams) { var fileInfo = new FileInfo(options.InputFileName); var baseExtractDirPath = Path.Combine(fileInfo.DirectoryName ?? string.Empty, string.Format(DirTemplate, fileInfo.Name)); if (!Directory.Exists(baseExtractDirPath)) { Directory.CreateDirectory(baseExtractDirPath); } using (var acb = AcbFile.FromFile(options.InputFileName)) { var formatVersion = acb.FormatVersion; if (acb.InternalAwb != null) { var internalDirPath = Path.Combine(baseExtractDirPath, "internal"); ProcessAllBinaries(formatVersion, baseDecodeParams, internalDirPath, acb.InternalAwb, acb.Stream, true); } if (acb.ExternalAwb != null) { var externalDirPath = Path.Combine(baseExtractDirPath, "external"); using (var fs = File.Open(acb.ExternalAwb.FileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { ProcessAllBinaries(formatVersion, baseDecodeParams, externalDirPath, acb.ExternalAwb, fs, false); } } } return 0; } private static void ProcessAllBinaries(uint acbFormatVersion, DecodeParams baseDecodeParams, string extractDir, Afs2Archive archive, Stream dataStream, bool isInternal) { if (!Directory.Exists(extractDir)) { Directory.CreateDirectory(extractDir); } var afsSource = isInternal ? "internal" : "external"; var decodeParams = baseDecodeParams; if (acbFormatVersion >= NewEncryptionVersion) { decodeParams.KeyModifier = archive.HcaKeyModifier; } else { decodeParams.KeyModifier = 0; } foreach (var entry in archive.Files) { var record = entry.Value; var extractFileName = AcbFile.GetSymbolicFileNameFromCueId(record.CueId); extractFileName = extractFileName.ReplaceExtension(".bin", ".wav"); var extractFilePath = Path.Combine(extractDir, extractFileName); using (var fileData = AcbHelper.ExtractToNewStream(dataStream, record.FileOffsetAligned, (int)record.FileLength)) { var isHcaStream = HcaReader.IsHcaStream(fileData); Console.Write("Processing {0} AFS: #{1} (offset={2} size={3})... ", afsSource, record.CueId, record.FileOffsetAligned, record.FileLength); if (isHcaStream) { try { using (var fs = File.Open(extractFilePath, FileMode.Create, FileAccess.Write, FileShare.Write)) { DecodeHca(fileData, fs, decodeParams); } Console.WriteLine("decoded"); } catch (Exception ex) { if (File.Exists(extractFilePath)) { File.Delete(extractFilePath); } Console.WriteLine(ex.ToString()); if (ex.InnerException != null) { Console.WriteLine("Details:"); Console.WriteLine(ex.InnerException.ToString()); } } } else { Console.WriteLine("skipped (not HCA)"); } } } } private static void DecodeHca(Stream hcaDataStream, Stream waveStream, DecodeParams decodeParams) { using (var hcaStream = new OneWayHcaAudioStream(hcaDataStream, decodeParams, true)) { var buffer = new byte[10240]; var read = 1; while (read > 0) { read = hcaStream.Read(buffer, 0, buffer.Length); if (read > 0) { waveStream.Write(buffer, 0, read); } } } } private static string ReplaceExtension(this string str, string oldExt, string newExt) { if (str == null || oldExt == null || newExt == null) { throw new ArgumentNullException(); } if (str.Length < oldExt.Length) { return str; } if (str.Substring(str.Length - oldExt.Length).ToLowerInvariant() != oldExt.ToLowerInvariant()) { return str; } return str.Substring(0, str.Length - oldExt.Length) + newExt; } private static readonly string DirTemplate = "_acb_{0}"; private const int DefaultExitCodeFail = -1; private const uint NewEncryptionVersion = 0x01300000; } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // Path to the folder that contains the editors we will load. //--------------------------------------------------------------------------------------------- $Tools::resourcePath = "tools/"; // These must be loaded first, in this order, before anything else is loaded $Tools::loadFirst = "editorClasses base worldEditor"; //--------------------------------------------------------------------------------------------- // Object that holds the simObject id that the materialEditor uses to interpret its material list //--------------------------------------------------------------------------------------------- $Tools::materialEditorList = ""; //--------------------------------------------------------------------------------------------- // Tools Package. //--------------------------------------------------------------------------------------------- package Tools { function loadKeybindings() { Parent::loadKeybindings(); } // Start-up. function onStart() { Parent::onStart(); new Settings(EditorSettings) { file = "tools/settings.xml"; }; EditorSettings.read(); echo( " % - Initializing Tools" ); // Default file path when saving from the editor (such as prefabs) if ($Pref::WorldEditor::LastPath $= "") { $Pref::WorldEditor::LastPath = getMainDotCsDir(); } // Common GUI stuff. exec( "./gui/cursors.ed.cs" ); exec( "./gui/profiles.ed.cs" ); exec( "./editorClasses/gui/panels/navPanelProfiles.ed.cs" ); // Make sure we get editor profiles before any GUI's // BUG: these dialogs are needed earlier in the init sequence, and should be moved to // common, along with the guiProfiles they depend on. exec( "./gui/guiDialogs.ed.cs" ); //%toggle = $Scripts::ignoreDSOs; //$Scripts::ignoreDSOs = true; $ignoredDatablockSet = new SimSet(); // fill the list of editors $editors[count] = getWordCount( $Tools::loadFirst ); for ( %i = 0; %i < $editors[count]; %i++ ) { $editors[%i] = getWord( $Tools::loadFirst, %i ); } %pattern = $Tools::resourcePath @ "/*/main.cs"; %folder = findFirstFile( %pattern ); if ( %folder $= "") { // if we have absolutely no matches for main.cs, we look for main.cs.dso %pattern = $Tools::resourcePath @ "/*/main.cs.dso"; %folder = findFirstFile( %pattern ); } while ( %folder !$= "" ) { if( filePath( %folder ) !$= "tools" ) // Skip the actual 'tools' folder...we want the children { %folder = filePath( %folder ); %editor = fileName( %folder ); if ( IsDirectory( %folder ) ) { // Yes, this sucks and should be done better if ( strstr( $Tools::loadFirst, %editor ) == -1 ) { $editors[$editors[count]] = %editor; $editors[count]++; } } } %folder = findNextFile( %pattern ); } // initialize every editor new SimSet( EditorPluginSet ); %count = $editors[count]; for ( %i = 0; %i < %count; %i++ ) { exec( "./" @ $editors[%i] @ "/main.cs" ); %initializeFunction = "initialize" @ $editors[%i]; if( isFunction( %initializeFunction ) ) call( %initializeFunction ); } // Popuplate the default SimObject icons that // are used by the various editors. EditorIconRegistry::loadFromPath( "tools/classIcons/" ); // Load up the tools resources. All the editors are initialized at this point, so // resources can override, redefine, or add functionality. Tools::LoadResources( $Tools::resourcePath ); //$Scripts::ignoreDSOs = %toggle; } function startToolTime(%tool) { if($toolDataToolCount $= "") $toolDataToolCount = 0; if($toolDataToolEntry[%tool] !$= "true") { $toolDataToolEntry[%tool] = "true"; $toolDataToolList[$toolDataToolCount] = %tool; $toolDataToolCount++; $toolDataClickCount[%tool] = 0; } $toolDataStartTime[%tool] = getSimTime(); $toolDataClickCount[%tool]++; } function endToolTime(%tool) { %startTime = 0; if($toolDataStartTime[%tool] !$= "") %startTime = $toolDataStartTime[%tool]; if($toolDataTotalTime[%tool] $= "") $toolDataTotalTime[%tool] = 0; $toolDataTotalTime[%tool] += getSimTime() - %startTime; } function dumpToolData() { %count = $toolDataToolCount; for(%i=0; %i<%count; %i++) { %tool = $toolDataToolList[%i]; %totalTime = $toolDataTotalTime[%tool]; if(%totalTime $= "") %totalTime = 0; %clickCount = $toolDataClickCount[%tool]; echo("---"); echo("Tool: " @ %tool); echo("Time (seconds): " @ %totalTime / 1000); echo("Activated: " @ %clickCount); echo("---"); } } // Shutdown. function onExit() { if( EditorGui.isInitialized ) EditorGui.shutdown(); // Free all the icon images in the registry. EditorIconRegistry::clear(); // Save any Layouts we might be using //GuiFormManager::SaveLayout(LevelBuilder, Default, User); %count = $editors[count]; for (%i = 0; %i < %count; %i++) { %destroyFunction = "destroy" @ $editors[%i]; if( isFunction( %destroyFunction ) ) call( %destroyFunction ); } // Call Parent. Parent::onExit(); // write out our settings xml file EditorSettings.write(); } }; function Tools::LoadResources( %path ) { %resourcesPath = %path @ "resources/"; %resourcesList = getDirectoryList( %resourcesPath ); %wordCount = getFieldCount( %resourcesList ); for( %i = 0; %i < %wordCount; %i++ ) { %resource = GetField( %resourcesList, %i ); if( isFile( %resourcesPath @ %resource @ "/resourceDatabase.cs") ) ResourceObject::load( %path, %resource ); } } //----------------------------------------------------------------------------- // Activate Package. //----------------------------------------------------------------------------- activatePackage(Tools);
// // Mono.Data.TdsTypes.TdsInt32 // // Author: // Tim Coleman (tim@timcoleman.com) // // (C) Copyright Tim Coleman, 2002 // // // 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 Mono.Data.TdsClient; using System; using System.Data.SqlTypes; using System.Globalization; namespace Mono.Data.TdsTypes { public struct TdsInt32 : INullable, IComparable { #region Fields int value; private bool notNull; public static readonly TdsInt32 MaxValue = new TdsInt32 (2147483647); public static readonly TdsInt32 MinValue = new TdsInt32 (-2147483648); public static readonly TdsInt32 Null; public static readonly TdsInt32 Zero = new TdsInt32 (0); #endregion #region Constructors public TdsInt32(int value) { this.value = value; notNull = true; } #endregion #region Properties public bool IsNull { get { return !notNull; } } public int Value { get { if (this.IsNull) throw new TdsNullValueException (); else return value; } } #endregion #region Methods public static TdsInt32 Add (TdsInt32 x, TdsInt32 y) { return (x + y); } public static TdsInt32 BitwiseAnd(TdsInt32 x, TdsInt32 y) { return (x & y); } public static TdsInt32 BitwiseOr(TdsInt32 x, TdsInt32 y) { return (x | y); } public int CompareTo(object value) { if (value == null) return 1; else if (!(value is TdsInt32)) throw new ArgumentException (Locale.GetText ("Value is not a System.Data.TdsTypes.TdsInt32")); else if (((TdsInt32)value).IsNull) return 1; else return this.value.CompareTo (((TdsInt32)value).Value); } public static TdsInt32 Divide(TdsInt32 x, TdsInt32 y) { return (x / y); } public override bool Equals(object value) { if (!(value is TdsInt32)) return false; else return (bool) (this == (TdsInt32)value); } public static TdsBoolean Equals(TdsInt32 x, TdsInt32 y) { return (x == y); } public override int GetHashCode() { return value; } public static TdsBoolean GreaterThan (TdsInt32 x, TdsInt32 y) { return (x > y); } public static TdsBoolean GreaterThanOrEqual (TdsInt32 x, TdsInt32 y) { return (x >= y); } public static TdsBoolean LessThan(TdsInt32 x, TdsInt32 y) { return (x < y); } public static TdsBoolean LessThanOrEqual(TdsInt32 x, TdsInt32 y) { return (x <= y); } public static TdsInt32 Mod(TdsInt32 x, TdsInt32 y) { return (x % y); } public static TdsInt32 Multiply(TdsInt32 x, TdsInt32 y) { return (x * y); } public static TdsBoolean NotEquals(TdsInt32 x, TdsInt32 y) { return (x != y); } public static TdsInt32 OnesComplement(TdsInt32 x) { return ~x; } public static TdsInt32 Parse(string s) { return new TdsInt32 (Int32.Parse (s)); } public static TdsInt32 Subtract(TdsInt32 x, TdsInt32 y) { return (x - y); } public TdsBoolean ToTdsBoolean() { return ((TdsBoolean)this); } public TdsByte ToTdsByte() { return ((TdsByte)this); } public TdsDecimal ToTdsDecimal() { return ((TdsDecimal)this); } public TdsDouble ToTdsDouble() { return ((TdsDouble)this); } public TdsInt16 ToTdsInt16() { return ((TdsInt16)this); } public TdsInt64 ToTdsInt64() { return ((TdsInt64)this); } public TdsMoney ToTdsMoney() { return ((TdsMoney)this); } public TdsSingle ToTdsSingle() { return ((TdsSingle)this); } public TdsString ToTdsString () { return ((TdsString)this); } public override string ToString() { if (this.IsNull) return "Null"; else return value.ToString (); } public static TdsInt32 Xor(TdsInt32 x, TdsInt32 y) { return (x ^ y); } #endregion #region Operators // Compute Addition public static TdsInt32 operator + (TdsInt32 x, TdsInt32 y) { return new TdsInt32 (x.Value + y.Value); } // Bitwise AND public static TdsInt32 operator & (TdsInt32 x, TdsInt32 y) { return new TdsInt32 (x.Value & y.Value); } // Bitwise OR public static TdsInt32 operator | (TdsInt32 x, TdsInt32 y) { return new TdsInt32 (x.Value | y.Value); } // Compute Division public static TdsInt32 operator / (TdsInt32 x, TdsInt32 y) { return new TdsInt32 (x.Value / y.Value); } // Compare Equality public static TdsBoolean operator == (TdsInt32 x, TdsInt32 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value == y.Value); } // Bitwise Exclusive-OR (XOR) public static TdsInt32 operator ^ (TdsInt32 x, TdsInt32 y) { return new TdsInt32 (x.Value ^ y.Value); } // > Compare public static TdsBoolean operator >(TdsInt32 x, TdsInt32 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value > y.Value); } // >= Compare public static TdsBoolean operator >= (TdsInt32 x, TdsInt32 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value >= y.Value); } // != Inequality Compare public static TdsBoolean operator != (TdsInt32 x, TdsInt32 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value != y.Value); } // < Compare public static TdsBoolean operator < (TdsInt32 x, TdsInt32 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value < y.Value); } // <= Compare public static TdsBoolean operator <= (TdsInt32 x, TdsInt32 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value <= y.Value); } // Compute Modulus public static TdsInt32 operator % (TdsInt32 x, TdsInt32 y) { return new TdsInt32 (x.Value % y.Value); } // Compute Multiplication public static TdsInt32 operator * (TdsInt32 x, TdsInt32 y) { return new TdsInt32 (x.Value * y.Value); } // Ones Complement public static TdsInt32 operator ~ (TdsInt32 x) { return new TdsInt32 (~x.Value); } // Subtraction public static TdsInt32 operator - (TdsInt32 x, TdsInt32 y) { return new TdsInt32 (x.Value - y.Value); } // Negates the Value public static TdsInt32 operator - (TdsInt32 x) { return new TdsInt32 (-x.Value); } // Type Conversions public static explicit operator TdsInt32 (TdsBoolean x) { if (x.IsNull) return Null; else return new TdsInt32 ((int)x.ByteValue); } public static explicit operator TdsInt32 (TdsDecimal x) { if (x.IsNull) return Null; else return new TdsInt32 ((int)x.Value); } public static explicit operator TdsInt32 (TdsDouble x) { if (x.IsNull) return Null; else return new TdsInt32 ((int)x.Value); } public static explicit operator int (TdsInt32 x) { return x.Value; } public static explicit operator TdsInt32 (TdsInt64 x) { if (x.IsNull) return Null; else return new TdsInt32 ((int)x.Value); } public static explicit operator TdsInt32(TdsMoney x) { if (x.IsNull) return Null; else return new TdsInt32 ((int)x.Value); } public static explicit operator TdsInt32(TdsSingle x) { if (x.IsNull) return Null; else return new TdsInt32 ((int)x.Value); } public static explicit operator TdsInt32(TdsString x) { return TdsInt32.Parse (x.Value); } public static implicit operator TdsInt32(int x) { return new TdsInt32 (x); } public static implicit operator TdsInt32(TdsByte x) { if (x.IsNull) return Null; else return new TdsInt32 ((int)x.Value); } public static implicit operator TdsInt32(TdsInt16 x) { if (x.IsNull) return Null; else return new TdsInt32 ((int)x.Value); } #endregion } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using FluentAssertions; using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.CommandFactory; using Microsoft.DotNet.Tools.Test.Utilities; using NuGet.Frameworks; using Xunit; using Microsoft.DotNet.Tools.Tests.Utilities; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.DotNet.Tests { public class GivenAProjectDependenciesCommandFactory : TestBase { private static readonly NuGetFramework s_desktopTestFramework = FrameworkConstants.CommonFrameworks.Net451; private RepoDirectoriesProvider _repoDirectoriesProvider; public GivenAProjectDependenciesCommandFactory() { _repoDirectoriesProvider = new RepoDirectoriesProvider(); Environment.SetEnvironmentVariable( Constants.MSBUILD_EXE_PATH, Path.Combine(_repoDirectoriesProvider.Stage2Sdk, "MSBuild.dll")); } [WindowsOnlyFact] public void It_resolves_desktop_apps_defaulting_to_Debug_Configuration() { var configuration = "Debug"; var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx") .CreateInstance() .WithSourceFiles() .WithNuGetConfig(_repoDirectoriesProvider.TestPackages); var restoreCommand = new RestoreCommand() .WithWorkingDirectory(testInstance.Root) .ExecuteWithCapturedOutput() .Should().Pass(); var buildCommand = new BuildCommand() .WithWorkingDirectory(testInstance.Root) .WithConfiguration(configuration) .WithCapturedOutput() .Execute() .Should().Pass(); var factory = new ProjectDependenciesCommandFactory( s_desktopTestFramework, null, null, null, testInstance.Root.FullName); var command = factory.Create("dotnet-desktop-and-portable", null); command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName); Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe"); } [WindowsOnlyFact] public void It_resolves_desktop_apps_when_configuration_is_Debug() { var configuration = "Debug"; var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx") .CreateInstance() .WithSourceFiles() .WithNuGetConfig(_repoDirectoriesProvider.TestPackages); var restoreCommand = new RestoreCommand() .WithWorkingDirectory(testInstance.Root) .ExecuteWithCapturedOutput() .Should().Pass(); var buildCommand = new BuildCommand() .WithWorkingDirectory(testInstance.Root) .WithConfiguration(configuration) .Execute() .Should().Pass(); var factory = new ProjectDependenciesCommandFactory( s_desktopTestFramework, configuration, null, null, testInstance.Root.FullName); var command = factory.Create("dotnet-desktop-and-portable", null); command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName); Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe"); } [WindowsOnlyFact] public void It_resolves_desktop_apps_when_configuration_is_Release() { var configuration = "Debug"; var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx") .CreateInstance() .WithSourceFiles() .WithNuGetConfig(_repoDirectoriesProvider.TestPackages); var restoreCommand = new RestoreCommand() .WithWorkingDirectory(testInstance.Root) .ExecuteWithCapturedOutput() .Should().Pass(); var buildCommand = new BuildCommand() .WithWorkingDirectory(testInstance.Root) .WithConfiguration(configuration) .WithCapturedOutput() .Execute() .Should().Pass(); var factory = new ProjectDependenciesCommandFactory( s_desktopTestFramework, configuration, null, null, testInstance.Root.FullName); var command = factory.Create("dotnet-desktop-and-portable", null); command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName); Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe"); } [WindowsOnlyFact] public void It_resolves_desktop_apps_using_configuration_passed_to_create() { var configuration = "Debug"; var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx") .CreateInstance() .WithSourceFiles() .WithNuGetConfig(_repoDirectoriesProvider.TestPackages); var restoreCommand = new RestoreCommand() .WithWorkingDirectory(testInstance.Root) .ExecuteWithCapturedOutput() .Should().Pass(); var buildCommand = new BuildCommand() .WithWorkingDirectory(testInstance.Root) .WithConfiguration(configuration) .WithCapturedOutput() .Execute() .Should().Pass(); var factory = new ProjectDependenciesCommandFactory( s_desktopTestFramework, "Debug", null, null, testInstance.Root.FullName); var command = factory.Create("dotnet-desktop-and-portable", null, configuration: configuration); command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName); Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe"); } [Fact] public void It_resolves_tools_whose_package_name_is_different_than_dll_name() { Environment.SetEnvironmentVariable( Constants.MSBUILD_EXE_PATH, Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "MSBuild.dll")); var configuration = "Debug"; var testInstance = TestAssets.Get("AppWithDirectDepWithOutputName") .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var buildCommand = new BuildCommand() .WithProjectDirectory(testInstance.Root) .WithConfiguration(configuration) .WithCapturedOutput() .Execute() .Should().Pass(); var factory = new ProjectDependenciesCommandFactory( NuGetFrameworks.NetCoreApp30, configuration, null, null, testInstance.Root.FullName); var command = factory.Create("dotnet-tool-with-output-name", null); command.CommandArgs.Should().Contain( Path.Combine("toolwithoutputname", "1.0.0", "lib", "netcoreapp3.0", "dotnet-tool-with-output-name.dll")); } } }
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ using System; using boolean = System.Boolean; namespace Facebook.CSSLayout { /** * Calculates layouts based on CSS style. See {@link #layoutNode(CSSNode, float)}. */ static class LayoutEngine { const int POSITION_LEFT = CSSLayout.POSITION_LEFT; const int POSITION_TOP = CSSLayout.POSITION_TOP; const int POSITION_RIGHT = CSSLayout.POSITION_RIGHT; const int POSITION_BOTTOM = CSSLayout.POSITION_BOTTOM; const int DIMENSION_WIDTH = CSSLayout.DIMENSION_WIDTH; const int DIMENSION_HEIGHT = CSSLayout.DIMENSION_HEIGHT; const int CSS_FLEX_DIRECTION_COLUMN = (int)CSSFlexDirection.Column; const int CSS_FLEX_DIRECTION_COLUMN_REVERSE = (int)CSSFlexDirection.ColumnReverse; const int CSS_FLEX_DIRECTION_ROW = (int)CSSFlexDirection.Row; const int CSS_FLEX_DIRECTION_ROW_REVERSE = (int)CSSFlexDirection.RowReverse; const int CSS_POSITION_RELATIVE = (int)CSSPositionType.Relative; const int CSS_POSITION_ABSOLUTE = (int)CSSPositionType.Absolute; private static readonly int[] leading = { POSITION_TOP, POSITION_BOTTOM, POSITION_LEFT, POSITION_RIGHT, }; private static readonly int[] trailing = { POSITION_BOTTOM, POSITION_TOP, POSITION_RIGHT, POSITION_LEFT, }; private static readonly int[] pos = { POSITION_TOP, POSITION_BOTTOM, POSITION_LEFT, POSITION_RIGHT, }; private static readonly int[] dim = { DIMENSION_HEIGHT, DIMENSION_HEIGHT, DIMENSION_WIDTH, DIMENSION_WIDTH, }; private static readonly int[] leadingSpacing = { Spacing.TOP, Spacing.BOTTOM, Spacing.START, Spacing.START }; private static readonly int[] trailingSpacing = { Spacing.BOTTOM, Spacing.TOP, Spacing.END, Spacing.END }; private static float boundAxis(CSSNode node, int axis, float value) { float min = CSSConstants.Undefined; float max = CSSConstants.Undefined; if (axis == CSS_FLEX_DIRECTION_COLUMN || axis == CSS_FLEX_DIRECTION_COLUMN_REVERSE) { min = node.style.minHeight; max = node.style.maxHeight; } else if (axis == CSS_FLEX_DIRECTION_ROW || axis == CSS_FLEX_DIRECTION_ROW_REVERSE) { min = node.style.minWidth; max = node.style.maxWidth; } float boundValue = value; if (!float.IsNaN(max) && max >= 0.0 && boundValue > max) { boundValue = max; } if (!float.IsNaN(min) && min >= 0.0 && boundValue < min) { boundValue = min; } return boundValue; } private static void setDimensionFromStyle(CSSNode node, int axis) { // The parent already computed us a width or height. We just skip it if (!float.IsNaN(node.layout.dimensions[dim[axis]])) { return; } // We only run if there's a width or height defined if (float.IsNaN(node.style.dimensions[dim[axis]]) || node.style.dimensions[dim[axis]] <= 0.0) { return; } // The dimensions can never be smaller than the padding and border float maxLayoutDimension = Math.Max( boundAxis(node, axis, node.style.dimensions[dim[axis]]), node.style.padding.getWithFallback(leadingSpacing[axis], leading[axis]) + node.style.padding.getWithFallback(trailingSpacing[axis], trailing[axis]) + node.style.border.getWithFallback(leadingSpacing[axis], leading[axis]) + node.style.border.getWithFallback(trailingSpacing[axis], trailing[axis])); node.layout.dimensions[dim[axis]] = maxLayoutDimension; } private static float getRelativePosition(CSSNode node, int axis) { float lead = node.style.position[leading[axis]]; if (!float.IsNaN(lead)) { return lead; } float trailingPos = node.style.position[trailing[axis]]; return float.IsNaN(trailingPos) ? 0 : -trailingPos; } static int resolveAxis(int axis, CSSDirection direction) { if (direction == CSSDirection.RTL) { if (axis == CSS_FLEX_DIRECTION_ROW) { return CSS_FLEX_DIRECTION_ROW_REVERSE; } else if (axis == CSS_FLEX_DIRECTION_ROW_REVERSE) { return CSS_FLEX_DIRECTION_ROW; } } return axis; } static CSSDirection resolveDirection(CSSNode node, CSSDirection? parentDirection) { CSSDirection direction = node.style.direction; if (direction == CSSDirection.Inherit) { direction = (parentDirection == null ? CSSDirection.LTR : parentDirection.Value); } return direction; } static int getFlexDirection(CSSNode node) { return (int)node.style.flexDirection; } private static int getCrossFlexDirection(int axis, CSSDirection direction) { if (axis == CSS_FLEX_DIRECTION_COLUMN || axis == CSS_FLEX_DIRECTION_COLUMN_REVERSE) { return resolveAxis(CSS_FLEX_DIRECTION_ROW, direction); } else { return CSS_FLEX_DIRECTION_COLUMN; } } static CSSAlign getAlignItem(CSSNode node, CSSNode child) { if (child.style.alignSelf != CSSAlign.Auto) { return child.style.alignSelf; } return node.style.alignItems; } static boolean isMeasureDefined(CSSNode node) { return node.IsMeasureDefined; } static boolean needsRelayout(CSSNode node, float parentMaxWidth) { return node.isDirty() || !FloatUtil.floatsEqual( node.lastLayout.requestedHeight, node.layout.dimensions[DIMENSION_HEIGHT]) || !FloatUtil.floatsEqual( node.lastLayout.requestedWidth, node.layout.dimensions[DIMENSION_WIDTH]) || !FloatUtil.floatsEqual(node.lastLayout.parentMaxWidth, parentMaxWidth); } internal static void layoutNode(CSSLayoutContext layoutContext, CSSNode node, float parentMaxWidth, CSSDirection? parentDirection) { if (needsRelayout(node, parentMaxWidth)) { node.lastLayout.requestedWidth = node.layout.dimensions[DIMENSION_WIDTH]; node.lastLayout.requestedHeight = node.layout.dimensions[DIMENSION_HEIGHT]; node.lastLayout.parentMaxWidth = parentMaxWidth; layoutNodeImpl(layoutContext, node, parentMaxWidth, parentDirection); node.lastLayout.copy(node.layout); } else { node.layout.copy(node.lastLayout); } node.markHasNewLayout(); } static void layoutNodeImpl(CSSLayoutContext layoutContext, CSSNode node, float parentMaxWidth, CSSDirection? parentDirection) { var childCount_ = node.getChildCount(); for (int i_ = 0; i_ < childCount_; i_++) { node.getChildAt(i_).layout.resetResult(); } /** START_GENERATED **/ CSSDirection direction = resolveDirection(node, parentDirection); int mainAxis = resolveAxis(getFlexDirection(node), direction); int crossAxis = getCrossFlexDirection(mainAxis, direction); int resolvedRowAxis = resolveAxis(CSS_FLEX_DIRECTION_ROW, direction); // Handle width and height style attributes setDimensionFromStyle(node, mainAxis); setDimensionFromStyle(node, crossAxis); // Set the resolved resolution in the node's layout node.layout.direction = direction; // The position is set by the parent, but we need to complete it with a // delta composed of the margin and left/top/right/bottom node.layout.position[leading[mainAxis]] += node.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + getRelativePosition(node, mainAxis); node.layout.position[trailing[mainAxis]] += node.style.margin.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) + getRelativePosition(node, mainAxis); node.layout.position[leading[crossAxis]] += node.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + getRelativePosition(node, crossAxis); node.layout.position[trailing[crossAxis]] += node.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]) + getRelativePosition(node, crossAxis); // Inline immutable values from the target node to avoid excessive method // invocations during the layout calculation. int childCount = node.getChildCount(); float paddingAndBorderAxisResolvedRow = ((node.style.padding.getWithFallback(leadingSpacing[resolvedRowAxis], leading[resolvedRowAxis]) + node.style.border.getWithFallback(leadingSpacing[resolvedRowAxis], leading[resolvedRowAxis])) + (node.style.padding.getWithFallback(trailingSpacing[resolvedRowAxis], trailing[resolvedRowAxis]) + node.style.border.getWithFallback(trailingSpacing[resolvedRowAxis], trailing[resolvedRowAxis]))); if (isMeasureDefined(node)) { boolean isResolvedRowDimDefined = !float.IsNaN(node.layout.dimensions[dim[resolvedRowAxis]]); float width = CSSConstants.Undefined; if ((!float.IsNaN(node.style.dimensions[dim[resolvedRowAxis]]) && node.style.dimensions[dim[resolvedRowAxis]] >= 0.0)) { width = node.style.dimensions[DIMENSION_WIDTH]; } else if (isResolvedRowDimDefined) { width = node.layout.dimensions[dim[resolvedRowAxis]]; } else { width = parentMaxWidth - (node.style.margin.getWithFallback(leadingSpacing[resolvedRowAxis], leading[resolvedRowAxis]) + node.style.margin.getWithFallback(trailingSpacing[resolvedRowAxis], trailing[resolvedRowAxis])); } width -= paddingAndBorderAxisResolvedRow; // We only need to give a dimension for the text if we haven't got any // for it computed yet. It can either be from the style attribute or because // the element is flexible. boolean isRowUndefined = !(!float.IsNaN(node.style.dimensions[dim[resolvedRowAxis]]) && node.style.dimensions[dim[resolvedRowAxis]] >= 0.0) && !isResolvedRowDimDefined; boolean isColumnUndefined = !(!float.IsNaN(node.style.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]]) && node.style.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]] >= 0.0) && float.IsNaN(node.layout.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]]); // Let's not measure the text if we already know both dimensions if (isRowUndefined || isColumnUndefined) { MeasureOutput measureDim = node.measure( layoutContext.measureOutput, width ); if (isRowUndefined) { node.layout.dimensions[DIMENSION_WIDTH] = measureDim.width + paddingAndBorderAxisResolvedRow; } if (isColumnUndefined) { node.layout.dimensions[DIMENSION_HEIGHT] = measureDim.height + ((node.style.padding.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + node.style.border.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN])) + (node.style.padding.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]) + node.style.border.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]))); } } if (childCount == 0) { return; } } boolean isNodeFlexWrap = (node.style.flexWrap == CSSWrap.Wrap); CSSJustify justifyContent = node.style.justifyContent; float leadingPaddingAndBorderMain = (node.style.padding.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + node.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis])); float leadingPaddingAndBorderCross = (node.style.padding.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + node.style.border.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis])); float paddingAndBorderAxisMain = ((node.style.padding.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + node.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis])) + (node.style.padding.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) + node.style.border.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]))); float paddingAndBorderAxisCross = ((node.style.padding.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + node.style.border.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis])) + (node.style.padding.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]) + node.style.border.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]))); boolean isMainDimDefined = !float.IsNaN(node.layout.dimensions[dim[mainAxis]]); boolean isCrossDimDefined = !float.IsNaN(node.layout.dimensions[dim[crossAxis]]); boolean isMainRowDirection = (mainAxis == CSS_FLEX_DIRECTION_ROW || mainAxis == CSS_FLEX_DIRECTION_ROW_REVERSE); int i; int ii; CSSNode child; int axis; CSSNode firstAbsoluteChild = null; CSSNode currentAbsoluteChild = null; float definedMainDim = CSSConstants.Undefined; if (isMainDimDefined) { definedMainDim = node.layout.dimensions[dim[mainAxis]] - paddingAndBorderAxisMain; } // We want to execute the next two loops one per line with flex-wrap int startLine = 0; int endLine = 0; // int nextOffset = 0; int alreadyComputedNextLayout = 0; // We aggregate the total dimensions of the container in those two variables float linesCrossDim = 0; float linesMainDim = 0; int linesCount = 0; while (endLine < childCount) { // <Loop A> Layout non flexible children and count children by type // mainContentDim is accumulation of the dimensions and margin of all the // non flexible children. This will be used in order to either set the // dimensions of the node if none already exist, or to compute the // remaining space left for the flexible children. float mainContentDim = 0; // There are three kind of children, non flexible, flexible and absolute. // We need to know how many there are in order to distribute the space. int flexibleChildrenCount = 0; float totalFlexible = 0; int nonFlexibleChildrenCount = 0; // Use the line loop to position children in the main axis for as long // as they are using a simple stacking behaviour. Children that are // immediately stacked in the initial loop will not be touched again // in <Loop C>. boolean isSimpleStackMain = (isMainDimDefined && justifyContent == CSSJustify.FlexStart) || (!isMainDimDefined && justifyContent != CSSJustify.Center); int firstComplexMain = (isSimpleStackMain ? childCount : startLine); // Use the initial line loop to position children in the cross axis for // as long as they are relatively positioned with alignment STRETCH or // FLEX_START. Children that are immediately stacked in the initial loop // will not be touched again in <Loop D>. boolean isSimpleStackCross = true; int firstComplexCross = childCount; CSSNode firstFlexChild = null; CSSNode currentFlexChild = null; float mainDim = leadingPaddingAndBorderMain; float crossDim = 0; float maxWidth; for (i = startLine; i < childCount; ++i) { child = node.getChildAt(i); child.lineIndex = linesCount; child.nextAbsoluteChild = null; child.nextFlexChild = null; CSSAlign alignItem = getAlignItem(node, child); // Pre-fill cross axis dimensions when the child is using stretch before // we call the recursive layout pass if (alignItem == CSSAlign.Stretch && child.style.positionType == CSSPositionType.Relative && isCrossDimDefined && !(!float.IsNaN(child.style.dimensions[dim[crossAxis]]) && child.style.dimensions[dim[crossAxis]] >= 0.0)) { child.layout.dimensions[dim[crossAxis]] = Math.Max( boundAxis(child, crossAxis, node.layout.dimensions[dim[crossAxis]] - paddingAndBorderAxisCross - (child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]))), // You never want to go smaller than padding ((child.style.padding.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.border.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis])) + (child.style.padding.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]) + child.style.border.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]))) ); } else if (child.style.positionType == CSSPositionType.Absolute) { // Store a private linked list of absolutely positioned children // so that we can efficiently traverse them later. if (firstAbsoluteChild == null) { firstAbsoluteChild = child; } if (currentAbsoluteChild != null) { currentAbsoluteChild.nextAbsoluteChild = child; } currentAbsoluteChild = child; // Pre-fill dimensions when using absolute position and both offsets for the axis are defined (either both // left and right or top and bottom). for (ii = 0; ii < 2; ii++) { axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN; if (!float.IsNaN(node.layout.dimensions[dim[axis]]) && !(!float.IsNaN(child.style.dimensions[dim[axis]]) && child.style.dimensions[dim[axis]] >= 0.0) && !float.IsNaN(child.style.position[leading[axis]]) && !float.IsNaN(child.style.position[trailing[axis]])) { child.layout.dimensions[dim[axis]] = Math.Max( boundAxis(child, axis, node.layout.dimensions[dim[axis]] - ((node.style.padding.getWithFallback(leadingSpacing[axis], leading[axis]) + node.style.border.getWithFallback(leadingSpacing[axis], leading[axis])) + (node.style.padding.getWithFallback(trailingSpacing[axis], trailing[axis]) + node.style.border.getWithFallback(trailingSpacing[axis], trailing[axis]))) - (child.style.margin.getWithFallback(leadingSpacing[axis], leading[axis]) + child.style.margin.getWithFallback(trailingSpacing[axis], trailing[axis])) - (float.IsNaN(child.style.position[leading[axis]]) ? 0 : child.style.position[leading[axis]]) - (float.IsNaN(child.style.position[trailing[axis]]) ? 0 : child.style.position[trailing[axis]])), // You never want to go smaller than padding ((child.style.padding.getWithFallback(leadingSpacing[axis], leading[axis]) + child.style.border.getWithFallback(leadingSpacing[axis], leading[axis])) + (child.style.padding.getWithFallback(trailingSpacing[axis], trailing[axis]) + child.style.border.getWithFallback(trailingSpacing[axis], trailing[axis]))) ); } } } float nextContentDim = 0; // It only makes sense to consider a child flexible if we have a computed // dimension for the node. if (isMainDimDefined && (child.style.positionType == CSSPositionType.Relative && child.style.flex > 0)) { flexibleChildrenCount++; totalFlexible += child.style.flex; // Store a private linked list of flexible children so that we can // efficiently traverse them later. if (firstFlexChild == null) { firstFlexChild = child; } if (currentFlexChild != null) { currentFlexChild.nextFlexChild = child; } currentFlexChild = child; // Even if we don't know its exact size yet, we already know the padding, // border and margin. We'll use this partial information, which represents // the smallest possible size for the child, to compute the remaining // available space. nextContentDim = ((child.style.padding.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis])) + (child.style.padding.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) + child.style.border.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]))) + (child.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.margin.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis])); } else { maxWidth = CSSConstants.Undefined; if (!isMainRowDirection) { if ((!float.IsNaN(node.style.dimensions[dim[resolvedRowAxis]]) && node.style.dimensions[dim[resolvedRowAxis]] >= 0.0)) { maxWidth = node.layout.dimensions[dim[resolvedRowAxis]] - paddingAndBorderAxisResolvedRow; } else { maxWidth = parentMaxWidth - (node.style.margin.getWithFallback(leadingSpacing[resolvedRowAxis], leading[resolvedRowAxis]) + node.style.margin.getWithFallback(trailingSpacing[resolvedRowAxis], trailing[resolvedRowAxis])) - paddingAndBorderAxisResolvedRow; } } // This is the main recursive call. We layout non flexible children. if (alreadyComputedNextLayout == 0) { layoutNode(layoutContext, child, maxWidth, direction); } // Absolute positioned elements do not take part of the layout, so we // don't use them to compute mainContentDim if (child.style.positionType == CSSPositionType.Relative) { nonFlexibleChildrenCount++; // At this point we know the final size and margin of the element. nextContentDim = (child.layout.dimensions[dim[mainAxis]] + child.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.margin.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis])); } } // The element we are about to add would make us go to the next line if (isNodeFlexWrap && isMainDimDefined && mainContentDim + nextContentDim > definedMainDim && // If there's only one element, then it's bigger than the content // and needs its own line i != startLine) { nonFlexibleChildrenCount--; alreadyComputedNextLayout = 1; break; } // Disable simple stacking in the main axis for the current line as // we found a non-trivial child. The remaining children will be laid out // in <Loop C>. if (isSimpleStackMain && (child.style.positionType != CSSPositionType.Relative || (child.style.positionType == CSSPositionType.Relative && child.style.flex > 0))) { isSimpleStackMain = false; firstComplexMain = i; } // Disable simple stacking in the cross axis for the current line as // we found a non-trivial child. The remaining children will be laid out // in <Loop D>. if (isSimpleStackCross && (child.style.positionType != CSSPositionType.Relative || (alignItem != CSSAlign.Stretch && alignItem != CSSAlign.FlexStart) || float.IsNaN(child.layout.dimensions[dim[crossAxis]]))) { isSimpleStackCross = false; firstComplexCross = i; } if (isSimpleStackMain) { child.layout.position[pos[mainAxis]] += mainDim; if (isMainDimDefined) { child.layout.position[trailing[mainAxis]] = node.layout.dimensions[dim[mainAxis]] - child.layout.dimensions[dim[mainAxis]] - child.layout.position[pos[mainAxis]]; } mainDim += (child.layout.dimensions[dim[mainAxis]] + child.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.margin.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis])); crossDim = Math.Max(crossDim, boundAxis(child, crossAxis, (child.layout.dimensions[dim[crossAxis]] + child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis])))); } if (isSimpleStackCross) { child.layout.position[pos[crossAxis]] += linesCrossDim + leadingPaddingAndBorderCross; if (isCrossDimDefined) { child.layout.position[trailing[crossAxis]] = node.layout.dimensions[dim[crossAxis]] - child.layout.dimensions[dim[crossAxis]] - child.layout.position[pos[crossAxis]]; } } alreadyComputedNextLayout = 0; mainContentDim += nextContentDim; endLine = i + 1; } // <Loop B> Layout flexible children and allocate empty space // In order to position the elements in the main axis, we have two // controls. The space between the beginning and the first element // and the space between each two elements. float leadingMainDim = 0; float betweenMainDim = 0; // The remaining available space that needs to be allocated float remainingMainDim = 0; if (isMainDimDefined) { remainingMainDim = definedMainDim - mainContentDim; } else { remainingMainDim = Math.Max(mainContentDim, 0) - mainContentDim; } // If there are flexible children in the mix, they are going to fill the // remaining space if (flexibleChildrenCount != 0) { float flexibleMainDim = remainingMainDim / totalFlexible; float baseMainDim; float boundMainDim; // If the flex share of remaining space doesn't meet min/max bounds, // remove this child from flex calculations. currentFlexChild = firstFlexChild; while (currentFlexChild != null) { baseMainDim = flexibleMainDim * currentFlexChild.style.flex + ((currentFlexChild.style.padding.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + currentFlexChild.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis])) + (currentFlexChild.style.padding.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) + currentFlexChild.style.border.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]))); boundMainDim = boundAxis(currentFlexChild, mainAxis, baseMainDim); if (baseMainDim != boundMainDim) { remainingMainDim -= boundMainDim; totalFlexible -= currentFlexChild.style.flex; } currentFlexChild = currentFlexChild.nextFlexChild; } flexibleMainDim = remainingMainDim / totalFlexible; // The non flexible children can overflow the container, in this case // we should just assume that there is no space available. if (flexibleMainDim < 0) { flexibleMainDim = 0; } currentFlexChild = firstFlexChild; while (currentFlexChild != null) { // At this point we know the final size of the element in the main // dimension currentFlexChild.layout.dimensions[dim[mainAxis]] = boundAxis(currentFlexChild, mainAxis, flexibleMainDim * currentFlexChild.style.flex + ((currentFlexChild.style.padding.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + currentFlexChild.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis])) + (currentFlexChild.style.padding.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) + currentFlexChild.style.border.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]))) ); maxWidth = CSSConstants.Undefined; if ((!float.IsNaN(node.style.dimensions[dim[resolvedRowAxis]]) && node.style.dimensions[dim[resolvedRowAxis]] >= 0.0)) { maxWidth = node.layout.dimensions[dim[resolvedRowAxis]] - paddingAndBorderAxisResolvedRow; } else if (!isMainRowDirection) { maxWidth = parentMaxWidth - (node.style.margin.getWithFallback(leadingSpacing[resolvedRowAxis], leading[resolvedRowAxis]) + node.style.margin.getWithFallback(trailingSpacing[resolvedRowAxis], trailing[resolvedRowAxis])) - paddingAndBorderAxisResolvedRow; } // And we recursively call the layout algorithm for this child layoutNode(layoutContext, currentFlexChild, maxWidth, direction); child = currentFlexChild; currentFlexChild = currentFlexChild.nextFlexChild; child.nextFlexChild = null; } // We use justifyContent to figure out how to allocate the remaining // space available } else if (justifyContent != CSSJustify.FlexStart) { if (justifyContent == CSSJustify.Center) { leadingMainDim = remainingMainDim / 2; } else if (justifyContent == CSSJustify.FlexEnd) { leadingMainDim = remainingMainDim; } else if (justifyContent == CSSJustify.SpaceBetween) { remainingMainDim = Math.Max(remainingMainDim, 0); if (flexibleChildrenCount + nonFlexibleChildrenCount - 1 != 0) { betweenMainDim = remainingMainDim / (flexibleChildrenCount + nonFlexibleChildrenCount - 1); } else { betweenMainDim = 0; } } else if (justifyContent == CSSJustify.SpaceAround) { // Space on the edges is half of the space between elements betweenMainDim = remainingMainDim / (flexibleChildrenCount + nonFlexibleChildrenCount); leadingMainDim = betweenMainDim / 2; } } // <Loop C> Position elements in the main axis and compute dimensions // At this point, all the children have their dimensions set. We need to // find their position. In order to do that, we accumulate data in // variables that are also useful to compute the total dimensions of the // container! mainDim += leadingMainDim; for (i = firstComplexMain; i < endLine; ++i) { child = node.getChildAt(i); if (child.style.positionType == CSSPositionType.Absolute && !float.IsNaN(child.style.position[leading[mainAxis]])) { // In case the child is position absolute and has left/top being // defined, we override the position to whatever the user said // (and margin/border). child.layout.position[pos[mainAxis]] = (float.IsNaN(child.style.position[leading[mainAxis]]) ? 0 : child.style.position[leading[mainAxis]]) + node.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]); } else { // If the child is position absolute (without top/left) or relative, // we put it at the current accumulated offset. child.layout.position[pos[mainAxis]] += mainDim; // Define the trailing position accordingly. if (isMainDimDefined) { child.layout.position[trailing[mainAxis]] = node.layout.dimensions[dim[mainAxis]] - child.layout.dimensions[dim[mainAxis]] - child.layout.position[pos[mainAxis]]; } // Now that we placed the element, we need to update the variables // We only need to do that for relative elements. Absolute elements // do not take part in that phase. if (child.style.positionType == CSSPositionType.Relative) { // The main dimension is the sum of all the elements dimension plus // the spacing. mainDim += betweenMainDim + (child.layout.dimensions[dim[mainAxis]] + child.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.margin.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis])); // The cross dimension is the max of the elements dimension since there // can only be one element in that cross dimension. crossDim = Math.Max(crossDim, boundAxis(child, crossAxis, (child.layout.dimensions[dim[crossAxis]] + child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis])))); } } } float containerCrossAxis = node.layout.dimensions[dim[crossAxis]]; if (!isCrossDimDefined) { containerCrossAxis = Math.Max( // For the cross dim, we add both sides at the end because the value // is aggregate via a max function. Intermediate negative values // can mess this computation otherwise boundAxis(node, crossAxis, crossDim + paddingAndBorderAxisCross), paddingAndBorderAxisCross ); } // <Loop D> Position elements in the cross axis for (i = firstComplexCross; i < endLine; ++i) { child = node.getChildAt(i); if (child.style.positionType == CSSPositionType.Absolute && !float.IsNaN(child.style.position[leading[crossAxis]])) { // In case the child is absolutely positionned and has a // top/left/bottom/right being set, we override all the previously // computed positions to set it correctly. child.layout.position[pos[crossAxis]] = (float.IsNaN(child.style.position[leading[crossAxis]]) ? 0 : child.style.position[leading[crossAxis]]) + node.style.border.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]); } else { float leadingCrossDim = leadingPaddingAndBorderCross; // For a relative children, we're either using alignItems (parent) or // alignSelf (child) in order to determine the position in the cross axis if (child.style.positionType == CSSPositionType.Relative) { /*eslint-disable */ // This variable is intentionally re-defined as the code is transpiled to a block scope language CSSAlign alignItem = getAlignItem(node, child); /*eslint-enable */ if (alignItem == CSSAlign.Stretch) { // You can only stretch if the dimension has not already been set // previously. if (float.IsNaN(child.layout.dimensions[dim[crossAxis]])) { child.layout.dimensions[dim[crossAxis]] = Math.Max( boundAxis(child, crossAxis, containerCrossAxis - paddingAndBorderAxisCross - (child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]))), // You never want to go smaller than padding ((child.style.padding.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.border.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis])) + (child.style.padding.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]) + child.style.border.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]))) ); } } else if (alignItem != CSSAlign.FlexStart) { // The remaining space between the parent dimensions+padding and child // dimensions+margin. float remainingCrossDim = containerCrossAxis - paddingAndBorderAxisCross - (child.layout.dimensions[dim[crossAxis]] + child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis])); if (alignItem == CSSAlign.Center) { leadingCrossDim += remainingCrossDim / 2; } else { // CSSAlign.FlexEnd leadingCrossDim += remainingCrossDim; } } } // And we apply the position child.layout.position[pos[crossAxis]] += linesCrossDim + leadingCrossDim; // Define the trailing position accordingly. if (isCrossDimDefined) { child.layout.position[trailing[crossAxis]] = node.layout.dimensions[dim[crossAxis]] - child.layout.dimensions[dim[crossAxis]] - child.layout.position[pos[crossAxis]]; } } } linesCrossDim += crossDim; linesMainDim = Math.Max(linesMainDim, mainDim); linesCount += 1; startLine = endLine; } // <Loop E> // // Note(prenaux): More than one line, we need to layout the crossAxis // according to alignContent. // // Note that we could probably remove <Loop D> and handle the one line case // here too, but for the moment this is safer since it won't interfere with // previously working code. // // See specs: // http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#layout-algorithm // section 9.4 // if (linesCount > 1 && isCrossDimDefined) { float nodeCrossAxisInnerSize = node.layout.dimensions[dim[crossAxis]] - paddingAndBorderAxisCross; float remainingAlignContentDim = nodeCrossAxisInnerSize - linesCrossDim; float crossDimLead = 0; float currentLead = leadingPaddingAndBorderCross; CSSAlign alignContent = node.style.alignContent; if (alignContent == CSSAlign.FlexEnd) { currentLead += remainingAlignContentDim; } else if (alignContent == CSSAlign.Center) { currentLead += remainingAlignContentDim / 2; } else if (alignContent == CSSAlign.Stretch) { if (nodeCrossAxisInnerSize > linesCrossDim) { crossDimLead = (remainingAlignContentDim / linesCount); } } int endIndex = 0; for (i = 0; i < linesCount; ++i) { int startIndex = endIndex; // compute the line's height and find the endIndex float lineHeight = 0; for (ii = startIndex; ii < childCount; ++ii) { child = node.getChildAt(ii); if (child.style.positionType != CSSPositionType.Relative) { continue; } if (child.lineIndex != i) { break; } if (!float.IsNaN(child.layout.dimensions[dim[crossAxis]])) { lineHeight = Math.Max( lineHeight, child.layout.dimensions[dim[crossAxis]] + (child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis])) ); } } endIndex = ii; lineHeight += crossDimLead; for (ii = startIndex; ii < endIndex; ++ii) { child = node.getChildAt(ii); if (child.style.positionType != CSSPositionType.Relative) { continue; } CSSAlign alignContentAlignItem = getAlignItem(node, child); if (alignContentAlignItem == CSSAlign.FlexStart) { child.layout.position[pos[crossAxis]] = currentLead + child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]); } else if (alignContentAlignItem == CSSAlign.FlexEnd) { child.layout.position[pos[crossAxis]] = currentLead + lineHeight - child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]) - child.layout.dimensions[dim[crossAxis]]; } else if (alignContentAlignItem == CSSAlign.Center) { float childHeight = child.layout.dimensions[dim[crossAxis]]; child.layout.position[pos[crossAxis]] = currentLead + (lineHeight - childHeight) / 2; } else if (alignContentAlignItem == CSSAlign.Stretch) { child.layout.position[pos[crossAxis]] = currentLead + child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]); // TODO(prenaux): Correctly set the height of items with undefined // (auto) crossAxis dimension. } } currentLead += lineHeight; } } boolean needsMainTrailingPos = false; boolean needsCrossTrailingPos = false; // If the user didn't specify a width or height, and it has not been set // by the container, then we set it via the children. if (!isMainDimDefined) { node.layout.dimensions[dim[mainAxis]] = Math.Max( // We're missing the last padding at this point to get the final // dimension boundAxis(node, mainAxis, linesMainDim + (node.style.padding.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) + node.style.border.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]))), // We can never assign a width smaller than the padding and borders paddingAndBorderAxisMain ); if (mainAxis == CSS_FLEX_DIRECTION_ROW_REVERSE || mainAxis == CSS_FLEX_DIRECTION_COLUMN_REVERSE) { needsMainTrailingPos = true; } } if (!isCrossDimDefined) { node.layout.dimensions[dim[crossAxis]] = Math.Max( // For the cross dim, we add both sides at the end because the value // is aggregate via a max function. Intermediate negative values // can mess this computation otherwise boundAxis(node, crossAxis, linesCrossDim + paddingAndBorderAxisCross), paddingAndBorderAxisCross ); if (crossAxis == CSS_FLEX_DIRECTION_ROW_REVERSE || crossAxis == CSS_FLEX_DIRECTION_COLUMN_REVERSE) { needsCrossTrailingPos = true; } } // <Loop F> Set trailing position if necessary if (needsMainTrailingPos || needsCrossTrailingPos) { for (i = 0; i < childCount; ++i) { child = node.getChildAt(i); if (needsMainTrailingPos) { child.layout.position[trailing[mainAxis]] = node.layout.dimensions[dim[mainAxis]] - child.layout.dimensions[dim[mainAxis]] - child.layout.position[pos[mainAxis]]; } if (needsCrossTrailingPos) { child.layout.position[trailing[crossAxis]] = node.layout.dimensions[dim[crossAxis]] - child.layout.dimensions[dim[crossAxis]] - child.layout.position[pos[crossAxis]]; } } } // <Loop G> Calculate dimensions for absolutely positioned elements currentAbsoluteChild = firstAbsoluteChild; while (currentAbsoluteChild != null) { // Pre-fill dimensions when using absolute position and both offsets for // the axis are defined (either both left and right or top and bottom). for (ii = 0; ii < 2; ii++) { axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN; if (!float.IsNaN(node.layout.dimensions[dim[axis]]) && !(!float.IsNaN(currentAbsoluteChild.style.dimensions[dim[axis]]) && currentAbsoluteChild.style.dimensions[dim[axis]] >= 0.0) && !float.IsNaN(currentAbsoluteChild.style.position[leading[axis]]) && !float.IsNaN(currentAbsoluteChild.style.position[trailing[axis]])) { currentAbsoluteChild.layout.dimensions[dim[axis]] = Math.Max( boundAxis(currentAbsoluteChild, axis, node.layout.dimensions[dim[axis]] - (node.style.border.getWithFallback(leadingSpacing[axis], leading[axis]) + node.style.border.getWithFallback(trailingSpacing[axis], trailing[axis])) - (currentAbsoluteChild.style.margin.getWithFallback(leadingSpacing[axis], leading[axis]) + currentAbsoluteChild.style.margin.getWithFallback(trailingSpacing[axis], trailing[axis])) - (float.IsNaN(currentAbsoluteChild.style.position[leading[axis]]) ? 0 : currentAbsoluteChild.style.position[leading[axis]]) - (float.IsNaN(currentAbsoluteChild.style.position[trailing[axis]]) ? 0 : currentAbsoluteChild.style.position[trailing[axis]]) ), // You never want to go smaller than padding ((currentAbsoluteChild.style.padding.getWithFallback(leadingSpacing[axis], leading[axis]) + currentAbsoluteChild.style.border.getWithFallback(leadingSpacing[axis], leading[axis])) + (currentAbsoluteChild.style.padding.getWithFallback(trailingSpacing[axis], trailing[axis]) + currentAbsoluteChild.style.border.getWithFallback(trailingSpacing[axis], trailing[axis]))) ); } if (!float.IsNaN(currentAbsoluteChild.style.position[trailing[axis]]) && !!float.IsNaN(currentAbsoluteChild.style.position[leading[axis]])) { currentAbsoluteChild.layout.position[leading[axis]] = node.layout.dimensions[dim[axis]] - currentAbsoluteChild.layout.dimensions[dim[axis]] - (float.IsNaN(currentAbsoluteChild.style.position[trailing[axis]]) ? 0 : currentAbsoluteChild.style.position[trailing[axis]]); } } child = currentAbsoluteChild; currentAbsoluteChild = currentAbsoluteChild.nextAbsoluteChild; child.nextAbsoluteChild = null; } } /** END_GENERATED **/ } }
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using OmniSharp.Models; using Xunit; namespace OmniSharp.Tests { public class SnippetFacts { [Fact] public async Task Can_template_generic_type_argument() { var source = @"public class Class1 { public Class1() { var l = new System.Collections.Generic.Lis$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("List<${1:T}>()$0", completions); } [Fact] public async Task Can_return_method_type_arguments_snippets() { var source = @"using System.Collections.Generic; public class Test { public string Get<SomeType>() { } } public class Class1 { public Class1() { var someObj = new Test(); someObj.G$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("Get<${1:SomeType}>()$0 : string", completions); } [Fact] public async Task Does_not_include_tsource_argument_type() { var source = @"using System.Collections.Generic; using System.Linq; public class Class1 { public Class1() { var l = new List<string>(); l.Firs$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("First()$0 : string", completions); ContainsSnippet("FirstOrDefault(${1:Func<string, bool> predicate})$0 : string", completions); } [Fact] public async Task Does_not_include_tresult_argument_type() { var source = @"using System.Collections.Generic; using System.Linq; public class Class1 { public Class1() { var dict = new Dictionary<string, object>(); dict.Sel$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("Select(${1:Func<KeyValuePair<string, object>, TResult> selector})$0 : IEnumerable<TResult>", completions); } [Fact] public async Task Can_template_field() { var source = @"using System.Collections.Generic; public class Class1 { public int someField; public Class1() { somef$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("someField$0 : int", completions); } [Fact] public async Task Can_return_all_constructors() { var source = @"public class MyClass { public MyClass() {} public MyClass(int param) {} public MyClass(int param, string param) {} } public class Class2 { public Class2() { var c = new My$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("MyClass()$0", completions); ContainsSnippet("MyClass(${1:int param})$0", completions); ContainsSnippet("MyClass(${1:int param}, ${2:string param})$0", completions); } [Fact] public async Task Can_template_generic_type_arguments() { var source = @"using System.Collections.Generic; public class Class1 { public Class1() { var l = new Dict$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("Dictionary<${1:TKey}, ${2:TValue}>()$0", completions); } [Fact] public async Task Can_template_parameter() { var source = @"using System.Collections.Generic; public class Class1 { public Class1() { var l = new Lis$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("List<${1:T}>(${2:IEnumerable<T> collection})$0", completions); } [Fact] public async Task Can_complete_namespace() { var source = @"using Sys$"; var completions = await FindCompletionsAsync(source); ContainsSnippet("System$0", completions); } [Fact] public async Task Can_complete_variable() { var source = @" public class Class1 { public Class1() { var aVariable = 1; av$ } } "; var completions = await FindCompletionsAsync(source); ContainsSnippet("aVariable$0 : int", completions); } [Fact] public async Task Void_methods_end_with_semicolons() { var source = @" using System; public class Class1 { public Class1() { Console.WriteLi$ } } "; var completions = await FindCompletionsAsync(source); ContainsSnippet("WriteLine();$0 : void", completions); } [Fact] public async Task Fuzzy_matches_are_returned_when_first_letters_match() { var source = @" using System; public class Class1 { public Class1() { Console.wrl$ } } "; var completions = await FindCompletionsAsync(source); ContainsSnippet("WriteLine();$0 : void", completions); } [Fact] public async Task Fuzzy_matches_are_not_returned_when_first_letters_do_not_match() { var source = @" using System; public class Class1 { public Class1() { Console.rl$ } } "; var completions = await FindCompletionsAsync(source); Assert.DoesNotContain("WriteLine();$0 : void", completions); } [Fact] public async Task Can_complete_parameter() { var source = @" public class Class1 { public Class1() { } public Class2(Class1 class1) { clas$ } } "; var completions = await FindCompletionsAsync(source); ContainsSnippet("class1$0 : Class1", completions); } [Fact] public async Task Can_return_keywords() { var source = @"usin$"; var completions = await FindCompletionsAsync(source); ContainsSnippet("using", completions); } [Fact] public async Task Returns_enums() { var source = @"public enum Colors { Red, Blue } public class MyClass1 { public MyClass1() { Col$ } }"; var completions = await FindCompletionsAsync(source); Assert.Equal(1, completions.Count()); ContainsSnippet("Colors$0", completions); } [Fact] public async Task Returns_event_without_event_keyword() { var source = @" public class MyClass1 { public event TickHandler TickChanged; public MyClass1() { Tick$ } }"; var completions = await FindCompletionsAsync(source); Assert.Equal(1, completions.Count()); ContainsSnippet("TickChanged$0", completions); } [Fact] public async Task Returns_method_without_optional_params() { var source = @" public class Class1 { public void OptionalParam(int i, string s = null) { } public void DoSomething() { Opt$ } } "; var completions = await FindCompletionsAsync(source); ContainsSnippet("OptionalParam(${1:int i});$0 : void", completions); ContainsSnippet("OptionalParam(${1:int i}, ${2:string s = null});$0 : void", completions); } private void ContainsSnippet(string expected, IEnumerable<string> completions) { if (!completions.Contains(expected)) { System.Console.Error.WriteLine("Did not find - " + expected); foreach (var completion in completions) { System.Console.WriteLine(completion); } } Assert.Contains(expected, completions); } private async Task<IEnumerable<string>> FindCompletionsAsync(string source) { var workspace = TestHelpers.CreateSimpleWorkspace(source); var controller = new OmnisharpController(workspace, new FakeOmniSharpOptions()); var request = CreateRequest(source); var response = await controller.AutoComplete(request); var completions = response as IEnumerable<AutoCompleteResponse>; return completions.Select(completion => BuildCompletion(completion)); } private string BuildCompletion(AutoCompleteResponse completion) { string result = completion.Snippet; if (completion.ReturnType != null) { result += " : " + completion.ReturnType; } return result; } private AutoCompleteRequest CreateRequest(string source, string fileName = "dummy.cs") { var lineColumn = TestHelpers.GetLineAndColumnFromDollar(source); return new AutoCompleteRequest { Line = lineColumn.Line, Column = lineColumn.Column, FileName = fileName, Buffer = source.Replace("$", ""), WordToComplete = GetPartialWord(source), WantSnippet = true, WantReturnType = true }; } private static string GetPartialWord(string editorText) { MatchCollection matches = Regex.Matches(editorText, @"([a-zA-Z0-9_]*)\$"); return matches[0].Groups[1].ToString(); } } }
using System; using System.Runtime.InteropServices; namespace SharpShell.Interop { internal static class Uxtheme { [DllImport("uxtheme.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern IntPtr OpenThemeData(IntPtr hWnd, String classList); [DllImport("uxtheme.dll", ExactSpelling = true)] public extern static Int32 CloseThemeData(IntPtr hTheme); [DllImport("uxtheme", ExactSpelling=true)] public extern static Int32 GetThemePartSize(IntPtr hTheme, IntPtr hdc, int part, WindowPartState state, ref RECT pRect, int eSize, out SIZE size); [DllImport("uxtheme", ExactSpelling=true)] public extern static Int32 GetThemePartSize(IntPtr hTheme, IntPtr hdc, int part, WindowPartState state, IntPtr pRect, int eSize, out SIZE size); [DllImport("uxtheme", ExactSpelling = true)] public extern static Int32 GetThemeInt(IntPtr hTheme, int iPartId, int iStateId, int iPropId, out int piVal); [DllImport("uxtheme", ExactSpelling = true)] public extern static Int32 GetThemeMargins(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, int iPropId, IntPtr prc, out MARGINS pMargins); [DllImport("uxtheme", ExactSpelling = true, CharSet = CharSet.Unicode)] public extern static Int32 GetThemeTextExtent(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, String text, int textLength, UInt32 textFlags, ref RECT boundingRect, out RECT extentRect); [DllImport("uxtheme", ExactSpelling = true, CharSet = CharSet.Unicode)] public extern static Int32 GetThemeTextExtent(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, String text, int textLength, UInt32 textFlags, IntPtr boundingRect, out RECT extentRect); [DllImport("uxtheme", ExactSpelling = true)] public extern static Int32 DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, ref RECT pRect, IntPtr pClipRect); [DllImport("uxtheme", ExactSpelling = true)] public extern static int IsThemeBackgroundPartiallyTransparent(IntPtr hTheme, int iPartId, int iStateId); [DllImport("uxtheme", ExactSpelling = true, CharSet = CharSet.Unicode)] public extern static Int32 DrawThemeText(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, String text, int textLength, UInt32 textFlags, UInt32 textFlags2, ref RECT pRect); [DllImport("uxtheme", ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern Int32 GetBufferedPaintBits(IntPtr hBufferedPaint, out IntPtr ppbBuffer, out int pcxRow); [DllImport("uxtheme.dll", SetLastError = true)] public static extern IntPtr BeginBufferedPaint(IntPtr hdc, ref RECT prcTarget, BP_BUFFERFORMAT dwFormat, ref BP_PAINTPARAMS pPaintParams, out IntPtr phdc); [DllImport("uxtheme.dll")] public static extern IntPtr EndBufferedPaint(IntPtr hBufferedPaint, bool fUpdateTarget); [DllImport("uxtheme.dll", SetLastError = true)] [PreserveSig] public static extern IntPtr BufferedPaintInit(); [DllImport("uxtheme.dll", SetLastError = true)] [PreserveSig] public static extern IntPtr BufferedPaintUnInit(); public enum WindowPartState : int { // Frame States FS_ACTIVE = 1, FS_INACTIVE = 2, // Caption States CS_ACTIVE = 1, CS_INACTIVE = 2, CS_DISABLED = 3, // Max Caption States MXCS_ACTIVE = 1, MXCS_INACTIVE = 2, MXCS_DISABLED = 3, // Min Caption States MNCS_ACTIVE = 1, MNCS_INACTIVE = 2, MNCS_DISABLED = 3, // Horizontal Scrollbar States HSS_NORMAL = 1, HSS_HOT = 2, HSS_PUSHED = 3, HSS_DISABLED = 4, // Horizontal Thumb States HTS_NORMAL = 1, HTS_HOT = 2, HTS_PUSHED = 3, HTS_DISABLED = 4, // Vertical Scrollbar States VSS_NORMAL = 1, VSS_HOT = 2, VSS_PUSHED = 3, VSS_DISABLED = 4, // Vertical Thumb States VTS_NORMAL = 1, VTS_HOT = 2, VTS_PUSHED = 3, VTS_DISABLED = 4, // System Button States SBS_NORMAL = 1, SBS_HOT = 2, SBS_PUSHED = 3, SBS_DISABLED = 4, // Minimize Button States MINBS_NORMAL = 1, MINBS_HOT = 2, MINBS_PUSHED = 3, MINBS_DISABLED = 4, // Maximize Button States MAXBS_NORMAL = 1, MAXBS_HOT = 2, MAXBS_PUSHED = 3, MAXBS_DISABLED = 4, // Restore Button States RBS_NORMAL = 1, RBS_HOT = 2, RBS_PUSHED = 3, RBS_DISABLED = 4, // Help Button States HBS_NORMAL = 1, HBS_HOT = 2, HBS_PUSHED = 3, HBS_DISABLED = 4, // Close Button States CBS_NORMAL = 1, CBS_HOT = 2, CBS_PUSHED = 3, CBS_DISABLED = 4 } } public enum POPUPITEMSTATES { MPI_NORMAL = 1, MPI_HOT = 2, MPI_DISABLED = 3, MPI_DISABLEDHOT = 4, } enum POPUPCHECKBACKGROUNDSTATES { MCB_DISABLED = 1, MCB_NORMAL = 2, MCB_BITMAP = 3, } enum POPUPCHECKSTATES { MC_CHECKMARKNORMAL = 1, MC_CHECKMARKDISABLED = 2, MC_BULLETNORMAL = 3, MC_BULLETDISABLED = 4, } //todo tidy up and name properly. [StructLayout(LayoutKind.Sequential)] public struct ICONINFO { public bool IsIcon; public int xHotspot; public int yHotspot; public IntPtr MaskBitmap; public IntPtr ColorBitmap; } [StructLayout(LayoutKind.Sequential)] public struct BLENDFUNCTION { public byte BlendOp; public byte BlendFlags; public byte SourceConstantAlpha; public byte AlphaFormat; } [StructLayout(LayoutKind.Sequential)] public struct BP_PAINTPARAMS { public uint cbSize; public uint dwFlags; // BPPF_ flags public IntPtr prcExclude; public IntPtr pBlendFunction; } public enum BP_BUFFERFORMAT { BPBF_COMPATIBLEBITMAP, // Compatible bitmap BPBF_DIB, // Device-independent bitmap BPBF_TOPDOWNDIB, // Top-down device-independent bitmap BPBF_TOPDOWNMONODIB // Top-down monochrome device-independent bitmap } }
/* ==================================================================== 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.Collections.Generic; using System.Collections.ObjectModel; using NPOI.SS.Formula.Function; namespace NPOI.SS.Formula.Atp { using System; using System.Collections; using NPOI.SS.Formula; using NPOI.SS.Formula.Eval; using NPOI.SS.Formula.Functions; using NPOI.SS.Formula.UDF; public class NotImplemented : FreeRefFunction { private String _functionName; public NotImplemented(String functionName) { _functionName = functionName; } public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec) { throw new NotImplementedFunctionException(_functionName); } } public class AnalysisToolPak : UDFFinder { public static UDFFinder instance = new AnalysisToolPak(); private static Dictionary<String, FreeRefFunction> _functionsByName = CreateFunctionsMap(); private AnalysisToolPak() { // no instances of this class } public override FreeRefFunction FindFunction(String name) { // functions that are available in Excel 2007+ have a prefix _xlfn. // if you save such a .xlsx workbook as .xls if (name.StartsWith("_xlfn.")) name = name.Substring(6); string key = name.ToUpper(); if (_functionsByName.ContainsKey(key)) return (FreeRefFunction)_functionsByName[key]; return null; } private static Dictionary<String, FreeRefFunction> CreateFunctionsMap() { Dictionary<String, FreeRefFunction> m = new Dictionary<String, FreeRefFunction>(120); r(m, "ACCRINT", null); r(m, "ACCRINTM", null); r(m, "AMORDEGRC", null); r(m, "AMORLINC", null); r(m, "AVERAGEIF", AverageIf.instance); r(m, "AVERAGEIFS", AverageIfs.instance); r(m, "BAHTTEXT", null); r(m, "BESSELI", null); r(m, "BESSELJ", null); r(m, "BESSELK", null); r(m, "BESSELY", null); r(m, "BIN2DEC", Bin2Dec.instance); r(m, "BIN2HEX", null); r(m, "BIN2OCT", null); r(m, "COMPLEX", Complex.Instance); r(m, "CONVERT", null); r(m, "COUNTIFS", Countifs.instance); r(m, "COUPDAYBS", null); r(m, "COUPDAYS", null); r(m, "COUPDAYSNC", null); r(m, "COUPNCD", null); r(m, "COUPNUM", null); r(m, "COUPPCD", null); r(m, "CUBEKPIMEMBER", null); r(m, "CUBEMEMBER", null); r(m, "CUBEMEMBERPROPERTY", null); r(m, "CUBERANKEDMEMBER", null); r(m, "CUBESET", null); r(m, "CUBESETCOUNT", null); r(m, "CUBEVALUE", null); r(m, "CUMIPMT", null); r(m, "CUMPRINC", null); r(m, "DEC2BIN", Dec2Bin.instance); r(m, "DEC2HEX", Dec2Hex.instance); r(m, "DEC2OCT", null); r(m, "DELTA", Delta.instance); r(m, "DISC", null); r(m, "DOLLARDE", null); r(m, "DOLLARFR", null); r(m, "DURATION", null); r(m, "EDATE", EDate.Instance); r(m, "EFFECT", null); r(m, "EOMONTH", EOMonth.instance); r(m, "ERF", null); r(m, "ERFC", null); r(m, "FACTDOUBLE", FactDouble.instance); r(m, "FVSCHEDULE", null); r(m, "GCD", null); r(m, "GESTEP", null); r(m, "HEX2BIN", null); r(m, "HEX2DEC", Hex2Dec.instance); r(m, "HEX2OCT", null); r(m, "IFERROR", IfError.Instance); r(m, "IFNA", IfNa.instance); r(m, "IFS", Ifs.Instance); r(m, "IMABS", null); r(m, "IMAGINARY", Imaginary.instance); r(m, "IMARGUMENT", null); r(m, "IMCONJUGATE", null); r(m, "IMCOS", null); r(m, "IMDIV", null); r(m, "IMEXP", null); r(m, "IMLN", null); r(m, "IMLOG10", null); r(m, "IMLOG2", null); r(m, "IMPOWER", null); r(m, "IMPRODUCT", null); r(m, "IMREAL", ImReal.instance); r(m, "IMSIN", null); r(m, "IMSQRT", null); r(m, "IMSUB", null); r(m, "IMSUM", null); r(m, "INTRATE", null); r(m, "ISEVEN", ParityFunction.IS_EVEN); r(m, "ISODD", ParityFunction.IS_ODD); r(m, "JIS", null); r(m, "LCM", null); r(m, "MAXIFS", Maxifs.instance); r(m, "MDURATION", null); r(m, "MINIFS", Minifs.instance); r(m, "MROUND", MRound.Instance); r(m, "MULTINOMIAL", null); r(m, "NETWORKDAYS", NetworkdaysFunction.instance); r(m, "NOMINAL", null); r(m, "OCT2BIN", null); r(m, "OCT2DEC", Oct2Dec.instance); r(m, "OCT2HEX", null); r(m, "ODDFPRICE", null); r(m, "ODDFYIELD", null); r(m, "ODDLPRICE", null); r(m, "ODDLYIELD", null); r(m, "PRICE", null); r(m, "PRICEDISC", null); r(m, "PRICEMAT", null); r(m, "QUOTIENT", Quotient.instance); r(m, "RANDBETWEEN", RandBetween.Instance); r(m, "RECEIVED", null); r(m, "RTD", null); r(m, "SERIESSUM", null); r(m, "SQRTPI", null); r(m, "SUMIFS", Sumifs.instance); r(m, "SWITCH", Switch.instance); r(m, "TBILLEQ", null); r(m, "TBILLPRICE", null); r(m, "TBILLYIELD", null); r(m, "TEXTJOIN", TextJoinFunction.instance); r(m, "WEEKNUM", WeekNum.instance); r(m, "WORKDAY", WorkdayFunction.instance); r(m, "XIRR", null); r(m, "XNPV", null); r(m, "YEARFRAC", YearFrac.instance); r(m, "YIELD", null); r(m, "YIELDDISC", null); r(m, "YIELDMAT", null); return m; } private static void r(Dictionary<String, FreeRefFunction> m, String functionName, FreeRefFunction pFunc) { FreeRefFunction func = pFunc == null ? new NotImplemented(functionName) : pFunc; m[functionName]= func; } public static bool IsATPFunction(String name) { //AnalysisToolPak inst = (AnalysisToolPak)instance; return AnalysisToolPak._functionsByName.ContainsKey(name); } /** * Returns a collection of ATP function names implemented by POI. * * @return an array of supported functions * @since 3.8 beta6 */ public static ReadOnlyCollection<String> GetSupportedFunctionNames() { AnalysisToolPak inst = (AnalysisToolPak)instance; List<String> lst = new List<String>(); foreach (KeyValuePair<String, FreeRefFunction> me in AnalysisToolPak._functionsByName) { FreeRefFunction func = me.Value; if (func != null && !(func is NotImplemented)) { lst.Add(me.Key); } } return lst.AsReadOnly(); //Collections.unmodifiableCollection(lst); } /** * Returns a collection of ATP function names NOT implemented by POI. * * @return an array of not supported functions * @since 3.8 beta6 */ public static ReadOnlyCollection<String> GetNotSupportedFunctionNames() { AnalysisToolPak inst = (AnalysisToolPak)instance; List<String> lst = new List<String>(); foreach (KeyValuePair<String, FreeRefFunction> me in AnalysisToolPak._functionsByName) { FreeRefFunction func = me.Value; if (func != null && (func is NotImplemented)) { lst.Add(me.Key); } } return lst.AsReadOnly(); //Collections.unmodifiableCollection(lst); } /** * Register a ATP function in runtime. * * @param name the function name * @param func the functoin to register * @throws ArgumentException if the function is unknown or already registered. * @since 3.8 beta6 */ public static void RegisterFunction(String name, FreeRefFunction func) { AnalysisToolPak inst = (AnalysisToolPak)instance; if (!IsATPFunction(name)) { FunctionMetadata metaData = FunctionMetadataRegistry.GetFunctionByName(name); if (metaData != null) { throw new ArgumentException(name + " is a built-in Excel function. " + "Use FunctoinEval.RegisterFunction(String name, Function func) instead."); } else { throw new ArgumentException(name + " is not a function from the Excel Analysis Toolpack."); } } FreeRefFunction f = inst.FindFunction(name); if (f != null && !(f is NotImplemented)) { throw new ArgumentException("POI already implememts " + name + ". You cannot override POI's implementations of Excel functions"); } if (_functionsByName.ContainsKey(name)) _functionsByName[name] = func; else _functionsByName.Add(name, func); } } }
using System; using System.Collections; using UnityEngine; #if !UniRxLibrary using ObservableUnity = UniRx.Observable; #endif namespace UniRx { using System.Threading; #if !(UNITY_METRO || UNITY_WP8) && (UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0_0 || UNITY_3_0 || UNITY_2_6_1 || UNITY_2_6) // Fallback for Unity versions below 4.5 using Hash = System.Collections.Hashtable; using HashEntry = System.Collections.DictionaryEntry; #else // Unity 4.5 release notes: // WWW: deprecated 'WWW(string url, byte[] postData, Hashtable headers)', // use 'public WWW(string url, byte[] postData, Dictionary<string, string> headers)' instead. using Hash = System.Collections.Generic.Dictionary<string, string>; using HashEntry = System.Collections.Generic.KeyValuePair<string, string>; #endif public static partial class ObservableWWW { public static IObservable<string> Get(string url, Hash headers = null, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation)); } public static IObservable<byte[]> GetAndGetBytes(string url, Hash headers = null, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation)); } public static IObservable<WWW> GetWWW(string url, Hash headers = null, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation)); } public static IObservable<string> Post(string url, byte[] postData, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, postData), observer, progress, cancellation)); } public static IObservable<string> Post(string url, byte[] postData, Hash headers, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, postData, headers), observer, progress, cancellation)); } public static IObservable<string> Post(string url, WWWForm content, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, content), observer, progress, cancellation)); } public static IObservable<string> Post(string url, WWWForm content, Hash headers, IProgress<float> progress = null) { var contentHeaders = content.headers; return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation)); } public static IObservable<byte[]> PostAndGetBytes(string url, byte[] postData, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, postData), observer, progress, cancellation)); } public static IObservable<byte[]> PostAndGetBytes(string url, byte[] postData, Hash headers, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, postData, headers), observer, progress, cancellation)); } public static IObservable<byte[]> PostAndGetBytes(string url, WWWForm content, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, content), observer, progress, cancellation)); } public static IObservable<byte[]> PostAndGetBytes(string url, WWWForm content, Hash headers, IProgress<float> progress = null) { var contentHeaders = content.headers; return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation)); } public static IObservable<WWW> PostWWW(string url, byte[] postData, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, postData), observer, progress, cancellation)); } public static IObservable<WWW> PostWWW(string url, byte[] postData, Hash headers, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, postData, headers), observer, progress, cancellation)); } public static IObservable<WWW> PostWWW(string url, WWWForm content, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, content), observer, progress, cancellation)); } public static IObservable<WWW> PostWWW(string url, WWWForm content, Hash headers, IProgress<float> progress = null) { var contentHeaders = content.headers; return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation)); } public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, int version, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, version), observer, progress, cancellation)); } public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, int version, uint crc, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, version, crc), observer, progress, cancellation)); } // over Unity5 supports Hash128 #if !(UNITY_4_7 || UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0_0 || UNITY_3_0 || UNITY_2_6_1 || UNITY_2_6) public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, Hash128 hash128, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, hash128), observer, progress, cancellation)); } public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, Hash128 hash128, uint crc, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, hash128, crc), observer, progress, cancellation)); } #endif // over 4.5, Hash define is Dictionary. // below Unity 4.5, WWW only supports Hashtable. // Unity 4.5, 4.6 WWW supports Dictionary and [Obsolete]Hashtable but WWWForm.content is Hashtable. // Unity 5.0 WWW only supports Dictionary and WWWForm.content is also Dictionary. #if !(UNITY_METRO || UNITY_WP8) && (UNITY_4_5 || UNITY_4_6 || UNITY_4_7) static Hash MergeHash(Hashtable wwwFormHeaders, Hash externalHeaders) { var newHeaders = new Hash(); foreach (DictionaryEntry item in wwwFormHeaders) { newHeaders[item.Key.ToString()] = item.Value.ToString(); } foreach (HashEntry item in externalHeaders) { newHeaders[item.Key] = item.Value; } return newHeaders; } #else static Hash MergeHash(Hash wwwFormHeaders, Hash externalHeaders) { foreach (HashEntry item in externalHeaders) { wwwFormHeaders[item.Key] = item.Value; } return wwwFormHeaders; } #endif static IEnumerator Fetch(WWW www, IObserver<WWW> observer, IProgress<float> reportProgress, CancellationToken cancel) { using (www) { if (reportProgress != null) { while (!www.isDone && !cancel.IsCancellationRequested) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } yield return null; } } else { if (!www.isDone) { yield return www; } } if (cancel.IsCancellationRequested) { yield break; } if (reportProgress != null) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } } if (!string.IsNullOrEmpty(www.error)) { observer.OnError(new WWWErrorException(www, www.text)); } else { observer.OnNext(www); observer.OnCompleted(); } } } static IEnumerator FetchText(WWW www, IObserver<string> observer, IProgress<float> reportProgress, CancellationToken cancel) { using (www) { if (reportProgress != null) { while (!www.isDone && !cancel.IsCancellationRequested) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } yield return null; } } else { if (!www.isDone) { yield return www; } } if (cancel.IsCancellationRequested) { yield break; } if (reportProgress != null) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } } if (!string.IsNullOrEmpty(www.error)) { observer.OnError(new WWWErrorException(www, www.text)); } else { observer.OnNext(www.text); observer.OnCompleted(); } } } static IEnumerator FetchBytes(WWW www, IObserver<byte[]> observer, IProgress<float> reportProgress, CancellationToken cancel) { using (www) { if (reportProgress != null) { while (!www.isDone && !cancel.IsCancellationRequested) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } yield return null; } } else { if (!www.isDone) { yield return www; } } if (cancel.IsCancellationRequested) { yield break; } if (reportProgress != null) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } } if (!string.IsNullOrEmpty(www.error)) { observer.OnError(new WWWErrorException(www, www.text)); } else { observer.OnNext(www.bytes); observer.OnCompleted(); } } } static IEnumerator FetchAssetBundle(WWW www, IObserver<AssetBundle> observer, IProgress<float> reportProgress, CancellationToken cancel) { using (www) { if (reportProgress != null) { while (!www.isDone && !cancel.IsCancellationRequested) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } yield return null; } } else { if (!www.isDone) { yield return www; } } if (cancel.IsCancellationRequested) { yield break; } if (reportProgress != null) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } } if (!string.IsNullOrEmpty(www.error)) { observer.OnError(new WWWErrorException(www, "")); } else { observer.OnNext(www.assetBundle); observer.OnCompleted(); } } } } public class WWWErrorException : Exception { public string RawErrorMessage { get; private set; } public bool HasResponse { get; private set; } public string Text { get; private set; } public System.Net.HttpStatusCode StatusCode { get; private set; } public System.Collections.Generic.Dictionary<string, string> ResponseHeaders { get; private set; } public WWW WWW { get; private set; } // cache the text because if www was disposed, can't access it. public WWWErrorException(WWW www, string text) { this.WWW = www; this.RawErrorMessage = www.error; this.ResponseHeaders = www.responseHeaders; this.HasResponse = false; this.Text = text; var splitted = RawErrorMessage.Split(' ', ':'); if (splitted.Length != 0) { int statusCode; if (int.TryParse(splitted[0], out statusCode)) { this.HasResponse = true; this.StatusCode = (System.Net.HttpStatusCode)statusCode; } } } public override string ToString() { var text = this.Text; if (string.IsNullOrEmpty(text)) { return RawErrorMessage; } else { return RawErrorMessage + " " + text; } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Threading; using System.Globalization; using System.Windows.Forms; using DotSpatial.Positioning.Drawing; using DotSpatial.Positioning.Gps.IO; using DotSpatial.Positioning; #if !PocketPC || DesignTime || Framework20 using System.ComponentModel; #endif #if PocketPC using DotSpatial.Positioning.Licensing; #endif namespace DotSpatial.Positioning.Gps.Controls { /// <summary> /// Represents a user control used to measure speed graphically. /// </summary> #if !PocketPC || DesignTime [ToolboxBitmap(typeof(Speedometer))] [DefaultProperty("Value")] #endif #if Framework20 #if !PocketPC [ToolboxItem(true)] #endif #endif public sealed class Speedometer : PolarControl { #if !PocketPC private System.Threading.Thread InterpolationThread; private bool IsInterpolationActive; //private ManualResetEvent InterpolationThreadWaitHandle = new ManualResetEvent(false); private ManualResetEvent AnimationWaitHandle = new ManualResetEvent(false); private Interpolator ValueInterpolator = new Interpolator(15, InterpolationMethod.CubicEaseInOut); private int InterpolationIndex; private SolidBrush pNeedleShadowBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 0)); private Size pNeedleShadowSize = new Size(5, 5); #endif private Speed pMaximumSpeed = new Speed(120, SpeedUnit.KilometersPerHour); private Speed pSpeedLabelInterval = new Speed(10, SpeedUnit.KilometersPerHour); private Speed pMinorTickInterval = new Speed(5, SpeedUnit.KilometersPerHour); private Speed pMajorTickInterval = new Speed(10, SpeedUnit.KilometersPerHour); private Pen pCenterPen = new Pen(Color.Gray); private Pen pMinorTickPen = new Pen(Color.Black); private Pen pMajorTickPen = new Pen(Color.Black); private string pSpeedLabelFormat = "v"; #if PocketPC private Font pSpeedLabelFont = new Font("Tahoma", 7.0f, FontStyle.Regular); #else private Font pSpeedLabelFont = new Font("Tahoma", 11.0f, FontStyle.Regular); #endif private SolidBrush pSpeedLabelBrush = new SolidBrush(Color.Black); private Speed pSpeed = new Speed(0, SpeedUnit.MetersPerSecond); private SolidBrush pNeedleFillBrush = new SolidBrush(Color.Red); private Pen pNeedleOutlinePen = new Pen(Color.Black); private Angle pMinimumAngle = new Angle(40); private Angle pMaximumAngle = new Angle(320); private static PolarCoordinate[] SpeedometerNeedle = new PolarCoordinate[] { new PolarCoordinate(70, new Angle(1), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(90), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(95), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(100), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(105), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(110), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(115), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(120), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(125), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(130), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(135), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(140), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(145), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(150), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(155), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(160), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(165), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(170), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(175), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(180), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(185), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(190), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(195), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(200), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(205), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(210), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(215), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(220), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(225), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(230), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(235), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(240), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(245), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(250), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(255), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(260), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(265), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(8, new Angle(270), Azimuth.South, PolarCoordinateOrientation.Clockwise), new PolarCoordinate(70, new Angle(359), Azimuth.South, PolarCoordinateOrientation.Clockwise) }; private bool pIsUsingRealTimeData = false; private bool pIsUnitLabelVisible = true; private double ConversionFactor; #if (PocketPC && Framework20) private const int MaximumGracefulShutdownTime = 2000; #elif !PocketPC private const int MaximumGracefulShutdownTime = 500; #endif public event EventHandler<SpeedEventArgs> ValueChanged; public Speedometer() : base("DotSpatial.Positioning Multithreaded Speedometer Control (http://dotspatial.codeplex.com)") { #if !PocketPC // Start the interpolation thread InterpolationThread = new Thread(new ThreadStart(InterpolationLoop)); InterpolationThread.IsBackground = true; InterpolationThread.Name = "DotSpatial.Positioning Speedometer Needle Animation Thread (http://dotspatial.codeplex.com)"; IsInterpolationActive = true; InterpolationThread.Start(); #endif // Set the control to display clockwise from north Orientation = PolarCoordinateOrientation.Clockwise; Origin = Azimuth.South; // The center is zero and edge is 100 CenterR = 0; MaximumR = 100; // Use the speed depending on the local culture if(RegionInfo.CurrentRegion.IsMetric) { pMaximumSpeed = new Speed(120, SpeedUnit.KilometersPerHour); pSpeedLabelInterval = new Speed(10, SpeedUnit.KilometersPerHour); #if PocketPC pMinorTickInterval = new Speed(5, SpeedUnit.KilometersPerHour); #else pMinorTickInterval = new Speed(1, SpeedUnit.KilometersPerHour); #endif pMajorTickInterval = new Speed(10, SpeedUnit.KilometersPerHour); } else { pMaximumSpeed = new Speed(120, SpeedUnit.StatuteMilesPerHour); pSpeedLabelInterval = new Speed(10, SpeedUnit.StatuteMilesPerHour); #if PocketPC pMinorTickInterval = new Speed(5, SpeedUnit.StatuteMilesPerHour); #else pMinorTickInterval = new Speed(1, SpeedUnit.StatuteMilesPerHour); #endif pMajorTickInterval = new Speed(10, SpeedUnit.StatuteMilesPerHour); } // Calculate the factor for converting speed into an angle ConversionFactor = (pMaximumAngle.DecimalDegrees - pMinimumAngle.DecimalDegrees) / pMaximumSpeed.Value; //#if PocketPC && !Framework20 && !DesignTime // // Bind the global event for when speed changes // DotSpatial.Positioning.Gps.IO.Devices.SpeedChanged += new EventHandler<SpeedEventArgs>(Devices_CurrentSpeedChanged); //#endif } //#if !PocketPC || Framework20 // protected override void OnHandleCreated(EventArgs e) // { // base.OnHandleCreated(e); // // Subscribe to events // try // { // // Only hook into events if we're at run-time. Hooking events // // at design-time can actually cause errors in the WF Designer. // if (License.Context.UsageMode == LicenseUsageMode.Runtime) // { // DotSpatial.Positioning.Gps.IO.Devices.SpeedChanged += new EventHandler<SpeedEventArgs>(Devices_CurrentSpeedChanged); // } // } // catch // { // } // } // protected override void OnHandleDestroyed(EventArgs e) // { // try // { // // Only hook into events if we're at run-time. Hooking events // // at design-time can actually cause errors in the WF Designer. // if (License.Context.UsageMode == LicenseUsageMode.Runtime) // { // DotSpatial.Positioning.Gps.IO.Devices.SpeedChanged -= new EventHandler<SpeedEventArgs>(Devices_CurrentSpeedChanged); // } // } // catch // { // } // finally // { // base.OnHandleDestroyed(e); // } // } //#endif protected override void Dispose(bool disposing) { try { // Only hook into events if we're at run-time. Hooking events // at design-time can actually cause errors in the WF Designer. if (LicenseManager.UsageMode == LicenseUsageMode.Runtime && pIsUsingRealTimeData) { Devices.SpeedChanged -= new EventHandler<SpeedEventArgs>(Devices_CurrentSpeedChanged); } } catch { } #if !PocketPC // Get the interpolation thread out of a loop IsInterpolationActive = false; if (InterpolationThread != null) { if (AnimationWaitHandle != null) { try { AnimationWaitHandle.Set(); } catch { } } if (!InterpolationThread.Join(MaximumGracefulShutdownTime)) { try { InterpolationThread.Abort(); } catch { } } } if (AnimationWaitHandle != null) { try { AnimationWaitHandle.Close(); } catch { } finally { AnimationWaitHandle = null; } } #endif if (pCenterPen != null) { try { pCenterPen.Dispose(); } catch { } finally { pCenterPen = null; } } if (pMinorTickPen != null) { try { pMinorTickPen.Dispose(); } catch { } finally { pMinorTickPen = null; } } if (pMajorTickPen != null) { try { pMajorTickPen.Dispose(); } catch { } finally { pMajorTickPen = null; } } if (pSpeedLabelFont != null) { try { pSpeedLabelFont.Dispose(); } catch { } finally { pSpeedLabelFont = null; } } if (pSpeedLabelBrush != null) { try { pSpeedLabelBrush.Dispose(); } catch { } finally { pSpeedLabelBrush = null; } } if (pNeedleFillBrush != null) { try { pNeedleFillBrush.Dispose(); } catch { } finally { pNeedleFillBrush = null; } } if (pNeedleOutlinePen != null) { try { pNeedleOutlinePen.Dispose(); } catch { } finally { pNeedleOutlinePen = null; } } #if !PocketPC if (pNeedleShadowBrush != null) { try { pNeedleShadowBrush.Dispose(); } catch { } finally { pNeedleShadowBrush = null; } } #endif try { base.Dispose(disposing); } catch { } } #if Framework20 && !PocketPC [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override Azimuth Origin { get { return base.Origin; } set { base.Origin = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override Angle Rotation { get { return base.Rotation; } set { base.Rotation = value; } } #endif protected override void OnPaintOffScreen(PaintEventArgs e) { PolarGraphics f = base.CreatePolarGraphics(e.Graphics); // What altitude are we drawing? #if PocketPC Speed SpeedToRender = pSpeed; #else Speed SpeedToRender = new Speed(ValueInterpolator[InterpolationIndex], pSpeed.Units); #endif // Cache drawing intervals and such to prevent a race condition double MinorInterval = pMinorTickInterval.Value; double MajorInterval = pMajorTickInterval.Value; double CachedSpeedLabelInterval = pSpeedLabelInterval.ToUnitType(pMaximumSpeed.Units).Value; Speed MaxSpeed = pMaximumSpeed.Clone(); double MinorStep = pMinorTickInterval.ToUnitType(pMaximumSpeed.Units).Value; double MajorStep = pMajorTickInterval.ToUnitType(pMaximumSpeed.Units).Value; // Draw tick marks double angle; PolarCoordinate start; PolarCoordinate end; #region Draw minor tick marks if (MinorInterval > 0) { for (double speed = 0; speed < MaxSpeed.Value; speed += MinorStep) { // Convert the speed to an angle angle = speed * ConversionFactor + pMinimumAngle.DecimalDegrees; // Get the coordinate of the line's start start = new PolarCoordinate(95, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise); end = new PolarCoordinate(100, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise); // And draw a line f.DrawLine(pMinorTickPen, start, end); } } #endregion #region Draw major tick marks if (MajorInterval > 0) { for (double speed = 0; speed < MaxSpeed.Value; speed += MajorStep) { // Convert the speed to an angle angle = speed * ConversionFactor + pMinimumAngle.DecimalDegrees; // Get the coordinate of the line's start start = new PolarCoordinate(90, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise); end = new PolarCoordinate(100, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise); // And draw a line f.DrawLine(pMajorTickPen, start, end); } #region Draw a major tick mark at the maximum speed // Convert the speed to an angle angle = MaxSpeed.Value * ConversionFactor + pMinimumAngle.DecimalDegrees; // Get the coordinate of the line's start start = new PolarCoordinate(90, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise); end = new PolarCoordinate(100, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise); // And draw a line f.DrawLine(pMajorTickPen, start, end); #endregion } #endregion if (CachedSpeedLabelInterval > 0) { for (double speed = 0; speed < MaxSpeed.Value; speed += CachedSpeedLabelInterval) { // Convert the speed to an angle angle = speed * ConversionFactor + pMinimumAngle.DecimalDegrees; // And draw a line f.DrawCenteredString(new Speed(speed, MaxSpeed.Units).ToString(pSpeedLabelFormat, CultureInfo.CurrentCulture), pSpeedLabelFont, pSpeedLabelBrush, new PolarCoordinate(75, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise)); } // Convert the speed to an angle angle = MaxSpeed.Value * ConversionFactor + pMinimumAngle.DecimalDegrees; // And draw the speed label f.DrawCenteredString(MaxSpeed.ToString(pSpeedLabelFormat, CultureInfo.CurrentCulture), pSpeedLabelFont, pSpeedLabelBrush, new PolarCoordinate(75, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise)); } // Draw the units for the speedometer if (pIsUnitLabelVisible) { f.DrawCenteredString(pMaximumSpeed.ToString("u", CultureInfo.CurrentCulture), pSpeedLabelFont, pSpeedLabelBrush, new PolarCoordinate(90, Angle.Empty, Azimuth.South, PolarCoordinateOrientation.Clockwise)); } PolarCoordinate[] Needle = new PolarCoordinate[SpeedometerNeedle.Length]; for(int index = 0; index < Needle.Length; index++) { Needle[index] = SpeedometerNeedle[index].Rotate((SpeedToRender.ToUnitType(pMaximumSpeed.Units).Value * this.ConversionFactor) + pMinimumAngle.DecimalDegrees); } // Draw an ellipse at the center f.DrawEllipse(pCenterPen, PolarCoordinate.Empty, 10); #if !PocketPC // Now draw a shadow f.Graphics.TranslateTransform(pNeedleShadowSize.Width, pNeedleShadowSize.Height, MatrixOrder.Append); f.FillPolygon(pNeedleShadowBrush, Needle); f.Graphics.ResetTransform(); #endif // Then draw the actual needle f.FillPolygon(pNeedleFillBrush, Needle); f.DrawPolygon(pNeedleOutlinePen, Needle); } #if !PocketPC || DesignTime [Category("Speedometer Needle")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color of the edge of the needle.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color NeedleOutlineColor { get { return pNeedleOutlinePen.Color; } set { if(pNeedleOutlinePen.Color.Equals(value)) return; pNeedleOutlinePen.Color = value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Speedometer Needle")] [DefaultValue(typeof(Color), "Red")] [Description("Controls the color of the interior of the needle.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color NeedleFillColor { get { return pNeedleFillBrush.Color; } set { if(pNeedleFillBrush.Color.Equals(value)) return; pNeedleFillBrush.Color = value; InvokeRepaint(); } } #if !PocketPC [Category("Appearance")] [DefaultValue(typeof(Color), "128, 0, 0, 0")] [Description("Controls the color of the shadow cast by the needle.")] public Color NeedleShadowColor { get { return pNeedleShadowBrush.Color; } set { pNeedleShadowBrush.Color = value; InvokeRepaint(); } } #endif #if !PocketPC [Category("Appearance")] [DefaultValue(typeof(Size), "5, 5")] [Description("Controls the size of the shadow cast by the needle.")] public Size NeedleShadowSize { get { return pNeedleShadowSize; } set { pNeedleShadowSize = value; InvokeRepaint(); } } #endif #if !PocketPC || DesignTime [Category("Behavior")] [Description("Controls the amount of speed being displayed in the control.")] [DefaultValue(typeof(Speed), "0 m/s")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif ////[CLSCompliant(false)] public Speed Value { get { return pSpeed; } set { if(pSpeed.Equals(value)) return; pSpeed = value.ToUnitType(pMaximumSpeed.Units); #if PocketPC InvokeRepaint(); #else if(IsDisposed) return; lock(ValueInterpolator) { // Are we changing direction? if(pSpeed.Value >= ValueInterpolator.Minimum && pSpeed.Value > ValueInterpolator[InterpolationIndex]) { // No. Just set the new maximum ValueInterpolator.Maximum = pSpeed.Value; } else if(pSpeed.Value < ValueInterpolator.Minimum) { // We're changing directions, so stop then accellerate again ValueInterpolator.Minimum = ValueInterpolator[InterpolationIndex]; ValueInterpolator.Maximum = pSpeed.Value; InterpolationIndex = 0; } else if(pSpeed.Value > ValueInterpolator.Minimum && pSpeed.Value < ValueInterpolator[InterpolationIndex]) { // We're changing directions, so stop then accellerate again ValueInterpolator.Minimum = ValueInterpolator[InterpolationIndex]; ValueInterpolator.Maximum = pSpeed.Value; InterpolationIndex = 0; } else if(pSpeed.Value > ValueInterpolator.Maximum) { // No. Just set the new maximum ValueInterpolator.Maximum = pSpeed.Value; } } // And activate the interpolation thread AnimationWaitHandle.Set(); #endif OnValueChanged(new SpeedEventArgs(pSpeed)); } } private void OnValueChanged(SpeedEventArgs e) { if (ValueChanged != null) ValueChanged(this, e); } #if !PocketPC [Category("Behavior")] [DefaultValue(typeof(InterpolationMethod), "CubicEaseInOut")] [Description("Controls how the control smoothly transitions from one value to another.")] ////[CLSCompliant(false)] public InterpolationMethod ValueInterpolationMethod { get { return ValueInterpolator.InterpolationMethod; } set { ValueInterpolator.InterpolationMethod = value; } } #endif #if !PocketPC || DesignTime [Category("Behavior")] [DefaultValue(typeof(Speed), "120 km/h")] [Description("Controls the fastest speed allowed by the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif ////[CLSCompliant(false)] public Speed MaximumSpeed { get { return pMaximumSpeed; } set { if(pMaximumSpeed.Equals(value)) return; pMaximumSpeed = value; // Calculate the factor for converting speed into an angle ConversionFactor = (pMaximumAngle.DecimalDegrees - pMinimumAngle.DecimalDegrees) / pMaximumSpeed.Value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Speed Label")] [DefaultValue(typeof(Speed), "10 km/h")] [Description("Controls the amount of speed in between each label around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif ////[CLSCompliant(false)] public Speed SpeedLabelInterval { get { return pSpeedLabelInterval; } set { if(pSpeedLabelInterval.Equals(value)) return; pSpeedLabelInterval = value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Tick Marks")] [DefaultValue(typeof(Speed), "5 km/h")] [Description("Controls the number of degrees in between each smaller tick mark around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif ////[CLSCompliant(false)] public Speed MinorTickInterval { get { return pMinorTickInterval; } set { if(pMinorTickInterval.Equals(value)) return; pMinorTickInterval = value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Tick Marks")] [DefaultValue(typeof(Speed), "10 km/h")] [Description("Controls the number of degrees in between each larger tick mark around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif ////[CLSCompliant(false)] public Speed MajorTickInterval { get { return pMajorTickInterval; } set { if(pMajorTickInterval.Equals(value)) return; pMajorTickInterval = value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Tick Marks")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color of smaller tick marks drawn around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color MinorTickColor { get { return pMinorTickPen.Color; } set { if(pMinorTickPen.Color.Equals(value)) return; pMinorTickPen.Color = value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Appearance")] [DefaultValue(typeof(bool), "True")] [Description("Controls whether the speed label is drawn in the center of the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public bool IsUnitLabelVisible { get { return pIsUnitLabelVisible; } set { if (pIsUnitLabelVisible.Equals(value)) return; pIsUnitLabelVisible = value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Behavior")] [DefaultValue(typeof(bool), "False")] [Description("Controls whether the Value property is set manually, or automatically read from any available GPS device.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public bool IsUsingRealTimeData { get { return pIsUsingRealTimeData; } set { // Has nothing changed? if(pIsUsingRealTimeData == value) return; // Store the new value pIsUsingRealTimeData = value; if (pIsUsingRealTimeData) { // Only hook into events if we're at run-time. Hooking events // at design-time can actually cause errors in the WF Designer. if (LicenseManager.UsageMode == LicenseUsageMode.Runtime) { Devices.SpeedChanged += new EventHandler<SpeedEventArgs>(Devices_CurrentSpeedChanged); } // Set the current real-time speed Value = Devices.Speed; } else { // Only hook into events if we're at run-time. Hooking events // at design-time can actually cause errors in the WF Designer. if (LicenseManager.UsageMode == LicenseUsageMode.Runtime) { Devices.SpeedChanged -= new EventHandler<SpeedEventArgs>(Devices_CurrentSpeedChanged); } // Reset the value to zero Value = Speed.AtRest; } InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Tick Marks")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color of larger tick marks drawn around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color MajorTickColor { get { return pMajorTickPen.Color; } set { if(pMajorTickPen.Color.Equals(value)) return; pMajorTickPen.Color = value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Speed Label")] [DefaultValue(typeof(string), "v")] [Description("Controls the display format used for speed labels drawn around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public string SpeedLabelFormat { get { return pSpeedLabelFormat; } set { if(pSpeedLabelFormat.Equals(value)) return; pSpeedLabelFormat = value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Speed Label")] #if PocketPC [DefaultValue(typeof(Font), "Tahoma, 7pt")] #else [DefaultValue(typeof(Font), "Tahoma, 11pt")] #endif [Description("Controls the font used for speed labels drawn around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Font SpeedLabelFont { get { return pSpeedLabelFont; } set { if(pSpeedLabelFont.Equals(value)) return; pSpeedLabelFont = value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Speed Label")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color of speed labels drawn around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color SpeedLabelColor { get { return pSpeedLabelBrush.Color; } set { if(pSpeedLabelBrush.Color.Equals(value)) return; pSpeedLabelBrush.Color = value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Behavior")] [DefaultValue(typeof(Angle), "40")] [Description("Controls the angle associated with the smallest possible speed.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif ////[CLSCompliant(false)] public Angle MinimumAngle { get { return pMinimumAngle; } set { if(pMinimumAngle.Equals(value)) return; pMinimumAngle = value; // Calculate the factor for converting speed into an angle ConversionFactor = (pMaximumAngle.DecimalDegrees - pMinimumAngle.DecimalDegrees) / pMaximumSpeed.Value; InvokeRepaint(); } } #if !PocketPC || DesignTime [Category("Behavior")] [DefaultValue(typeof(Angle), "320")] [Description("Controls the angle associated with the largest possible speed.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif ////[CLSCompliant(false)] public Angle MaximumAngle { get { return pMaximumAngle; } set { if(pMaximumAngle.Equals(value)) return; pMaximumAngle = value; // Calculate the factor for converting speed into an angle ConversionFactor = (pMaximumAngle.DecimalDegrees - pMinimumAngle.DecimalDegrees) / pMaximumSpeed.Value; InvokeRepaint(); } } private void Devices_CurrentSpeedChanged(object sender, SpeedEventArgs e) { if(pIsUsingRealTimeData) Value = e.Speed; } #if !PocketPC protected override void OnTargetFrameRateChanged(int framesPerSecond) { base.OnTargetFrameRateChanged(framesPerSecond); // Recalculate our things ValueInterpolator.Count = framesPerSecond; // Adjust the index if it's outside of bounds if(InterpolationIndex > ValueInterpolator.Count - 1) InterpolationIndex = ValueInterpolator.Count - 1; } private void InterpolationLoop() { // Flag that we're alive //InterpolationThreadWaitHandle.Set(); // Are we at the end? while(IsInterpolationActive) { try { // Wait for interpolation to actually be needed //InterpolationThread.Suspend(); AnimationWaitHandle.WaitOne(); // If we're shutting down, just exit if (!IsInterpolationActive) break; // Keep updating interpolation until we're done while (IsInterpolationActive && InterpolationIndex < ValueInterpolator.Count) { // Render the next value InvokeRepaint(); InterpolationIndex++; // Wait for the next frame Thread.Sleep(1000 / ValueInterpolator.Count); } // Reset interpolation ValueInterpolator.Minimum = ValueInterpolator.Maximum; InterpolationIndex = 0; AnimationWaitHandle.Reset(); } catch(ThreadAbortException) { // Just exit! break; } catch { } } // Flag that we're alive //InterpolationThreadWaitHandle.Set(); } #endif } }
// <copyright file="TangoPointCloud.cs" company="Google"> // // Copyright 2016 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. // // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using Tango; using UnityEngine; /// <summary> /// Utility functions for working with and visualizing point cloud data from the /// Tango depth API. Used by the Tango Point Cloud prefab to enable depth point /// functionality. /// </summary> public class TangoPointCloud : MonoBehaviour, ITangoPointCloud { /// <summary> /// If set, the point cloud will be transformed to be in the Area /// Description frame. /// </summary> public bool m_useAreaDescriptionPose; /// <summary> /// If set, update the point cloud's mesh (very slow, useful for debugging). /// </summary> public bool m_updatePointsMesh; /// <summary> /// The points of the point cloud, in world space. /// /// Note that not every member of this array will be filled out. See /// m_pointsCount. /// </summary> [HideInInspector] public Vector3[] m_points; /// <summary> /// The number of points in m_points. /// </summary> [HideInInspector] public int m_pointsCount = 0; /// <summary> /// The average depth (relative to the depth camera). /// </summary> [HideInInspector] public float m_overallZ = 0.0f; /// <summary> /// Time between the last two depth events. /// </summary> [HideInInspector] public float m_depthDeltaTime = 0.0f; /// <summary> /// The position of the floor at y height when FindFloor has been called. /// /// The default value is 0, even if no floor has been found. When FindFloor has completed successfully, /// the result is assigned here. /// </summary> [HideInInspector] public float m_floorPlaneY = 0.0f; /// <summary> /// Check if a floor has been found. /// /// The value is <c>true</c> if the method FindFloor has successfully found a floor, which is assigned /// to m_floorPlaneY. The value is always <c>false</c> if FindFloor has not been called. /// </summary> [HideInInspector] public bool m_floorFound = false; /// <summary> /// The maximum points displayed. Just some constant value. /// </summary> private const int MAX_POINT_COUNT = 61440; /// <summary> /// The minimum number of points near a world position y to determine that it is a reasonable floor. /// </summary> private const int RECOGNITION_THRESHOLD = 1000; /// <summary> /// The minimum number of points near a world position y to determine that it is not simply noise points. /// </summary> private const int NOISE_THRESHOLD = 500; /// <summary> /// The interval in meters between buckets of points. For example, a high sensitivity of 0.01 will group /// points into buckets every 1cm. /// </summary> private const float SENSITIVITY = 0.02f; private TangoApplication m_tangoApplication; // Matrices for transforming pointcloud to world coordinates. // This equation will take account of the camera sensors extrinsic. // Full equation is: // Matrix4x4 unityWorldTDepthCamera = // m_unityWorldTStartService * startServiceTDevice * Matrix4x4.Inverse(m_imuTDevice) * m_imuTDepthCamera; private Matrix4x4 m_unityWorldTStartService; private Matrix4x4 m_imuTDevice; private Matrix4x4 m_imuTDepthCamera; // Matrix for transforming the Unity camera space to the color camera space. private Matrix4x4 m_colorCameraTUnityCamera; /// <summary> /// Color camera intrinsics. /// </summary> private TangoCameraIntrinsics m_colorCameraIntrinsics; /// <summary> /// If the camera data has already been set up. /// </summary> private bool m_cameraDataSetUp; /// <summary> /// The Tango timestamp from the last update of m_points. /// </summary> private double m_depthTimestamp; /// <summary> /// Mesh this script will modify. /// </summary> private Mesh m_mesh; private Renderer m_renderer; // Pose controller from which the offset is queried. private TangoDeltaPoseController m_tangoDeltaPoseController; /// <summary> /// Set to <c>true</c> when currently attempting to find a floor using depth points, <c>false</c> when not /// floor finding. /// </summary> private bool m_findFloorWithDepth = false; /// <summary> /// Used for floor finding, container for the number of points that fall into a y bucket within a sensitivity range. /// </summary> private Dictionary<float, int> m_numPointsAtY; /// <summary> /// Used for floor finding, the list of y value buckets that have sufficient points near that y position height /// to determine that it not simply noise. /// </summary> private List<float> m_nonNoiseBuckets; /// @cond /// <summary> /// Use this for initialization. /// </summary> public void Start() { m_tangoApplication = FindObjectOfType<TangoApplication>(); m_tangoApplication.Register(this); m_tangoDeltaPoseController = FindObjectOfType<TangoDeltaPoseController>(); m_unityWorldTStartService.SetColumn(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_unityWorldTStartService.SetColumn(1, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); m_unityWorldTStartService.SetColumn(2, new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); m_unityWorldTStartService.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); // Constant matrix converting Unity world frame frame to device frame. m_colorCameraTUnityCamera.SetColumn(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_colorCameraTUnityCamera.SetColumn(1, new Vector4(0.0f, -1.0f, 0.0f, 0.0f)); m_colorCameraTUnityCamera.SetColumn(2, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); m_colorCameraTUnityCamera.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); // Assign triangles, note: this is just for visualizing point in the mesh data. m_points = new Vector3[MAX_POINT_COUNT]; m_mesh = GetComponent<MeshFilter>().mesh; m_mesh.Clear(); // Points used for finding floor plane. m_numPointsAtY = new Dictionary<float, int>(); m_nonNoiseBuckets = new List<float>(); m_renderer = GetComponent<Renderer>(); } /// <summary> /// Unity callback when the component gets destroyed. /// </summary> public void OnDestroy() { m_tangoApplication.Unregister(this); } /// <summary> /// Callback that gets called when depth is available from the Tango Service. /// </summary> /// <param name="pointCloud">Depth information from Tango.</param> public void OnTangoPointCloudAvailable(TangoPointCloudData pointCloud) { // Calculate the time since the last successful depth data // collection. if (m_depthTimestamp != 0.0) { m_depthDeltaTime = (float)((pointCloud.m_timestamp - m_depthTimestamp) * 1000.0); } // Fill in the data to draw the point cloud. m_pointsCount = pointCloud.m_numPoints; if (m_pointsCount > 0) { _SetUpCameraData(); TangoCoordinateFramePair pair; TangoPoseData poseData = new TangoPoseData(); // Query pose to transform point cloud to world coordinates, here we are using the timestamp // that we get from depth. if (m_useAreaDescriptionPose) { pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; } else { pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; } PoseProvider.GetPoseAtTime(poseData, pointCloud.m_timestamp, pair); if (poseData.status_code != TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID) { return; } Matrix4x4 startServiceTDevice = poseData.ToMatrix4x4(); // The transformation matrix that represents the pointcloud's pose. // Explanation: // The pointcloud which is in Depth camera's frame, is put in unity world's // coordinate system(wrt unity world). // Then we are extracting the position and rotation from uwTuc matrix and applying it to // the PointCloud's transform. Matrix4x4 unityWorldTDepthCamera = m_unityWorldTStartService * startServiceTDevice * Matrix4x4.Inverse(m_imuTDevice) * m_imuTDepthCamera; transform.position = Vector3.zero; transform.rotation = Quaternion.identity; // Add offset to the pointcloud depending on the offset from TangoDeltaPoseController Matrix4x4 unityWorldOffsetTDepthCamera; if (m_tangoDeltaPoseController != null) { unityWorldOffsetTDepthCamera = m_tangoDeltaPoseController.UnityWorldOffset * unityWorldTDepthCamera; } else { unityWorldOffsetTDepthCamera = unityWorldTDepthCamera; } // Converting points array to world space. m_overallZ = 0; for (int i = 0; i < m_pointsCount; ++i) { Vector3 point = pointCloud[i]; m_points[i] = unityWorldOffsetTDepthCamera.MultiplyPoint3x4(point); m_overallZ += point.z; } m_overallZ = m_overallZ / m_pointsCount; m_depthTimestamp = pointCloud.m_timestamp; if (m_updatePointsMesh) { // Need to update indicies too! int[] indices = new int[m_pointsCount]; for (int i = 0; i < m_pointsCount; ++i) { indices[i] = i; } m_mesh.Clear(); m_mesh.vertices = m_points; m_mesh.SetIndices(indices, MeshTopology.Points, 0); } // The color should be pose relative, we need to store enough info to go back to pose values. m_renderer.material.SetMatrix("depthCameraTUnityWorld", unityWorldOffsetTDepthCamera.inverse); // Try to find the floor using this set of depth points if requested. if (m_findFloorWithDepth) { _FindFloorWithDepth(); } } else { m_overallZ = 0; } } /// @endcond /// <summary> /// Finds the closest point from a point cloud to a position on screen. /// /// This function is slow, as it looks at every single point in the point /// cloud. Avoid calling this more than once a frame. /// </summary> /// <returns>The index of the closest point, or -1 if not found.</returns> /// <param name="cam">The current camera.</param> /// <param name="pos">Position on screen (in pixels).</param> /// <param name="maxDist">The maximum pixel distance to allow.</param> public int FindClosestPoint(Camera cam, Vector2 pos, int maxDist) { int bestIndex = -1; float bestDistSqr = 0; for (int it = 0; it < m_pointsCount; ++it) { Vector3 screenPos3 = cam.WorldToScreenPoint(m_points[it]); Vector2 screenPos = new Vector2(screenPos3.x, screenPos3.y); float distSqr = Vector2.SqrMagnitude(screenPos - pos); if (distSqr > maxDist * maxDist) { continue; } if (bestIndex == -1 || distSqr < bestDistSqr) { bestIndex = it; bestDistSqr = distSqr; } } return bestIndex; } /// <summary> /// Given a screen coordinate, finds a plane that most closely fits the /// depth values in that area. /// /// This function is slow, as it looks at every single point in the point /// cloud. Avoid calling this more than once a frame. This also assumes the /// Unity camera intrinsics match the device's color camera. /// </summary> /// <returns><c>true</c>, if a plane was found; <c>false</c> otherwise.</returns> /// <param name="cam">The Unity camera.</param> /// <param name="pos">The point in screen space to perform detection on.</param> /// <param name="planeCenter">Filled in with the center of the plane in Unity world space.</param> /// <param name="plane">Filled in with a model of the plane in Unity world space.</param> public bool FindPlane(Camera cam, Vector2 pos, out Vector3 planeCenter, out Plane plane) { if (m_pointsCount == 0) { // No points to check, maybe not connected to the service yet planeCenter = Vector3.zero; plane = new Plane(); return false; } Matrix4x4 colorCameraTUnityWorld = m_colorCameraTUnityCamera * cam.transform.worldToLocalMatrix; Vector2 normalizedPos = cam.ScreenToViewportPoint(pos); // If the camera has a TangoARScreen attached, it is not displaying the entire color camera image. Correct // the normalized coordinates by taking the clipping into account. TangoARScreen arScreen = cam.gameObject.GetComponent<TangoARScreen>(); if (arScreen != null) { normalizedPos = arScreen.ViewportPointToCameraImagePoint(normalizedPos); } TangoCameraIntrinsics alignedIntrinsics = new TangoCameraIntrinsics(); VideoOverlayProvider.GetDeviceOientationAlignedIntrinsics(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, alignedIntrinsics); int returnValue = TangoSupport.FitPlaneModelNearClick( m_points, m_pointsCount, m_depthTimestamp, alignedIntrinsics, ref colorCameraTUnityWorld, normalizedPos, out planeCenter, out plane); if (returnValue == Common.ErrorType.TANGO_SUCCESS) { return true; } else { return false; } } /// <summary> /// Start processing the point cloud depth points to find the position of the floor. /// </summary> public void FindFloor() { m_floorFound = false; m_findFloorWithDepth = true; m_floorPlaneY = 0.0f; } /// <summary> /// Sets up extrinsic matrixes and camera intrinsics for this hardware. /// </summary> private void _SetUpCameraData() { if (m_cameraDataSetUp) { return; } double timestamp = 0.0; TangoCoordinateFramePair pair; TangoPoseData poseData = new TangoPoseData(); // Query the extrinsics between IMU and device frame. pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_IMU; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; PoseProvider.GetPoseAtTime(poseData, timestamp, pair); m_imuTDevice = poseData.ToMatrix4x4(); // Query the extrinsics between IMU and depth camera frame. pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_IMU; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_CAMERA_DEPTH; PoseProvider.GetPoseAtTime(poseData, timestamp, pair); m_imuTDepthCamera = poseData.ToMatrix4x4(); // Also get the camera intrinsics m_colorCameraIntrinsics = new TangoCameraIntrinsics(); VideoOverlayProvider.GetIntrinsics(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, m_colorCameraIntrinsics); m_cameraDataSetUp = true; } /// <summary> /// Use the last received set of depth points to find a reasonable floor. /// </summary> private void _FindFloorWithDepth() { m_numPointsAtY.Clear(); m_nonNoiseBuckets.Clear(); // Count each depth point into a bucket based on its world position y value. for (int i = 0; i < m_pointsCount; i++) { Vector3 point = m_points[i]; if (!point.Equals(Vector3.zero)) { // Group similar points into buckets based on sensitivity. float roundedY = Mathf.Round(point.y / SENSITIVITY) * SENSITIVITY; if (!m_numPointsAtY.ContainsKey(roundedY)) { m_numPointsAtY.Add(roundedY, 0); } m_numPointsAtY[roundedY]++; // Check if the y plane is a non-noise plane. if (m_numPointsAtY[roundedY] > NOISE_THRESHOLD && !m_nonNoiseBuckets.Contains(roundedY)) { m_nonNoiseBuckets.Add(roundedY); } } } // Find a plane at the y value. The y value must be below the camera y position. m_nonNoiseBuckets.Sort(); for (int i = 0; i < m_nonNoiseBuckets.Count; i++) { float yBucket = m_nonNoiseBuckets[i]; int numPoints = m_numPointsAtY[yBucket]; if (numPoints > RECOGNITION_THRESHOLD && yBucket < Camera.main.transform.position.y) { // Reject the plane if it is not the lowest. if (yBucket > m_nonNoiseBuckets[0]) { return; } m_floorFound = true; m_findFloorWithDepth = false; m_floorPlaneY = yBucket; m_numPointsAtY.Clear(); m_nonNoiseBuckets.Clear(); } } } }
namespace com.snippets.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using com.snippets.Data.Entities; internal sealed class Configuration : DbMigrationsConfiguration<com.snippets.Data.Entities.snippetsDb> { public Configuration() { Database.SetInitializer<snippetsDb>(new DropCreateDatabaseIfModelChanges<snippetsDb>()); AutomaticMigrationsEnabled = true; } protected override void Seed(com.snippets.Data.Entities.snippetsDb context) { #region Populating Post Types Table context.Posts_Types.AddOrUpdate( p => p.TypeName, new Post_Type { TypeName = "Status" }, new Post_Type { TypeName = "Photo" }, new Post_Type { TypeName = "Snippets" } ); #endregion #region Populating Genders Table context.Genders.AddOrUpdate( p => p.GenderName, new Gender { GenderName = "Male" }, new Gender { GenderName = "Female" } ); #endregion #region Populating Preference Types Table context.PreferenceTypes.AddOrUpdate( p=>p.Type, new PreferenceType{Type="Language", PreferenceTypeId=1} ); #endregion #region Populating Preferences Table context.Preferences.AddOrUpdate( p=>p.PreferenceName, new Preference{PreferenceTypeId=1, PreferenceName="C", LanguageCode="c", photo_url=@"~\Content\images\langs\lang-c.png"}, new Preference{PreferenceTypeId=1, PreferenceName="C++", LanguageCode="cpp", photo_url=@"~\Content\images\langs\lang-cpp.png"}, new Preference{PreferenceTypeId=1, PreferenceName="C#", LanguageCode="csharp", photo_url=@"~\Content\images\langs\lang-csharp.png"}, new Preference{PreferenceTypeId=1, PreferenceName="CSS", LanguageCode="css", photo_url=@"~\Content\images\langs\lang-css.png"}, new Preference{PreferenceTypeId=1, PreferenceName="Flex", LanguageCode="flex", photo_url=@"~\Content\images\langs\lang-flex.png"}, new Preference{PreferenceTypeId=1, PreferenceName="HTML", LanguageCode="html", photo_url=@"~\Content\images\langs\lang-html.png"}, new Preference{PreferenceTypeId=1, PreferenceName="Java", LanguageCode="java", photo_url=@"~\Content\images\langs\lang-java.png"}, new Preference{PreferenceTypeId=1, PreferenceName="Javascript", LanguageCode="javascript", photo_url=@"~\Content\images\langs\lang-js.png"}, new Preference{PreferenceTypeId=1, PreferenceName="Javascript With DOM", LanguageCode="javascript_dom", photo_url=@"~\Content\images\langs\lang-js_dom.png"}, new Preference{PreferenceTypeId=1, PreferenceName="Perl", LanguageCode="perl", photo_url=@"~\Content\images\langs\lang-perl.png"}, new Preference{PreferenceTypeId=1, PreferenceName="PHP", LanguageCode="php", photo_url=@"~\Content\images\langs\lang-php.png"}, new Preference{PreferenceTypeId=1, PreferenceName="Python", LanguageCode="python", photo_url=@"~\Content\images\langs\lang-python.png"}, new Preference{PreferenceTypeId=1, PreferenceName="Ruby", LanguageCode="ruby", photo_url=@"~\Content\images\langs\lang-ruby.png"}, new Preference{PreferenceTypeId=1, PreferenceName="SQL", LanguageCode="sql", photo_url=@"~\Content\images\langs\lang-sql.png"}, new Preference{PreferenceTypeId=1, PreferenceName="XML", LanguageCode="xml", photo_url=@"~\Content\images\langs\lang-xml.png"} ); #endregion #region Populating Countries Table context.Countries.AddOrUpdate( p=>p.CountryName, new Country { CountryName= "Afghanistan", CountryCode="AF" }, new Country { CountryName= "Aland Islands", CountryCode="AX" }, new Country { CountryName= "Albania", CountryCode="AL" }, new Country { CountryName= "Algeria", CountryCode="DZ" }, new Country { CountryName= "American Samoa", CountryCode="AS" }, new Country { CountryName= "Andorra", CountryCode="AD" }, new Country { CountryName= "Angola", CountryCode="AO" }, new Country { CountryName= "Anguilla", CountryCode="AI" }, new Country { CountryName= "Antarctica", CountryCode="AQ" }, new Country { CountryName= "Antigua And Barbuda", CountryCode="AG" }, new Country { CountryName= "Argentina", CountryCode="AR" }, new Country { CountryName= "Armenia", CountryCode="AM" }, new Country { CountryName= "Aruba", CountryCode="AW" }, new Country { CountryName= "Australia", CountryCode="AU" }, new Country { CountryName= "Austria", CountryCode="AT" }, new Country { CountryName= "Azerbaijan", CountryCode="AZ" }, new Country { CountryName= "Bahamas", CountryCode="BS" }, new Country { CountryName= "Bahrain", CountryCode="BH" }, new Country { CountryName= "Bangladesh", CountryCode="BD" }, new Country { CountryName= "Barbados", CountryCode="BB" }, new Country { CountryName= "Belarus", CountryCode="BY" }, new Country { CountryName= "Belgium", CountryCode="BE" }, new Country { CountryName= "Belize", CountryCode="BZ" }, new Country { CountryName= "Benin", CountryCode="BJ" }, new Country { CountryName= "Bermuda", CountryCode="BM" }, new Country { CountryName= "Bhutan", CountryCode="BT" }, new Country { CountryName= "Bolivia", CountryCode="BO" }, new Country { CountryName= "Bosnia And Herzegovina", CountryCode="BA" }, new Country { CountryName= "Botswana", CountryCode="BW" }, new Country { CountryName= "Bouvet Island", CountryCode="BV" }, new Country { CountryName= "Brazil", CountryCode="BR" }, new Country { CountryName= "British Indian Ocean Territory", CountryCode="IO" }, new Country { CountryName= "Brunei Darussalam", CountryCode="BN" }, new Country { CountryName= "Bulgaria", CountryCode="BG" }, new Country { CountryName= "Burkina Faso", CountryCode="BF" }, new Country { CountryName= "Burundi", CountryCode="BI" }, new Country { CountryName= "Cambodia", CountryCode="KH" }, new Country { CountryName= "Cameroon", CountryCode="CM" }, new Country { CountryName= "Canada", CountryCode="CA" }, new Country { CountryName= "Cape Verde", CountryCode="CV" }, new Country { CountryName= "Cayman Islands", CountryCode="KY" }, new Country { CountryName= "Central African Republic", CountryCode="CF" }, new Country { CountryName= "Chad", CountryCode="TD" }, new Country { CountryName= "Chile", CountryCode="CL" }, new Country { CountryName= "China", CountryCode="CN" }, new Country { CountryName= "Christmas Island", CountryCode="CX" }, new Country { CountryName= "Cocos (Keeling) Islands", CountryCode="CC" }, new Country { CountryName= "Colombia", CountryCode="CO" }, new Country { CountryName= "Comoros", CountryCode="KM" }, new Country { CountryName= "Congo", CountryCode="CG" }, new Country { CountryName= "Congo, The Democratic Republic Of The", CountryCode="CD" }, new Country { CountryName= "Cook Islands", CountryCode="CK" }, new Country { CountryName= "Costa Rica", CountryCode="CR" }, new Country { CountryName= "Cote D'Ivoire", CountryCode="CI" }, new Country { CountryName= "Croatia", CountryCode="HR" }, new Country { CountryName= "Cuba", CountryCode="CU" }, new Country { CountryName= "Cyprus", CountryCode="CY" }, new Country { CountryName= "Czech Republic", CountryCode="CZ" }, new Country { CountryName= "Denmark", CountryCode="DK" }, new Country { CountryName= "Djibouti", CountryCode="DJ" }, new Country { CountryName= "Dominica", CountryCode="DM" }, new Country { CountryName= "Dominican Republic", CountryCode="DO" }, new Country { CountryName= "Ecuador", CountryCode="EC" }, new Country { CountryName= "Egypt", CountryCode="EG" }, new Country { CountryName= "El Salvador", CountryCode="SV" }, new Country { CountryName= "Equatorial Guinea", CountryCode="GQ" }, new Country { CountryName= "Eritrea", CountryCode="ER" }, new Country { CountryName= "Estonia", CountryCode="EE" }, new Country { CountryName= "Ethiopia", CountryCode="ET" }, new Country { CountryName= "Falkland Islands (Malvinas)", CountryCode="FK" }, new Country { CountryName= "Faroe Islands", CountryCode="FO" }, new Country { CountryName= "Fiji", CountryCode="FJ" }, new Country { CountryName= "Finland", CountryCode="FI" }, new Country { CountryName= "France", CountryCode="FR" }, new Country { CountryName= "French Guiana", CountryCode="GF" }, new Country { CountryName= "French Polynesia", CountryCode="PF" }, new Country { CountryName= "French Southern Territories", CountryCode="TF" }, new Country { CountryName= "Gabon", CountryCode="GA" }, new Country { CountryName= "Gambia", CountryCode="GM" }, new Country { CountryName= "Georgia", CountryCode="GE" }, new Country { CountryName= "Germany", CountryCode="DE" }, new Country { CountryName= "Ghana", CountryCode="GH" }, new Country { CountryName= "Gibraltar", CountryCode="GI" }, new Country { CountryName= "Greece", CountryCode="GR" }, new Country { CountryName= "Greenland", CountryCode="GL" }, new Country { CountryName= "Grenada", CountryCode="GD" }, new Country { CountryName= "Guadeloupe", CountryCode="GP" }, new Country { CountryName= "Guam", CountryCode="GU" }, new Country { CountryName= "Guatemala", CountryCode="GT" }, new Country { CountryName= "Guernsey", CountryCode=" GG" }, new Country { CountryName= "Guinea", CountryCode="GN" }, new Country { CountryName= "Guinea-Bissau", CountryCode="GW" }, new Country { CountryName= "Guyana", CountryCode="GY" }, new Country { CountryName= "Haiti", CountryCode="HT" }, new Country { CountryName= "Heard Island And Mcdonald Islands", CountryCode="HM" }, new Country { CountryName= "Holy See (Vatican City State)", CountryCode="VA" }, new Country { CountryName= "Honduras", CountryCode="HN" }, new Country { CountryName= "Hong Kong", CountryCode="HK" }, new Country { CountryName= "Hungary", CountryCode="HU" }, new Country { CountryName= "Iceland", CountryCode="IS" }, new Country { CountryName= "India", CountryCode="IN" }, new Country { CountryName= "Indonesia", CountryCode="ID" }, new Country { CountryName= "Iran, Islamic Republic Of", CountryCode="IR" }, new Country { CountryName= "Iraq", CountryCode="IQ" }, new Country { CountryName= "Ireland", CountryCode="IE" }, new Country { CountryName= "Isle Of Man", CountryCode="IM" }, new Country { CountryName= "Israel", CountryCode="IL" }, new Country { CountryName= "Italy", CountryCode="IT" }, new Country { CountryName= "Jamaica", CountryCode="JM" }, new Country { CountryName= "Japan", CountryCode="JP" }, new Country { CountryName= "Jersey", CountryCode="JE" }, new Country { CountryName= "Jordan", CountryCode="JO" }, new Country { CountryName= "Kazakhstan", CountryCode="KZ" }, new Country { CountryName= "Kenya", CountryCode="KE" }, new Country { CountryName= "Kiribati", CountryCode="KI" }, new Country { CountryName= "Korea, Democratic People'S Republic Of", CountryCode="KP" }, new Country { CountryName= "Korea, Republic Of", CountryCode="KR" }, new Country { CountryName= "Kuwait", CountryCode="KW" }, new Country { CountryName= "Kyrgyzstan", CountryCode="KG" }, new Country { CountryName= "Lao People'S Democratic Republic", CountryCode="LA" }, new Country { CountryName= "Latvia", CountryCode="LV" }, new Country { CountryName= "Lebanon", CountryCode="LB" }, new Country { CountryName= "Lesotho", CountryCode="LS" }, new Country { CountryName= "Liberia", CountryCode="LR" }, new Country { CountryName= "Libyan Arab Jamahiriya", CountryCode="LY" }, new Country { CountryName= "Liechtenstein", CountryCode="LI" }, new Country { CountryName= "Lithuania", CountryCode="LT" }, new Country { CountryName= "Luxembourg", CountryCode="LU" }, new Country { CountryName= "Macao", CountryCode="MO" }, new Country { CountryName= "Macedonia, The Former Yugoslav Republic Of", CountryCode="MK" }, new Country { CountryName= "Madagascar", CountryCode="MG" }, new Country { CountryName= "Malawi", CountryCode="MW" }, new Country { CountryName= "Malaysia", CountryCode="MY" }, new Country { CountryName= "Maldives", CountryCode="MV" }, new Country { CountryName= "Mali", CountryCode="ML" }, new Country { CountryName= "Malta", CountryCode="MT" }, new Country { CountryName= "Marshall Islands", CountryCode="MH" }, new Country { CountryName= "Martinique", CountryCode="MQ" }, new Country { CountryName= "Mauritania", CountryCode="MR" }, new Country { CountryName= "Mauritius", CountryCode="MU" }, new Country { CountryName= "Mayotte", CountryCode="YT" }, new Country { CountryName= "Mexico", CountryCode="MX" }, new Country { CountryName= "Micronesia, Federated States Of", CountryCode="FM" }, new Country { CountryName= "Moldova, Republic Of", CountryCode="MD" }, new Country { CountryName= "Monaco", CountryCode="MC" }, new Country { CountryName= "Mongolia", CountryCode="MN" }, new Country { CountryName= "Montserrat", CountryCode="MS" }, new Country { CountryName= "Morocco", CountryCode="MA" }, new Country { CountryName= "Mozambique", CountryCode="MZ" }, new Country { CountryName= "Myanmar", CountryCode="MM" }, new Country { CountryName= "Namibia", CountryCode="NA" }, new Country { CountryName= "Nauru", CountryCode="NR" }, new Country { CountryName= "Nepal", CountryCode="NP" }, new Country { CountryName= "Netherlands", CountryCode="NL" }, new Country { CountryName= "Netherlands Antilles", CountryCode="AN" }, new Country { CountryName= "New Caledonia", CountryCode="NC" }, new Country { CountryName= "New Zealand", CountryCode="NZ" }, new Country { CountryName= "Nicaragua", CountryCode="NI" }, new Country { CountryName= "Niger", CountryCode="NE" }, new Country { CountryName= "Nigeria", CountryCode="NG" }, new Country { CountryName= "Niue", CountryCode="NU" }, new Country { CountryName= "Norfolk Island", CountryCode="NF" }, new Country { CountryName= "Northern Mariana Islands", CountryCode="MP" }, new Country { CountryName= "Norway", CountryCode="NO" }, new Country { CountryName= "Oman", CountryCode="OM" }, new Country { CountryName= "Pakistan", CountryCode="PK" }, new Country { CountryName= "Palau", CountryCode="PW" }, new Country { CountryName= "Palestinian Territory, Occupied", CountryCode="PS" }, new Country { CountryName= "Panama", CountryCode="PA" }, new Country { CountryName= "Papua New Guinea", CountryCode="PG" }, new Country { CountryName= "Paraguay", CountryCode="PY" }, new Country { CountryName= "Peru", CountryCode="PE" }, new Country { CountryName= "Philippines", CountryCode="PH" }, new Country { CountryName= "Pitcairn", CountryCode="PN" }, new Country { CountryName= "Poland", CountryCode="PL" }, new Country { CountryName= "Portugal", CountryCode="PT" }, new Country { CountryName= "Puerto Rico", CountryCode="PR" }, new Country { CountryName= "Qatar", CountryCode="QA" }, new Country { CountryName= "Reunion", CountryCode="RE" }, new Country { CountryName= "Romania", CountryCode="RO" }, new Country { CountryName= "Russian Federation", CountryCode="RU" }, new Country { CountryName= "Rwanda", CountryCode="RW" }, new Country { CountryName= "Saint Helena", CountryCode="SH" }, new Country { CountryName= "Saint Kitts And Nevis", CountryCode="KN" }, new Country { CountryName= "Saint Lucia", CountryCode="LC" }, new Country { CountryName= "Saint Pierre And Miquelon", CountryCode="PM" }, new Country { CountryName= "Saint Vincent And The Grenadines", CountryCode="VC" }, new Country { CountryName= "Samoa", CountryCode="WS" }, new Country { CountryName= "San Marino", CountryCode="SM" }, new Country { CountryName= "Sao Tome And Principe", CountryCode="ST" }, new Country { CountryName= "Saudi Arabia", CountryCode="SA" }, new Country { CountryName= "Senegal", CountryCode="SN" }, new Country { CountryName= "Serbia And Montenegro", CountryCode="CS" }, new Country { CountryName= "Seychelles", CountryCode="SC" }, new Country { CountryName= "Sierra Leone", CountryCode="SL" }, new Country { CountryName= "Singapore", CountryCode="SG" }, new Country { CountryName= "Slovakia", CountryCode="SK" }, new Country { CountryName= "Slovenia", CountryCode="SI" }, new Country { CountryName= "Solomon Islands", CountryCode="SB" }, new Country { CountryName= "Somalia", CountryCode="SO" }, new Country { CountryName= "South Africa", CountryCode="ZA" }, new Country { CountryName= "South Georgia And The South Sandwich Islands", CountryCode="GS" }, new Country { CountryName= "Spain", CountryCode="ES" }, new Country { CountryName= "Sri Lanka", CountryCode="LK" }, new Country { CountryName= "Sudan", CountryCode="SD" }, new Country { CountryName= "Suriname", CountryCode="SR" }, new Country { CountryName= "Svalbard And Jan Mayen", CountryCode="SJ" }, new Country { CountryName= "Swaziland", CountryCode="SZ" }, new Country { CountryName= "Sweden", CountryCode="SE" }, new Country { CountryName= "Switzerland", CountryCode="CH" }, new Country { CountryName= "Syrian Arab Republic", CountryCode="SY" }, new Country { CountryName= "Taiwan, Province Of China", CountryCode="TW" }, new Country { CountryName= "Tajikistan", CountryCode="TJ" }, new Country { CountryName= "Tanzania, United Republic Of", CountryCode="TZ" }, new Country { CountryName= "Thailand", CountryCode="TH" }, new Country { CountryName= "Timor-Leste", CountryCode="TL" }, new Country { CountryName= "Togo", CountryCode="TG" }, new Country { CountryName= "Tokelau", CountryCode="TK" }, new Country { CountryName= "Tonga", CountryCode="TO" }, new Country { CountryName= "Trinidad And Tobago", CountryCode="TT" }, new Country { CountryName= "Tunisia", CountryCode="TN" }, new Country { CountryName= "Turkey", CountryCode="TR" }, new Country { CountryName= "Turkmenistan", CountryCode="TM" }, new Country { CountryName= "Turks And Caicos Islands", CountryCode="TC" }, new Country { CountryName= "Tuvalu", CountryCode="TV" }, new Country { CountryName= "Uganda", CountryCode="UG" }, new Country { CountryName= "Ukraine", CountryCode="UA" }, new Country { CountryName= "United Arab Emirates", CountryCode="AE" }, new Country { CountryName= "United Kingdom", CountryCode="GB" }, new Country { CountryName= "United States", CountryCode="US" }, new Country { CountryName= "United States Minor Outlying Islands", CountryCode="UM" }, new Country { CountryName= "Uruguay", CountryCode="UY" }, new Country { CountryName= "Uzbekistan", CountryCode="UZ" }, new Country { CountryName= "Vanuatu", CountryCode="VU" }, new Country { CountryName= "Venezuela", CountryCode="VE" }, new Country { CountryName= "Viet Nam", CountryCode="VN" }, new Country { CountryName= "Virgin Islands, British", CountryCode="VG" }, new Country { CountryName= "Virgin Islands, U.S.", CountryCode="VI" }, new Country { CountryName= "Wallis And Futuna", CountryCode="WF" }, new Country { CountryName= "Western Sahara", CountryCode="EH" }, new Country { CountryName= "Yemen", CountryCode="YE" }, new Country { CountryName= "Zambia", CountryCode="ZM" }, new Country { CountryName= "Zimbabwe", CountryCode="ZW" }, new Country { CountryName= "(Not Specified)", CountryCode="ZZ" } ); #endregion } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Security.Permissions; using System.Xml; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; using System.Globalization; using System.Threading; using System.Runtime.Remoting.Lifetime; using System.Runtime.Remoting; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class serves as a surrogate for the build engine. It limits access to the build engine by implementing only a subset /// of all public methods on the Engine class. /// </summary> internal sealed class EngineProxy : MarshalByRefObject, IBuildEngine3 { #region Data // The logging interface private EngineLoggingServices loggingServices; // We've already computed and cached the line/column number of the task node in the project file. private bool haveProjectFileLocation = false; // The line number of the task node in the calling project file. private int lineNumber; // The column number of the task node in the calling project file. private int columnNumber; /// <summary> /// The full path to the project that's currently building. /// </summary> private string parentProjectFullFileName; /// <summary> /// The project file that contains the XML for task. This may be an import file and not the primary /// project file /// </summary> private string projectFileOfTaskNode; /// <summary> /// The token identifing the context of this evaluation /// </summary> private int handleId; /// <summary> /// Continue on error value per batch exposed via IBuildEngine /// </summary> private bool continueOnError; /// <summary> /// The module within which this class has been created. Used for all callbacks to /// engine. /// </summary> private TaskExecutionModule parentModule; /// <summary> /// Event contextual information, this tells the loggers where the task events were fired from /// </summary> private BuildEventContext buildEventContext; /// <summary> /// True if the task connected to this proxy is alive /// </summary> private bool activeProxy; /// <summary> /// This reference type is used to block access to a single entry methods of the interface /// </summary> private object callbackMonitor; /// <summary> /// A client sponsor is a class /// which will respond to a lease renewal request and will /// increase the lease time allowing the object to stay in memory /// </summary> private ClientSponsor sponsor; /// <summary> /// Will hold cached copy of typeof(BuildErrorEventArgs) used by each call to LogError /// </summary> private static Type buildErrorEventArgsType = null; /// <summary> /// Will hold cached copy of typeof(BuildErrorEventArgs) used by each call to LogError /// </summary> private static Type buildWarningEventArgsType = null; #endregion /// <summary> /// Private default constructor disallows parameterless instantiation. /// </summary> private EngineProxy() { // do nothing } /// <summary> /// Create an instance of this class to represent the IBuildEngine2 interface to the task /// including the event location where the log messages are raised /// </summary> /// <param name="parentModule">Parent Task Execution Module</param> /// <param name="handleId"></param> /// <param name="parentProjectFullFileName">the full path to the currently building project</param> /// <param name="projectFileOfTaskNode">the path to the actual file (project or targets) where the task invocation is located</param> /// <param name="loggingServices"></param> /// <param name="buildEventContext">Event Context where events will be seen to be raised from. Task messages will get this as their event context</param> internal EngineProxy ( TaskExecutionModule parentModule, int handleId, string parentProjectFullFileName, string projectFileOfTaskNode, EngineLoggingServices loggingServices, BuildEventContext buildEventContext ) { ErrorUtilities.VerifyThrow(parentModule != null, "No parent module."); ErrorUtilities.VerifyThrow(loggingServices != null, "No logging services."); ErrorUtilities.VerifyThrow(projectFileOfTaskNode != null, "Need project file path string"); this.parentModule = parentModule; this.handleId = handleId; this.parentProjectFullFileName = parentProjectFullFileName; this.projectFileOfTaskNode = projectFileOfTaskNode; this.loggingServices = loggingServices; this.buildEventContext = buildEventContext; this.callbackMonitor = new object(); activeProxy = true; } /// <summary> /// Stub implementation -- forwards to engine being proxied. /// </summary> public void LogErrorEvent(BuildErrorEventArgs e) { ErrorUtilities.VerifyThrowArgumentNull(e, "e"); ErrorUtilities.VerifyThrowInvalidOperation(activeProxy == true, "AttemptingToLogFromInactiveTask"); if (parentModule.IsRunningMultipleNodes && !e.GetType().IsSerializable) { loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name); return; } string message = GetUpdatedMessage(e.File, e.Message, parentProjectFullFileName); if (ContinueOnError) { // Convert the error into a warning. We do this because the whole point of // ContinueOnError is that a project author expects that the task might fail, // but wants to ignore the failures. This implies that we shouldn't be logging // errors either, because you should never have a successful build with errors. BuildWarningEventArgs warningEvent = new BuildWarningEventArgs ( e.Subcategory, e.Code, e.File, e.LineNumber, e.ColumnNumber, e.EndLineNumber, e.EndColumnNumber, message, // this is the new message from above e.HelpKeyword, e.SenderName); warningEvent.BuildEventContext = buildEventContext; loggingServices.LogWarningEvent(warningEvent); // Log a message explaining why we converted the previous error into a warning. loggingServices.LogComment(buildEventContext,MessageImportance.Normal, "ErrorConvertedIntoWarning"); } else { if(e.GetType().Equals(BuildErrorEventArgsType)) { // We'd like to add the project file to the subcategory, but since this property // is read-only on the BuildErrorEventArgs type, this requires creating a new // instance. However, if some task logged a custom error type, we don't want to // impolitely (as we already do above on ContinueOnError) throw the custom type // data away. e = new BuildErrorEventArgs ( e.Subcategory, e.Code, e.File, e.LineNumber, e.ColumnNumber, e.EndLineNumber, e.EndColumnNumber, message, // this is the new message from above e.HelpKeyword, e.SenderName ); } e.BuildEventContext = buildEventContext; loggingServices.LogErrorEvent(e); } } /// <summary> /// Stub implementation -- forwards to engine being proxied. /// </summary> public void LogWarningEvent(BuildWarningEventArgs e) { ErrorUtilities.VerifyThrowArgumentNull(e, "e"); ErrorUtilities.VerifyThrowInvalidOperation(activeProxy == true, "AttemptingToLogFromInactiveTask"); if (parentModule.IsRunningMultipleNodes && !e.GetType().IsSerializable) { loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name); return; } if (e.GetType().Equals(BuildWarningEventArgsType)) { // We'd like to add the project file to the message, but since this property // is read-only on the BuildWarningEventArgs type, this requires creating a new // instance. However, if some task logged a custom warning type, we don't want // to impolitely throw the custom type data away. string message = GetUpdatedMessage(e.File, e.Message, parentProjectFullFileName); e = new BuildWarningEventArgs ( e.Subcategory, e.Code, e.File, e.LineNumber, e.ColumnNumber, e.EndLineNumber, e.EndColumnNumber, message, // this is the new message from above e.HelpKeyword, e.SenderName ); } e.BuildEventContext = buildEventContext; loggingServices.LogWarningEvent(e); } /// <summary> /// /// </summary> /// <param name="file">File field from the original BuildEventArgs</param> /// <param name="message">Message field from the original BuildEventArgs</param> /// <param name="parentProjectFullFileName">Full file name of the parent (building) project.</param> /// <returns></returns> private static string GetUpdatedMessage(string file, string message, string parentProjectFullFileName) { #if BUILDING_DF_LKG // In the dogfood LKG, add the project path to the end, because we need it to help diagnose builds. // Don't bother doing anything if we don't have a project path (e.g., we loaded from XML directly) if (String.IsNullOrEmpty(parentProjectFullFileName)) { return message; } // Don't bother adding the project file path if it's already in the file part if(String.Equals(file, parentProjectFullFileName, StringComparison.OrdinalIgnoreCase)) { return message; } string updatedMessage = String.IsNullOrEmpty(message) ? String.Format(CultureInfo.InvariantCulture, "[{0}]", parentProjectFullFileName) : String.Format(CultureInfo.InvariantCulture, "{0} [{1}]", message, parentProjectFullFileName); return updatedMessage; #else // In the regular product, don't modify the message. We want to do this properly, with a field on the event args, in a future version. return message; #endif } /// <summary> /// Stub implementation -- forwards to engine being proxied. /// </summary> public void LogMessageEvent(BuildMessageEventArgs e) { ErrorUtilities.VerifyThrowArgumentNull(e, "e"); ErrorUtilities.VerifyThrowInvalidOperation(activeProxy == true, "AttemptingToLogFromInactiveTask"); if (parentModule.IsRunningMultipleNodes && !e.GetType().IsSerializable) { loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name); return; } e.BuildEventContext = buildEventContext; loggingServices.LogMessageEvent(e); } /// <summary> /// Stub implementation -- forwards to engine being proxied. /// </summary> public void LogCustomEvent(CustomBuildEventArgs e) { ErrorUtilities.VerifyThrowArgumentNull(e, "e"); ErrorUtilities.VerifyThrowInvalidOperation(activeProxy == true, "AttemptingToLogFromInactiveTask"); if (parentModule.IsRunningMultipleNodes && !e.GetType().IsSerializable) { loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name); return; } e.BuildEventContext = buildEventContext; loggingServices.LogCustomEvent(e); } /// <summary> /// Returns true if the ContinueOnError flag was set to true for this particular task /// in the project file. /// </summary> public bool ContinueOnError { get { ErrorUtilities.VerifyThrowInvalidOperation(activeProxy == true, "AttemptingToLogFromInactiveTask"); return this.continueOnError; } } /// <summary> /// Called by the task engine to update the value for each batch /// </summary> /// <param name="shouldContinueOnError"></param> internal void UpdateContinueOnError(bool shouldContinueOnError) { this.continueOnError = shouldContinueOnError; } /// <summary> /// Retrieves the line number of the task node withing the project file that called it. /// </summary> /// <remarks>This method is expensive in terms of perf. Do not call it in mainline scenarios.</remarks> /// <owner>RGoel</owner> public int LineNumberOfTaskNode { get { ErrorUtilities.VerifyThrowInvalidOperation(activeProxy == true, "AttemptingToLogFromInactiveTask"); ComputeProjectFileLocationOfTaskNode(); return this.lineNumber; } } /// <summary> /// Retrieves the line number of the task node withing the project file that called it. /// </summary> /// <remarks>This method is expensive in terms of perf. Do not call it in mainline scenarios.</remarks> /// <owner>RGoel</owner> public int ColumnNumberOfTaskNode { get { ErrorUtilities.VerifyThrowInvalidOperation(activeProxy == true, "AttemptingToLogFromInactiveTask"); ComputeProjectFileLocationOfTaskNode(); return this.columnNumber; } } /// <summary> /// Returns the full path to the project file that contained the call to this task. /// </summary> public string ProjectFileOfTaskNode { get { ErrorUtilities.VerifyThrowInvalidOperation(activeProxy == true, "AttemptingToLogFromInactiveTask"); return projectFileOfTaskNode; } } /// <summary> /// Computes the line/column number of the task node in the project file (or .TARGETS file) /// that called it. /// </summary> private void ComputeProjectFileLocationOfTaskNode() { if (!haveProjectFileLocation) { parentModule.GetLineColumnOfXmlNode(handleId, out this.lineNumber, out this.columnNumber); haveProjectFileLocation = true; } } /// <summary> /// Stub implementation -- forwards to engine being proxied. /// </summary> /// <param name="projectFileName"></param> /// <param name="targetNames"></param> /// <param name="globalProperties"></param> /// <param name="targetOutputs"></param> /// <returns>result of call to engine</returns> public bool BuildProjectFile ( string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs ) { return BuildProjectFile(projectFileName, targetNames, globalProperties, targetOutputs, null); } /// <summary> /// Stub implementation -- forwards to engine being proxied. /// </summary> /// <param name="projectFileName"></param> /// <param name="targetNames"></param> /// <param name="globalProperties"></param> /// <param name="targetOutputs"></param> /// <param name="toolsVersion">Tools Version to override on the project. May be null</param> /// <returns>result of call to engine</returns> public bool BuildProjectFile ( string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs, string toolsVersion ) { lock (callbackMonitor) { ErrorUtilities.VerifyThrowInvalidOperation(activeProxy == true, "AttemptingToLogFromInactiveTask"); // Wrap the project name into an array string[] projectFileNames = new string[1]; projectFileNames[0] = projectFileName; string[] toolsVersions = new string[1]; toolsVersions[0] = toolsVersion; IDictionary[] targetOutputsPerProject = new IDictionary[1]; targetOutputsPerProject[0] = targetOutputs; IDictionary[] globalPropertiesPerProject = new IDictionary[1]; globalPropertiesPerProject[0] = globalProperties; return parentModule.BuildProjectFile(handleId, projectFileNames, targetNames, globalPropertiesPerProject, targetOutputsPerProject, loggingServices, toolsVersions, false, false, buildEventContext); } } /// <summary> /// Stub implementation -- forwards to engine being proxied. /// </summary> /// <param name="projectFileNames"></param> /// <param name="targetNames"></param> /// <param name="globalProperties"></param> /// <param name="targetOutputsPerProject"></param> /// <param name="toolsVersions">Tools Version to overrides per project. May contain null values</param> /// <param name="unloadProjectsOnCompletion"></param> /// <returns>result of call to engine</returns> public bool BuildProjectFilesInParallel ( string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersions, bool useResultsCache, bool unloadProjectsOnCompletion ) { lock (callbackMonitor) { return parentModule.BuildProjectFile(handleId, projectFileNames, targetNames, globalProperties, targetOutputsPerProject, loggingServices, toolsVersions, useResultsCache, unloadProjectsOnCompletion, buildEventContext); } } /// <summary> /// Not implemented for the proxy /// </summary> public void Yield() { } /// <summary> /// Not implemented for the proxy /// </summary> public void Reacquire() { } /// <summary> /// Stub implementation -- forwards to engine being proxied. /// </summary> /// <remarks> /// 1) it is acceptable to pass null for both <c>targetNames</c> and <c>targetOutputs</c> /// 2) if no targets are specified, the default targets are built /// /// </remarks> /// <param name="projectFileNames">The project to build.</param> /// <param name="targetNames">The targets in the project to build (can be null).</param> /// <param name="globalProperties">An array of hashtables of additional global properties to apply /// to the child project (array entries can be null). /// The key and value in the hashtable should both be strings.</param> /// <param name="removeGlobalProperties">A list of global properties which should be removed.</param> /// <param name="toolsVersions">A tools version recognized by the Engine that will be used during this build (can be null).</param> /// <param name="returnTargetOutputs">Should the target outputs be returned in the BuildEngineResults</param> /// <returns>Returns a structure containing the success or failures of the build and the target outputs by project.</returns> public BuildEngineResult BuildProjectFilesInParallel ( string[] projectFileNames, string[] targetNames, IDictionary [] globalProperties, IList<string>[] removeGlobalProperties, string[] toolsVersions, bool returnTargetOutputs ) { lock (callbackMonitor) { ErrorUtilities.VerifyThrowInvalidOperation(activeProxy == true, "AttemptingToLogFromInactiveTask"); ErrorUtilities.VerifyThrowArgumentNull(projectFileNames, "projectFileNames"); ErrorUtilities.VerifyThrowArgumentNull(globalProperties, "globalPropertiesPerProject"); Dictionary<string, ITaskItem[]>[] targetOutputsPerProject = null; if (returnTargetOutputs) { targetOutputsPerProject = new Dictionary<string, ITaskItem[]>[projectFileNames.Length]; for (int i = 0; i < targetOutputsPerProject.Length; i++) { targetOutputsPerProject[i] = new Dictionary<string, ITaskItem[]>(StringComparer.OrdinalIgnoreCase); } } bool result = parentModule.BuildProjectFile(handleId, projectFileNames, targetNames, globalProperties, targetOutputsPerProject, loggingServices, toolsVersions, false, false, buildEventContext); return new BuildEngineResult(result, new List<IDictionary<string, ITaskItem[]>>(targetOutputsPerProject)); } } /// <summary> /// InitializeLifetimeService is called when the remote object is activated. /// This method will determine how long the lifetime for the object will be. /// </summary> public override object InitializeLifetimeService() { // Each MarshalByRef object has a reference to the service which // controls how long the remote object will stay around ILease lease = (ILease)base.InitializeLifetimeService(); // Set how long a lease should be initially. Once a lease expires // the remote object will be disconnected and it will be marked as being availiable // for garbage collection int initialLeaseTime = 1; string initialLeaseTimeFromEnvironment = Environment.GetEnvironmentVariable("MSBUILDENGINEPROXYINITIALLEASETIME"); if (!String.IsNullOrEmpty(initialLeaseTimeFromEnvironment)) { int leaseTimeFromEnvironment; if (int.TryParse(initialLeaseTimeFromEnvironment , out leaseTimeFromEnvironment) && leaseTimeFromEnvironment > 0) { initialLeaseTime = leaseTimeFromEnvironment; } } lease.InitialLeaseTime = TimeSpan.FromMinutes(initialLeaseTime); // Make a new client sponsor. A client sponsor is a class // which will respond to a lease renewal request and will // increase the lease time allowing the object to stay in memory sponsor = new ClientSponsor(); // When a new lease is requested lets make it last 1 minutes longer. int leaseExtensionTime = 1; string leaseExtensionTimeFromEnvironment = Environment.GetEnvironmentVariable("MSBUILDENGINEPROXYLEASEEXTENSIONTIME"); if (!String.IsNullOrEmpty(leaseExtensionTimeFromEnvironment)) { int leaseExtensionFromEnvironment; if (int.TryParse(leaseExtensionTimeFromEnvironment , out leaseExtensionFromEnvironment) && leaseExtensionFromEnvironment > 0) { leaseExtensionTime = leaseExtensionFromEnvironment; } } sponsor.RenewalTime = TimeSpan.FromMinutes(leaseExtensionTime); // Register the sponsor which will increase lease timeouts when the lease expires lease.Register(sponsor); return lease; } /// <summary> /// Indicates to the EngineProxy that it is no longer needed. /// Called by TaskEngine when the task using the EngineProxy is done. /// </summary> internal void MarkAsInActive() { activeProxy = false; // Since the task has a pointer to this class it may store it in a static field. Null out // internal data so the leak of this object doesn't lead to a major memory leak. loggingServices = null; parentModule = null; buildEventContext = null; // Clear out the sponsor (who is responsible for keeping the EngineProxy remoting lease alive until the task is done) // this will be null if the engineproxy was never sent accross an appdomain boundry. if (sponsor != null) { ILease lease = (ILease)RemotingServices.GetLifetimeService(this); if (lease != null) { lease.Unregister(sponsor); } sponsor.Close(); sponsor = null; } } #region Properties /// <summary> /// Provide a way to change the BuildEventContext of the engine proxy. This is important in batching where each batch will need its own buildEventContext. /// </summary> internal BuildEventContext BuildEventContext { get { return buildEventContext; } set { buildEventContext = value; } } /// <summary> /// This property allows a task to query whether or not the system is running in single process mode or multi process mode. /// Single process mode is where the engine is initialized with the number of cpus = 1 and the engine is not a child engine. /// The engine is in multi process mode when the engine is initialized with a number of cpus > 1 or the engine is a child engine. /// </summary> public bool IsRunningMultipleNodes { get { return parentModule.IsRunningMultipleNodes; } } /// <summary> /// Cached copy of typeof(BuildErrorEventArgs) used during each call to LogError /// </summary> private static Type BuildErrorEventArgsType { get { if (buildErrorEventArgsType == null) { buildErrorEventArgsType = typeof(BuildErrorEventArgs); } return buildErrorEventArgsType; } } /// <summary> /// Cached copy of typeof(BuildWarningEventArgs) used during each call to LogWarning /// </summary> private static Type BuildWarningEventArgsType { get { if (buildWarningEventArgsType == null) { buildWarningEventArgsType = typeof(BuildWarningEventArgs); } return buildWarningEventArgsType; } } #endregion } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Threading; using NUnit.Framework; #if !NUNIT using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute; using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute; #endif using NLog.Common; using NLog.Internal; using NLog.Targets; using NLog.Targets.Wrappers; using System.Collections.Generic; [TestFixture] public class AsyncTargetWrapperTests : NLogTestBase { [Test] public void AsyncTargetWrapperInitTest() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget, 300, AsyncTargetWrapperOverflowAction.Grow); Assert.AreEqual(AsyncTargetWrapperOverflowAction.Grow, targetWrapper.OverflowAction); Assert.AreEqual(300, targetWrapper.QueueLimit); Assert.AreEqual(50, targetWrapper.TimeToSleepBetweenBatches); Assert.AreEqual(100, targetWrapper.BatchSize); } [Test] public void AsyncTargetWrapperInitTest2() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, }; Assert.AreEqual(AsyncTargetWrapperOverflowAction.Discard, targetWrapper.OverflowAction); Assert.AreEqual(10000, targetWrapper.QueueLimit); Assert.AreEqual(50, targetWrapper.TimeToSleepBetweenBatches); Assert.AreEqual(100, targetWrapper.BatchSize); } [Test] public void AsyncTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper { WrappedTarget = myTarget, }; targetWrapper.Initialize(null); myTarget.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; ManualResetEvent continuationHit = new ManualResetEvent(false); Thread continuationThread = null; AsyncContinuation continuation = ex => { lastException = ex; continuationThread = Thread.CurrentThread; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); // continuation was not hit continuationHit.WaitOne(); Assert.AreNotSame(continuationThread, Thread.CurrentThread); Assert.IsNull(lastException); Assert.AreEqual(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.AreNotSame(continuationThread, Thread.CurrentThread); Assert.IsNull(lastException); Assert.AreEqual(2, myTarget.WriteCount); } [Test] public void AsyncTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget); targetWrapper.Initialize(null); myTarget.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(2, myTarget.WriteCount); } [Test] public void AsyncTargetWrapperAsyncWithExceptionTest1() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var targetWrapper = new AsyncTargetWrapper(myTarget); targetWrapper.Initialize(null); myTarget.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.IsNotNull(lastException); Assert.IsInstanceOfType(typeof(InvalidOperationException), lastException); // no flush on exception Assert.AreEqual(0, myTarget.FlushCount); Assert.AreEqual(1, myTarget.WriteCount); continuationHit.Reset(); lastException = null; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.IsNotNull(lastException); Assert.IsInstanceOfType(typeof(InvalidOperationException), lastException); Assert.AreEqual(0, myTarget.FlushCount); Assert.AreEqual(2, myTarget.WriteCount); } [Test] public void AsyncTargetWrapperFlushTest() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var targetWrapper = new AsyncTargetWrapper(myTarget) { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, }; targetWrapper.Initialize(null); myTarget.Initialize(null); List<Exception> exceptions = new List<Exception>(); int eventCount = 5000; for (int i = 0; i < eventCount; ++i) { targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation( ex => { lock (exceptions) { exceptions.Add(ex); } })); } Exception lastException = null; ManualResetEvent mre = new ManualResetEvent(false); string internalLog = RunAndCaptureInternalLog( () => { targetWrapper.Flush( cont => { try { // by this time all continuations should be completed Assert.AreEqual(eventCount, exceptions.Count); // with just 1 flush of the target Assert.AreEqual(1, myTarget.FlushCount); // and all writes should be accounted for Assert.AreEqual(eventCount, myTarget.WriteCount); } catch (Exception ex) { lastException = ex; } finally { mre.Set(); } }); mre.WaitOne(); }, LogLevel.Trace); if (lastException != null) { Assert.Fail(lastException.ToString() + "\r\n" + internalLog); } } [Test] public void AsyncTargetWrapperCloseTest() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var targetWrapper = new AsyncTargetWrapper(myTarget) { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, TimeToSleepBetweenBatches = 1000, }; targetWrapper.Initialize(null); myTarget.Initialize(null); bool continuationHit = false; targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { continuationHit = true; })); // quickly close the target before the timer elapses targetWrapper.Close(); } [Test] public void AsyncTargetWrapperExceptionTest() { var targetWrapper = new AsyncTargetWrapper { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, TimeToSleepBetweenBatches = 500, WrappedTarget = new DebugTarget(), }; targetWrapper.Initialize(null); // null out wrapped target - will cause exception on the timer thread targetWrapper.WrappedTarget = null; string internalLog = RunAndCaptureInternalLog( () => { targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { })); Thread.Sleep(3000); }, LogLevel.Trace); targetWrapper.Close(); Assert.IsTrue(internalLog.StartsWith("Error Error in lazy writer timer procedure: System.NullReferenceException", StringComparison.Ordinal), internalLog); } class MyAsyncTarget : Target { public int FlushCount; public int WriteCount; protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.IsTrue(this.FlushCount <= this.WriteCount); Interlocked.Increment(ref this.WriteCount); ThreadPool.QueueUserWorkItem( s => { if (this.ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { Interlocked.Increment(ref this.FlushCount); ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } protected override void Write(LogEventInfo logEvent) { Assert.IsTrue(this.FlushCount <= this.WriteCount); this.WriteCount++; } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; asyncContinuation(null); } } } }
#pragma warning disable SA1633 // File should have header - This is an imported file, // original header with license shall remain the same namespace UtfUnknown.Core.Models.MultiByte.Korean; internal class EUCKRSMModel : StateMachineModel { private static readonly int[] EUCKR_cls = { //BitPacket.Pack4bits(0,1,1,1,1,1,1,1), // 00 - 07 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 00 - 07 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 0, 0), // 08 - 0f BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 10 - 17 BitPackage.Pack4bits( 1, 1, 1, 0, 1, 1, 1, 1), // 18 - 1f BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 20 - 27 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 28 - 2f BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 30 - 37 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 38 - 3f BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 40 - 47 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 48 - 4f BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 50 - 57 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 58 - 5f BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 60 - 67 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 68 - 6f BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 70 - 77 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 78 - 7f BitPackage.Pack4bits( 0, 0, 0, 0, 0, 0, 0, 0), // 80 - 87 BitPackage.Pack4bits( 0, 0, 0, 0, 0, 0, 0, 0), // 88 - 8f BitPackage.Pack4bits( 0, 0, 0, 0, 0, 0, 0, 0), // 90 - 97 BitPackage.Pack4bits( 0, 0, 0, 0, 0, 0, 0, 0), // 98 - 9f BitPackage.Pack4bits( 0, 2, 2, 2, 2, 2, 2, 2), // a0 - a7 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 3, 3, 3), // a8 - af BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // b0 - b7 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // b8 - bf BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // c0 - c7 BitPackage.Pack4bits( 2, 3, 2, 2, 2, 2, 2, 2), // c8 - cf BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // d0 - d7 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // d8 - df BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // e0 - e7 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // e8 - ef BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // f0 - f7 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 0) // f8 - ff }; private static readonly int[] EUCKR_st = { BitPackage.Pack4bits( ERROR, START, 3, ERROR, ERROR, ERROR, ERROR, ERROR), //00-07 BitPackage.Pack4bits( ITSME, ITSME, ITSME, ITSME, ERROR, ERROR, START, START) //08-0f }; private static readonly int[] EUCKRCharLenTable = { 0, 1, 2, 0 }; public EUCKRSMModel() : base( new BitPackage( BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, EUCKR_cls), 4, new BitPackage( BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, EUCKR_st), EUCKRCharLenTable, CodepageName.EUC_KR) { } }
using SolidEdgeCommunity.Reader.Assembly; using SolidEdgeCommunity.Reader.Draft; using SolidEdgeCommunity.Reader.Native; using SolidEdgeCommunity.Reader.Part; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text; namespace SolidEdgeCommunity.Reader { public abstract partial class SolidEdgeDocument : CompoundFile { [DllImport("gdi32.dll", EntryPoint = "GetDIBits")] static extern int GetDIBits([In] IntPtr hdc, [In] IntPtr hbmp, uint uStartScan, uint cScanLines, [Out] byte[] lpvBits, ref BITMAPINFO lpbi, int uUsage); private Version _createdVersion; private Version _lastSavedVersion; internal SolidEdgeDocument(IStorage storage, System.Runtime.InteropServices.ComTypes.STATSTG statstg) : base(storage, statstg) { //HRESULT hr = HRESULT.S_OK; //System.Runtime.InteropServices.ComTypes.STATSTG[] elements; //if (NativeMethods.Succeeded(hr = storage.EnumElements(out elements))) //{ // foreach (System.Runtime.InteropServices.ComTypes.STATSTG element in elements) // { // Console.WriteLine("{0} - {1}", element.pwcsName, element.clsid); // } //} } internal static SolidEdgeDocument InvokeConstructor(Type type, IStorage storage, System.Runtime.InteropServices.ComTypes.STATSTG statstg) { ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(IStorage), typeof(System.Runtime.InteropServices.ComTypes.STATSTG) }, null); if (ctor != null) { return (SolidEdgeDocument)ctor.Invoke(new object[] { storage, statstg }); } else { Marshal.ThrowExceptionForHR(HRESULT.CO_E_CANTDETERMINECLASS); } return null; } internal static SolidEdgeDocument FromIStorage(IStorage storage) { if (storage == null) throw new ArgumentNullException("storage"); SolidEdgeDocument document = null; System.Runtime.InteropServices.ComTypes.STATSTG statstg = statstg = storage.GetStatistics(); // For now there is a 1 - 1 mapping. Type[] types = System.Reflection.Assembly.GetExecutingAssembly().GetSolidEdgeDocumentTypes(statstg.clsid); if (types.Length == 0) { Marshal.ThrowExceptionForHR(HRESULT.CO_E_CANTDETERMINECLASS); } else if (types.Length == 1) { document = InvokeConstructor(types[0], storage, statstg); } else // Future possibility for multiple types. i.e Guid.Empty { Marshal.ThrowExceptionForHR(HRESULT.CO_E_CANTDETERMINECLASS); } return document; } protected virtual void LoadBuildVersions() { BUILDVERSIONS buildVersions = default(BUILDVERSIONS); if (NativeMethods.Succeeded(RootStorage.ReadStructure<BUILDVERSIONS>(StreamName.BuildVersions, out buildVersions))) { _createdVersion = buildVersions.CreatedVersion.ToVersion(); _lastSavedVersion = buildVersions.LastSavedVersion.ToVersion(); } } protected virtual DocumentStatus GetDocumentStatus() { if (ExtendedSummaryInformation != null) { return (DocumentStatus)ExtendedSummaryInformation.Status; } else { return DocumentStatus.Unknown; } } protected virtual DocumentType GetDocumentType() { Type type = this.GetType(); SolidEdgeDocumentAttribute attribute = type.GetSolidEdgeDocumentAttribute(); if (attribute != null) { return attribute.DocumentType; } return DocumentType.Unknown; } public static Version GetCreatedVersion(string path) { using (SolidEdgeDocument document = SolidEdgeDocument.Open(path)) { return document.CreatedVersion; } } public static Version GetLastSavedVersion(string path) { using (SolidEdgeDocument document = SolidEdgeDocument.Open(path)) { return document.LastSavedVersion; } } public static DocumentStatus GetStatus(string path) { using (SolidEdgeDocument document = SolidEdgeDocument.Open(path)) { return document.Status; } } // Getting inconsistent results. Need to work on code. public Bitmap GetThumbnail() { Bitmap bitmap = null; PROPVARIANT propvar = default(PROPVARIANT); try { Marshal.ThrowExceptionForHR(GetPropertyValue(FMTID.FMTID_ExtendedSummaryInformation, (uint)ExtendedSummaryInformationConstants.LARGE_DIB, out propvar)); if (propvar.Type == VarEnum.VT_CF) { // Get CLIPDATA. CLIPDATA clipdata = propvar.GetCLIPDATA(); // built-in Windows format if (clipdata.ulClipFmt == -1) { // Pointer to BITMAPINFOHEADER. IntPtr pBIH = clipdata.pClipData; bitmap = DibToBitmap.Convert(pBIH); } else { Console.WriteLine("CLIP FORMAT ERROR"); Marshal.ThrowExceptionForHR(HRESULT.DV_E_CLIPFORMAT); } } else { Console.WriteLine("INVALID VARIANT ERROR"); Marshal.ThrowExceptionForHR(HRESULT.ERROR_INVALID_VARIANT); } } catch { throw; } finally { propvar.Clear(); } return bitmap; } public new static SolidEdgeDocument Open(string path) { SolidEdgeDocument document = null; IStorage storage = null; try { storage = CompoundFile.OpenStorage(path); document = FromIStorage(storage); } catch { throw; } finally { if (document == null) { if (storage != null) { storage.FinalRelease(); } } } return document; } public static SolidEdgeDocument Open(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); IStorage storage = CompoundFile.OpenStorage(stream); bool flag = false; try { return FromIStorage(storage); } catch { flag = true; throw; } finally { if ((flag) && (storage != null)) { storage.FinalRelease(); } } } internal static T Open<T>(string path) { SolidEdgeDocument document = null; bool flag = false; try { document = Open(path); return (T)Convert.ChangeType(document, typeof(T)); } catch { flag = true; throw; } finally { if ((flag) && (document != null)) { document.Close(); } } } #region Properties /// <summary> /// /// </summary> public Version CreatedVersion { get { // Note that build versions are delay loaded. if (_createdVersion == null) { LoadBuildVersions(); } return _createdVersion; } } /// <summary> /// /// </summary> public DocumentType DocumentType { get { return GetDocumentType(); } } /// <summary> /// /// </summary> public Version LastSavedVersion { get { // Note that build versions are delay loaded. if (_lastSavedVersion == null) { LoadBuildVersions(); } return _lastSavedVersion; } } /// <summary> /// /// </summary> public DocumentStatus Status { get { return GetDocumentStatus(); } } /// <summary> /// /// </summary> public ExtendedSummaryInformationPropertySet ExtendedSummaryInformation { get { return PropertySets.OfType<ExtendedSummaryInformationPropertySet>().FirstOrDefault(); } } /// <summary> /// /// </summary> public MechanicalModelingPropertySet MechanicalModeling { get { return PropertySets.OfType<MechanicalModelingPropertySet>().FirstOrDefault(); } } /// <summary> /// /// </summary> public ProjectInformationPropertySet ProjectInformation { get { return PropertySets.OfType<ProjectInformationPropertySet>().FirstOrDefault(); } } #endregion } }
#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; using System.Globalization; using System.Runtime.Serialization.Formatters; using Microsoft.Identity.Json.Utilities; using System.Runtime.Serialization; namespace Microsoft.Identity.Json.Serialization { internal class JsonSerializerProxy : JsonSerializer { private readonly JsonSerializerInternalReader _serializerReader; private readonly JsonSerializerInternalWriter _serializerWriter; private readonly JsonSerializer _serializer; public override event EventHandler<ErrorEventArgs> Error { add => _serializer.Error += value; remove => _serializer.Error -= value; } public override IReferenceResolver ReferenceResolver { get => _serializer.ReferenceResolver; set => _serializer.ReferenceResolver = value; } public override ITraceWriter TraceWriter { get => _serializer.TraceWriter; set => _serializer.TraceWriter = value; } public override IEqualityComparer EqualityComparer { get => _serializer.EqualityComparer; set => _serializer.EqualityComparer = value; } public override JsonConverterCollection Converters => _serializer.Converters; public override DefaultValueHandling DefaultValueHandling { get => _serializer.DefaultValueHandling; set => _serializer.DefaultValueHandling = value; } public override IContractResolver ContractResolver { get => _serializer.ContractResolver; set => _serializer.ContractResolver = value; } public override MissingMemberHandling MissingMemberHandling { get => _serializer.MissingMemberHandling; set => _serializer.MissingMemberHandling = value; } public override NullValueHandling NullValueHandling { get => _serializer.NullValueHandling; set => _serializer.NullValueHandling = value; } public override ObjectCreationHandling ObjectCreationHandling { get => _serializer.ObjectCreationHandling; set => _serializer.ObjectCreationHandling = value; } public override ReferenceLoopHandling ReferenceLoopHandling { get => _serializer.ReferenceLoopHandling; set => _serializer.ReferenceLoopHandling = value; } public override PreserveReferencesHandling PreserveReferencesHandling { get => _serializer.PreserveReferencesHandling; set => _serializer.PreserveReferencesHandling = value; } public override TypeNameHandling TypeNameHandling { get => _serializer.TypeNameHandling; set => _serializer.TypeNameHandling = value; } public override MetadataPropertyHandling MetadataPropertyHandling { get => _serializer.MetadataPropertyHandling; set => _serializer.MetadataPropertyHandling = value; } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public override FormatterAssemblyStyle TypeNameAssemblyFormat { get => _serializer.TypeNameAssemblyFormat; set => _serializer.TypeNameAssemblyFormat = value; } public override TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get => _serializer.TypeNameAssemblyFormatHandling; set => _serializer.TypeNameAssemblyFormatHandling = value; } public override ConstructorHandling ConstructorHandling { get => _serializer.ConstructorHandling; set => _serializer.ConstructorHandling = value; } //[Obsolete("Binder is obsolete. Use SerializationBinder instead.")] //public override SerializationBinder Binder //{ // get => _serializer.Binder; // set => _serializer.Binder = value; //} public override ISerializationBinder SerializationBinder { get => _serializer.SerializationBinder; set => _serializer.SerializationBinder = value; } public override StreamingContext Context { get => _serializer.Context; set => _serializer.Context = value; } public override Formatting Formatting { get => _serializer.Formatting; set => _serializer.Formatting = value; } public override DateFormatHandling DateFormatHandling { get => _serializer.DateFormatHandling; set => _serializer.DateFormatHandling = value; } public override DateTimeZoneHandling DateTimeZoneHandling { get => _serializer.DateTimeZoneHandling; set => _serializer.DateTimeZoneHandling = value; } public override DateParseHandling DateParseHandling { get => _serializer.DateParseHandling; set => _serializer.DateParseHandling = value; } public override FloatFormatHandling FloatFormatHandling { get => _serializer.FloatFormatHandling; set => _serializer.FloatFormatHandling = value; } public override FloatParseHandling FloatParseHandling { get => _serializer.FloatParseHandling; set => _serializer.FloatParseHandling = value; } public override StringEscapeHandling StringEscapeHandling { get => _serializer.StringEscapeHandling; set => _serializer.StringEscapeHandling = value; } public override string DateFormatString { get => _serializer.DateFormatString; set => _serializer.DateFormatString = value; } public override CultureInfo Culture { get => _serializer.Culture; set => _serializer.Culture = value; } public override int? MaxDepth { get => _serializer.MaxDepth; set => _serializer.MaxDepth = value; } public override bool CheckAdditionalContent { get => _serializer.CheckAdditionalContent; set => _serializer.CheckAdditionalContent = value; } internal JsonSerializerInternalBase GetInternalSerializer() { if (_serializerReader != null) { return _serializerReader; } else { return _serializerWriter; } } public JsonSerializerProxy(JsonSerializerInternalReader serializerReader) { ValidationUtils.ArgumentNotNull(serializerReader, nameof(serializerReader)); _serializerReader = serializerReader; _serializer = serializerReader.Serializer; } public JsonSerializerProxy(JsonSerializerInternalWriter serializerWriter) { ValidationUtils.ArgumentNotNull(serializerWriter, nameof(serializerWriter)); _serializerWriter = serializerWriter; _serializer = serializerWriter.Serializer; } internal override object DeserializeInternal(JsonReader reader, Type objectType) { if (_serializerReader != null) { return _serializerReader.Deserialize(reader, objectType, false); } else { return _serializer.Deserialize(reader, objectType); } } internal override void PopulateInternal(JsonReader reader, object target) { if (_serializerReader != null) { _serializerReader.Populate(reader, target); } else { _serializer.Populate(reader, target); } } internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType) { if (_serializerWriter != null) { _serializerWriter.Serialize(jsonWriter, value, rootType); } else { _serializer.Serialize(jsonWriter, value); } } } }
// <copyright file="SocketWrapper.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Runtime.Remoting.Messaging; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace OpenQA.Selenium.Safari.Internal { /// <summary> /// Provides a wrapper around a <see cref="System.Net.Sockets.Socket"/>. /// </summary> public class SocketWrapper : ISocket { private readonly Socket underlyingSocket; private bool disposed; private Stream stream; /// <summary> /// Initializes a new instance of the <see cref="SocketWrapper"/> class. /// </summary> public SocketWrapper() { this.underlyingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); if (this.underlyingSocket.Connected) { this.stream = new NetworkStream(this.underlyingSocket); } } /// <summary> /// Initializes a new instance of the <see cref="SocketWrapper"/> class. /// </summary> /// <param name="socket">The <see cref="Socket"/> to wrap.</param> public SocketWrapper(Socket socket) { if (socket == null) { throw new ArgumentNullException("socket", "Socket to wrap must not be null"); } this.underlyingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); if (this.underlyingSocket.Connected) { this.stream = new NetworkStream(this.underlyingSocket); } } /// <summary> /// Event raised when a connection is accepted by the socket. /// </summary> public event EventHandler<AcceptEventArgs> Accepted; /// <summary> /// Event raised when an error occurs accepting a connection. /// </summary> public event EventHandler<ErrorEventArgs> AcceptError; /// <summary> /// Event raised when data is sent through the socket. /// </summary> public event EventHandler Sent; /// <summary> /// Event raised when there is an error sending data. /// </summary> public event EventHandler<ErrorEventArgs> SendError; /// <summary> /// Event raised when data is received by the socket. /// </summary> public event EventHandler<ReceivedEventArgs> Received; /// <summary> /// Event raised when there is an error receiving data. /// </summary> public event EventHandler<ErrorEventArgs> ReceiveError; /// <summary> /// Event raised when authentication is completed over the socket. /// </summary> public event EventHandler Authenticated; /// <summary> /// Event raised when there is an error authenticating over the socket. /// </summary> public event EventHandler<ErrorEventArgs> AuthenticateError; /// <summary> /// Gets a value indicating whether the socket is connected. /// </summary> public bool Connected { get { return this.underlyingSocket.Connected; } } /// <summary> /// Gets the remote IP address of the socket connection. /// </summary> public string RemoteIPAddress { get { var endpoint = this.underlyingSocket.RemoteEndPoint as IPEndPoint; return endpoint != null ? endpoint.Address.ToString() : null; } } /// <summary> /// Gets a stream for reading and writing data. /// </summary> public Stream Stream { get { return this.stream; } } /// <summary> /// Accepts a connection for the socket. /// </summary> public void Accept() { this.underlyingSocket.BeginAccept(this.OnClientConnect, null); } /// <summary> /// Sends data over the socket. /// </summary> /// <param name="buffer">The data to be sent.</param> public void Send(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer", "Buffer to send must not be null"); } this.stream.BeginWrite(buffer, 0, buffer.Length, this.OnDataSend, null); } /// <summary> /// Receives data over the socket. /// </summary> /// <param name="buffer">The buffer into which the data will be read.</param> /// <param name="offset">The offset into the buffer at which the data will be read.</param> public void Receive(byte[] buffer, int offset) { if (buffer == null) { throw new ArgumentNullException("buffer", "Buffer to receive must not be null"); } this.stream.BeginRead(buffer, offset, buffer.Length, this.OnDataReceive, buffer); } /// <summary> /// Authenticates over the socket. /// </summary> /// <param name="certificate">An <see cref="X509Certificate2"/> that specifies authentication information.</param> public void Authenticate(X509Certificate2 certificate) { var ssl = new SslStream(this.stream, false); this.stream = ssl; ssl.BeginAuthenticateAsServer(certificate, false, SslProtocols.Tls, false, this.OnAuthenticate, ssl); } /// <summary> /// Closes the socket connection. /// </summary> public void Close() { if (this.stream != null) { this.stream.Close(); } if (this.underlyingSocket != null) { this.underlyingSocket.Close(); } } /// <summary> /// Binds the socket to a local end point. /// </summary> /// <param name="localEndPoint">The local end point to which to bind the socket.</param> public void Bind(EndPoint localEndPoint) { this.underlyingSocket.Bind(localEndPoint); } /// <summary> /// Starts listening to data received over the socket. /// </summary> /// <param name="backlog">The number of pending connections to process.</param> public void Listen(int backlog) { this.underlyingSocket.Listen(backlog); } /// <summary> /// Releases all resources used by the <see cref="SocketWrapper"/>. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Raises the Accepted event. /// </summary> /// <param name="e">An <see cref="AcceptEventArgs"/> that contains the event data.</param> protected void OnAccepted(AcceptEventArgs e) { if (this.Accepted != null) { this.Accepted(this, e); } } /// <summary> /// Raises the AcceptError event. /// </summary> /// <param name="e">An <see cref="ErrorEventArgs"/> that contains the event data.</param> protected void OnAcceptError(ErrorEventArgs e) { if (this.AcceptError != null) { this.AcceptError(this, e); } } /// <summary> /// Raises the Sent event. /// </summary> /// <param name="e">An <see cref="EventArgs"/> that contains the event data.</param> protected void OnSent(EventArgs e) { if (this.Sent != null) { this.Sent(this, e); } } /// <summary> /// Raises the SendError event. /// </summary> /// <param name="e">An <see cref="ErrorEventArgs"/> that contains the event data.</param> protected void OnSendError(ErrorEventArgs e) { if (this.SendError != null) { this.SendError(this, e); } } /// <summary> /// Raises the Received event. /// </summary> /// <param name="e">A <see cref="ReceivedEventArgs"/> that contains the event data.</param> protected void OnReceived(ReceivedEventArgs e) { if (this.Received != null) { this.Received(this, e); } } /// <summary> /// Raises the ReceiveError event. /// </summary> /// <param name="e">An <see cref="ErrorEventArgs"/> that contains the event data.</param> protected void OnReceiveError(ErrorEventArgs e) { if (this.ReceiveError != null) { this.ReceiveError(this, e); } } /// <summary> /// Raises the Authenticated event. /// </summary> /// <param name="e">An <see cref="EventArgs"/> that contains the event data.</param> protected void OnAuthenticated(EventArgs e) { if (this.Authenticated != null) { this.Authenticated(this, e); } } /// <summary> /// Raises the AuthenticateError event. /// </summary> /// <param name="e">An <see cref="ErrorEventArgs"/> that contains the event data.</param> protected void OnAuthenticateError(ErrorEventArgs e) { if (this.AuthenticateError != null) { this.AuthenticateError(this, e); } } /// <summary> /// Releases the unmanaged resources used by the <see cref="SocketWrapper"/> and optionally /// releases the managed resources. /// </summary> /// <param name="disposing"><see langword="true"/> to release managed and resources; /// <see langword="false"/> to only release unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing && !this.disposed) { this.disposed = true; if (this.stream != null) { this.stream.Dispose(); } if (this.underlyingSocket != null) { this.underlyingSocket.Close(); } } } private void OnAuthenticate(IAsyncResult asyncResult) { SslStream sslStream = asyncResult.AsyncState as SslStream; sslStream.EndAuthenticateAsServer(asyncResult); try { this.OnAuthenticated(new EventArgs()); } catch (Exception ex) { this.OnAuthenticateError(new ErrorEventArgs(ex)); } } private void OnDataReceive(IAsyncResult asyncResult) { try { int bytesRead = this.stream.EndRead(asyncResult); byte[] buffer = asyncResult.AsyncState as byte[]; this.OnReceived(new ReceivedEventArgs(bytesRead, buffer)); } catch (Exception ex) { this.OnReceiveError(new ErrorEventArgs(ex)); } } private void OnClientConnect(IAsyncResult asyncResult) { // This logic is mildly convoluted, and requires some explanation. // The socket can be closed (disposed) while there is still a // pending accept. This will cause an exception if we try to reference // the disposed socket. To mitigate this, we set a flag when Dispose() // is called so that we don't try to access a disposed socket. if (!this.disposed) { SocketWrapper actual = new SocketWrapper(this.underlyingSocket.EndAccept(asyncResult)); try { this.OnAccepted(new AcceptEventArgs(actual)); } catch (Exception ex) { this.OnAcceptError(new ErrorEventArgs(ex)); } } } private void OnDataSend(IAsyncResult asyncResult) { this.stream.EndWrite(asyncResult); try { this.OnSent(new EventArgs()); } catch (Exception ex) { this.OnSendError(new ErrorEventArgs(ex)); } } } }
using System; using System.Drawing; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Threading; using Microsoft.Win32; public class JobDestinationDlg : System.Windows.Forms.Form { delegate void SetStatusBarTextDelegate(string s); delegate void ResetListViewDelegate(); delegate void PopulateListViewDelegate(string[] sa); public System.Threading.Timer timer; private System.Threading.TimerCallback timerCallback; private udp udp; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; public System.Windows.Forms.ComboBox cbxHosts; private System.Windows.Forms.Label lbHost; public System.Windows.Forms.NumericUpDown nudPortnr; private System.Windows.Forms.Label lbPort; private System.Windows.Forms.CheckBox cbxAdvanced; public System.Windows.Forms.ListView lvHosts; private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.ColumnHeader Host; private System.Windows.Forms.ColumnHeader ncpu; private System.Windows.Forms.ColumnHeader avgLoad; private System.Windows.Forms.ColumnHeader Programs; object locker = new object(); public JobDestinationDlg() { Init(); PopulateCombobox(); //udp = new udp(); timerCallback = new System.Threading.TimerCallback(TimerTick); timer = new System.Threading.Timer(timerCallback, this, Timeout.Infinite, 0); } private void Init() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(JobDestinationDlg)); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.cbxHosts = new System.Windows.Forms.ComboBox(); this.lbHost = new System.Windows.Forms.Label(); this.nudPortnr = new System.Windows.Forms.NumericUpDown(); this.lbPort = new System.Windows.Forms.Label(); this.cbxAdvanced = new System.Windows.Forms.CheckBox(); this.lvHosts = new System.Windows.Forms.ListView(); this.Host = new System.Windows.Forms.ColumnHeader(); this.ncpu = new System.Windows.Forms.ColumnHeader(); this.avgLoad = new System.Windows.Forms.ColumnHeader(); this.Programs = new System.Windows.Forms.ColumnHeader(); this.statusBar1 = new System.Windows.Forms.StatusBar(); ((System.ComponentModel.ISupportInitialize)(this.nudPortnr)).BeginInit(); this.SuspendLayout(); // // btnOK // this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Location = new System.Drawing.Point(264+100, 176); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(72, 24); this.btnOK.TabIndex = 0; this.btnOK.Text = "OK"; // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(352+100, 176); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(72, 24); this.btnCancel.TabIndex = 1; this.btnCancel.Text = "Cancel"; // // cbxHosts // this.cbxHosts.Location = new System.Drawing.Point(8, 24); this.cbxHosts.Name = "cbxHosts"; this.cbxHosts.Size = new System.Drawing.Size(120, 21); this.cbxHosts.TabIndex = 3; this.cbxHosts.Click += new System.EventHandler(this.cbxHosts_Click); // // lbHost // this.lbHost.Location = new System.Drawing.Point(8, 8); this.lbHost.Name = "lbHost"; this.lbHost.Size = new System.Drawing.Size(104, 24); this.lbHost.TabIndex = 4; this.lbHost.Text = "Remote host"; // // nudPortnr // this.nudPortnr.Enabled = false; this.nudPortnr.Location = new System.Drawing.Point(8, 72); this.nudPortnr.Maximum = new System.Decimal(new int[] { 65535, 0, 0, 0}); this.nudPortnr.Minimum = new System.Decimal(new int[] { 1024, 0, 0, 0}); this.nudPortnr.Name = "nudPortnr"; this.nudPortnr.TabIndex = 5; this.nudPortnr.Value = new System.Decimal(new int[] { 7040, 0, 0, 0}); // // lbPort // this.lbPort.Enabled = false; this.lbPort.Location = new System.Drawing.Point(8, 56); this.lbPort.Name = "lbPort"; this.lbPort.Size = new System.Drawing.Size(104, 24); this.lbPort.TabIndex = 6; this.lbPort.Text = "Port number"; // // cbxAdvanced // this.cbxAdvanced.Location = new System.Drawing.Point(8, 112); this.cbxAdvanced.Name = "cbxAdvanced"; this.cbxAdvanced.TabIndex = 7; this.cbxAdvanced.Text = "Advanced"; this.cbxAdvanced.CheckedChanged += new System.EventHandler(this.cbxAdvanced_CheckedChanged); // // lvHosts // this.lvHosts.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.Host, this.ncpu, this.avgLoad, this.Programs}); this.lvHosts.FullRowSelect = true; this.lvHosts.GridLines = true; this.lvHosts.Location = new System.Drawing.Point(160, 0); this.lvHosts.MultiSelect = false; this.lvHosts.Name = "lvHosts"; this.lvHosts.Size = new System.Drawing.Size(272+100, 160); this.lvHosts.TabIndex = 8; this.lvHosts.View = System.Windows.Forms.View.Details; this.lvHosts.SelectedIndexChanged += new System.EventHandler(this.lvHosts_SelectedIndexChanged); // // Host // this.Host.Text = "Host"; this.Host.Width = 148; // // ncpu // this.ncpu.Text = "#CPU\'s"; // // avgLoad // this.avgLoad.Text = "Load"; this.Programs.Text = "Features"; Programs.Width = 200; // // statusBar1 // this.statusBar1.Location = new System.Drawing.Point(0, 210); this.statusBar1.Name = "statusBar1"; this.statusBar1.Size = new System.Drawing.Size(434, 22); this.statusBar1.SizingGrip = false; this.statusBar1.TabIndex = 9; this.statusBar1.Text = "statusBar1"; // // JobDestinationDlg // this.AcceptButton = this.btnOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(434+100, 232); this.ControlBox = false; this.Controls.Add(this.statusBar1); this.Controls.Add(this.lvHosts); this.Controls.Add(this.cbxAdvanced); this.Controls.Add(this.nudPortnr); this.Controls.Add(this.cbxHosts); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.lbHost); this.Controls.Add(this.lbPort); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "JobDestinationDlg"; this.ShowInTaskbar = false; this.Text = "Choose an SFB server"; this.Activated += new System.EventHandler(this.JobDestinationDlg_Activated); this.Deactivate += new System.EventHandler(this.JobDestinationDlg_Deactivate); ((System.ComponentModel.ISupportInitialize)(this.nudPortnr)).EndInit(); this.ResumeLayout(false); } private void cbxAdvanced_CheckedChanged(object sender, System.EventArgs e) { this.lbPort.Enabled = ((CheckBox)sender).Checked; this.nudPortnr.Enabled = ((CheckBox)sender).Checked; } private void PopulateCombobox() { RegistryKey reghouston11 = Registry.CurrentUser.OpenSubKey(Houston.regKeyString, true); if (reghouston11 == null) reghouston11 = Registry.CurrentUser.CreateSubKey(Houston.regKeyString); RegistryKey reghosts = reghouston11.OpenSubKey("Hosts", true); if (reghosts == null) reghosts = reghouston11.CreateSubKey("Hosts"); List<string> hosts = new List<string>(reghosts.GetValueNames()); hosts.Sort(); foreach (string host in hosts) { if (!cbxHosts.Items.Contains(reghosts.GetValue(host).ToString())) cbxHosts.Items.Add(reghosts.GetValue(host).ToString()); } if (cbxHosts.Items.Count > 0) cbxHosts.Text = cbxHosts.Items[0].ToString(); reghosts.Close(); reghouston11.Close(); } public void UpdateList() { int i; for (i = 0; i < cbxHosts.Items.Count; i++) { if (string.Compare(cbxHosts.Items[i].ToString(), cbxHosts.Text, true) == 0) break; } if (i == cbxHosts.Items.Count) { cbxHosts.Items.Insert(0, cbxHosts.Text); cbxHosts.SelectedIndex = 0; } } private void JobDestinationDlg_Activated(object sender, System.EventArgs e) { //timer.Change(polling ? 3000 : 0,30000); udp = new udp(); timer.Change(0, 0); // One time and only one time. Runs in a different thread. //TimerTick(this); //Console.WriteLine("poll"); //if (!polling) TimerTick(this); // One time. } private void JobDestinationDlg_Deactivate(object sender, System.EventArgs e) { lock(locker) { udp.Close(); udp=null; } } private static void TimerTick(Object obj) { JobDestinationDlg rjo = (JobDestinationDlg)obj; rjo.SetStatusBarText("Polling for sfb servers..."); if ( rjo.udp != null ) { lock(rjo.locker) { rjo.udp.SendDatagram(Environment.UserName + "@" + System.Net.Dns.GetHostName() + "\t" + "SystemLoad?"); } } else return; rjo.ResetListView(); int i = 0; rjo.SetStatusBarText(i.ToString() + " sfb server" + (i != 1 ? "s" : "") + " found."); for (; ; ) { string answ; string[] splittedansw; if ( rjo.udp != null ){ try { answ = rjo.udp.GetDatagram(); if (answ == null) break; } catch { break; } } else break; splittedansw = answ.Split(new Char[] { '\t' }); if (splittedansw.Length > 2 && splittedansw[1] == "SystemLoad") { i++; rjo.SetStatusBarText(i.ToString() + " sfb server" + (i != 1 ? "s" : "") + " found."); rjo.PopulateListView(splittedansw); } } } public void SetStatusBarText(string s) { if (!statusBar1.InvokeRequired) { statusBar1.Text = s; } else //We are on a non GUI thread. { SetStatusBarTextDelegate ssbtDel = new SetStatusBarTextDelegate(SetStatusBarText); statusBar1.Invoke(ssbtDel, new object[] { s }); } } public void ResetListView() { if (!lvHosts.InvokeRequired) { lvHosts.Items.Clear(); } else //We are on a non GUI thread. { ResetListViewDelegate rlvDel = new ResetListViewDelegate(ResetListView); lvHosts.Invoke(rlvDel); } } public void PopulateListView(string[] sa) { if (!lvHosts.InvokeRequired) { ListViewItem lvi = lvHosts.Items.Add(sa[0]); lvi.SubItems.Add(sa[2]); lvi.SubItems.Add(sa[3]); if ( sa.Length>4) lvi.SubItems.Add(sa[4]); lvHosts.Sort(); } else //We are on a non GUI thread. { PopulateListViewDelegate plvDel = new PopulateListViewDelegate(PopulateListView); lvHosts.Invoke(plvDel, new object[] { sa }); } } private void cbxHosts_Click(object sender, System.EventArgs e) { if (this.lvHosts.SelectedItems.Count > 0) { this.lvHosts.SelectedItems[0].Selected = false; } } private void lvHosts_SelectedIndexChanged(object sender, System.EventArgs e) { if (lvHosts.SelectedItems.Count == 1) cbxHosts.Text = lvHosts.SelectedItems[0].Text; } protected override void OnFormClosed(FormClosedEventArgs e) { //udp.Close(); base.OnFormClosed(e); } }
using System; using System.Diagnostics; using System.Reflection; using System.Threading.Tasks; namespace Orleans.Serialization.Invocation { public abstract class Request : IInvokable { public abstract int ArgumentCount { get; } [DebuggerHidden] public ValueTask<Response> Invoke() { try { var resultTask = InvokeInner(); if (resultTask.IsCompleted) { resultTask.GetAwaiter().GetResult(); return new ValueTask<Response>(Response.FromResult<object>(null)); } return CompleteInvokeAsync(resultTask); } catch (Exception exception) { return new ValueTask<Response>(Response.FromException(exception)); } } [DebuggerHidden] private static async ValueTask<Response> CompleteInvokeAsync(ValueTask resultTask) { try { await resultTask; return Response.FromResult<object>(null); } catch (Exception exception) { return Response.FromException(exception); } } // Generated [DebuggerHidden] protected abstract ValueTask InvokeInner(); public abstract TTarget GetTarget<TTarget>(); public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder; public abstract TArgument GetArgument<TArgument>(int index); public abstract void SetArgument<TArgument>(int index, in TArgument value); public abstract void Dispose(); public abstract string MethodName { get; } public abstract Type[] MethodTypeArguments { get; } public abstract string InterfaceName { get; } public abstract Type InterfaceType { get; } public abstract Type[] InterfaceTypeArguments { get; } public abstract Type[] ParameterTypes { get; } public abstract MethodInfo Method { get; } } public abstract class Request<TResult> : IInvokable { public abstract int ArgumentCount { get; } [DebuggerHidden] public ValueTask<Response> Invoke() { try { var resultTask = InvokeInner(); if (resultTask.IsCompleted) { return new ValueTask<Response>(Response.FromResult(resultTask.Result)); } return CompleteInvokeAsync(resultTask); } catch (Exception exception) { return new ValueTask<Response>(Response.FromException(exception)); } } [DebuggerHidden] private static async ValueTask<Response> CompleteInvokeAsync(ValueTask<TResult> resultTask) { try { var result = await resultTask; return Response.FromResult(result); } catch (Exception exception) { return Response.FromException(exception); } } // Generated [DebuggerHidden] protected abstract ValueTask<TResult> InvokeInner(); public abstract TTarget GetTarget<TTarget>(); public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder; public abstract TArgument GetArgument<TArgument>(int index); public abstract void SetArgument<TArgument>(int index, in TArgument value); public abstract void Dispose(); public abstract string MethodName { get; } public abstract Type[] MethodTypeArguments { get; } public abstract string InterfaceName { get; } public abstract Type InterfaceType { get; } public abstract Type[] InterfaceTypeArguments { get; } public abstract Type[] ParameterTypes { get; } public abstract MethodInfo Method { get; } } public abstract class TaskRequest<TResult> : IInvokable { public abstract int ArgumentCount { get; } [DebuggerHidden] public ValueTask<Response> Invoke() { try { var resultTask = InvokeInner(); var status = resultTask.Status; if (resultTask.IsCompleted) { return new ValueTask<Response>(Response.FromResult(resultTask.GetAwaiter().GetResult())); } return CompleteInvokeAsync(resultTask); } catch (Exception exception) { return new ValueTask<Response>(Response.FromException(exception)); } } [DebuggerHidden] private static async ValueTask<Response> CompleteInvokeAsync(Task<TResult> resultTask) { try { var result = await resultTask; return Response.FromResult(result); } catch (Exception exception) { return Response.FromException(exception); } } // Generated [DebuggerHidden] protected abstract Task<TResult> InvokeInner(); public abstract TTarget GetTarget<TTarget>(); public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder; public abstract TArgument GetArgument<TArgument>(int index); public abstract void SetArgument<TArgument>(int index, in TArgument value); public abstract void Dispose(); public abstract string MethodName { get; } public abstract Type[] MethodTypeArguments { get; } public abstract string InterfaceName { get; } public abstract Type InterfaceType { get; } public abstract Type[] InterfaceTypeArguments { get; } public abstract Type[] ParameterTypes { get; } public abstract MethodInfo Method { get; } } public abstract class TaskRequest : IInvokable { public abstract int ArgumentCount { get; } [DebuggerHidden] public ValueTask<Response> Invoke() { try { var resultTask = InvokeInner(); var status = resultTask.Status; if (resultTask.IsCompleted) { resultTask.GetAwaiter().GetResult(); return new ValueTask<Response>(Response.FromResult<object>(null)); } return CompleteInvokeAsync(resultTask); } catch (Exception exception) { return new ValueTask<Response>(Response.FromException(exception)); } } [DebuggerHidden] private static async ValueTask<Response> CompleteInvokeAsync(Task resultTask) { try { await resultTask; return Response.FromResult<object>(null); } catch (Exception exception) { return Response.FromException(exception); } } // Generated [DebuggerHidden] protected abstract Task InvokeInner(); public abstract TTarget GetTarget<TTarget>(); public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder; public abstract TArgument GetArgument<TArgument>(int index); public abstract void SetArgument<TArgument>(int index, in TArgument value); public abstract void Dispose(); public abstract string MethodName { get; } public abstract Type[] MethodTypeArguments { get; } public abstract string InterfaceName { get; } public abstract Type InterfaceType { get; } public abstract Type[] InterfaceTypeArguments { get; } public abstract Type[] ParameterTypes { get; } public abstract MethodInfo Method { get; } } public abstract class VoidRequest : IInvokable { public abstract int ArgumentCount { get; } [DebuggerHidden] public ValueTask<Response> Invoke() { try { InvokeInner(); return new ValueTask<Response>(Response.FromResult<object>(null)); } catch (Exception exception) { return new ValueTask<Response>(Response.FromException(exception)); } } // Generated [DebuggerHidden] protected abstract void InvokeInner(); public abstract TTarget GetTarget<TTarget>(); public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder; public abstract TArgument GetArgument<TArgument>(int index); public abstract void SetArgument<TArgument>(int index, in TArgument value); public abstract void Dispose(); public abstract string MethodName { get; } public abstract Type[] MethodTypeArguments { get; } public abstract string InterfaceName { get; } public abstract Type InterfaceType { get; } public abstract Type[] InterfaceTypeArguments { get; } public abstract Type[] ParameterTypes { get; } public abstract MethodInfo Method { get; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Array operations. /// </summary> public partial class Array : IServiceOperations<AutoRestComplexTestService>, IArray { /// <summary> /// Initializes a new instance of the Array class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public Array(AutoRestComplexTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex types with array property /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<ArrayWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<ArrayWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types with array property /// </summary> /// <param name='array'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(IList<string> array = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { ArrayWrapper complexBody = null; if (array != null) { complexBody = new ArrayWrapper(); complexBody.Array = array; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with array property which is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<ArrayWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<ArrayWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types with array property which is empty /// </summary> /// <param name='array'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(IList<string> array = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { ArrayWrapper complexBody = null; if (array != null) { complexBody = new ArrayWrapper(); complexBody.Array = array; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with array property while server doesn't provide a /// response payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<ArrayWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/notprovided").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<ArrayWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System.Runtime.Serialization.Formatters.Binary; using System; using System.IO; using System.Collections.Generic; using UnityEngine; using libmapgen; [RequireComponent (typeof (MeshFilter))] [RequireComponent (typeof (MeshRenderer))] public class MapGenerator : MonoBehaviour, ISerializationCallbackReceiver { public GameObject mapHandler = null; public bool createMesh = true; public bool generateMapInRuntime = true; MapContext context = new MapContext(); BinaryFormatter serializer = new BinaryFormatter(); // our own serializer for the ruleset! // ruleset values - serialized [HideInInspector] [UnityEngine.SerializeField] string generator_serialized; [HideInInspector] [UnityEngine.SerializeField] List<string> passes_serialized; [HideInInspector] [UnityEngine.SerializeField] // need this to make mapArea not reset when starting the scene MapArea mapArea; Ruleset ruleset; [HideInInspector] [UnityEngine.SerializeField] List<string> pass_names; [HideInInspector] [UnityEngine.SerializeField] int width = 8; [HideInInspector] [UnityEngine.SerializeField] int height = 12; [HideInInspector] [UnityEngine.SerializeField] float min_h = 0.0f; [HideInInspector] [UnityEngine.SerializeField] float max_h = 2.0f; void Start () { InitRuleset(); if (generateMapInRuntime == true) { RegenerateMap(); } } IInitialMapGenerator DefaultGenerator() { return new RandomHeightmap(width, height, min_h, max_h); } // make sure the ruleset is never null public void InitRuleset() { if (ruleset != null) { return; } ResetRuleset(); } public void ResetRuleset() { ruleset = new Ruleset(DefaultGenerator()); pass_names = new List<string>(); } public void SetGenerator(IInitialMapGenerator g) { ruleset.generator = g; } public int GetPassCount() { return ruleset.passes.Count; } public string GetPassName(int i) { return pass_names[i]; } public IMapPassEditor GetPass(int i) { return (IMapPassEditor)ruleset.passes[i]; } public void AddPass(IMapPassEditor p, string name) { ruleset.passes.Add(p); pass_names.Add(name); } public void RemovePass(int i) { ruleset.passes.RemoveAt(i); pass_names.RemoveAt(i); } public void MovePass(int from, int to) { IMapPassEditor pass = (IMapPassEditor)ruleset.passes[from]; string name = pass_names[from]; ruleset.passes.RemoveAt(from); pass_names.RemoveAt(from); ruleset.passes.Insert(to, pass); pass_names.Insert(to, name); } public MapContext GetMapContext() { context.width = width; context.height = height; context.min_h = min_h; context.max_h = max_h; return context; } public int GetWidth() { return width; } public int GetHeight() { return height; } public void SetSize(int x, int y) { if (x == width && y == height) { return; } width = x; height = y; ruleset.generator.width = x; ruleset.generator.height = y; } public void RegenerateMap() { mapArea = ruleset.generate(); if (mapHandler != null) { IMapHandler handler = mapHandler.GetComponent<IMapHandler>(); if (handler != null) { handler.OnMapFinish(mapArea); } else { Debug.LogWarning("map handler lacks IMapHandler script"); } } // TODO: remove new mesh when creating new map without createMesh if (createMesh) { GetComponent<MeshFilter>().mesh = CreateMesh(width, height); } } public Mesh DeleteMap() { if (mapHandler != null) { IMapHandler handler = mapHandler.GetComponent<IMapHandler>(); if (handler != null) { handler.OnMapDelete(mapArea); } else { Debug.LogWarning("map handler lacks IMapHandler script"); } } mapArea = null; MeshFilter filter = GetComponent<MeshFilter>(); Mesh mesh = filter.sharedMesh; filter.mesh = null; return mesh; } // TODO: factor creating a mesh into its own class Mesh CreateMesh(int width, int height) { if (width == 0 || height == 0) { return new Mesh(); // nothing to generate! } // we're making a vertex grid like this // // (map size 2x1) // // vertices: // // 2-------3-------4 // | | | // | 0 | 1 | // | | | // 5-------6-------7 // // here, cvertex = 2 // // triangle0 = 0, 3, 2 // triangle1 = 0, 6, 3 // triangle2 = 0, 5, 6 // triangle3 = 0, 5, 2 // etc. // int vertices_num = width * height + (width+1) * (height+1); // for every tile: 4 triangles, each has 3 points int triangles_num = 3 * 4 * width * height; Vector3[] vertices = new Vector3[vertices_num]; // add central vertices for (int y=0; y<height; y++) { for (int x=0; x<width; x++) { vertices[y*width + x] = new Vector3((float)x + 0.5f, mapArea.getHeightAt(x, y), (float)y + 0.5f); } } int cvertex = height * width; // corner vertices start at this index // add corner vertices. These have a grid of (width+1, height+1) for (int y=0; y < height + 1; y++) { for (int x=0; x < width + 1; x++) { float z = CalculateCornerHeight(x, y, vertices, width, height); vertices[cvertex + y*(width+1) + x] = new Vector3((float)x, z, (float)y); } } Vector2[] uv = new Vector2[vertices_num]; // don't care about uv right now for (int i=0; i<vertices_num; i++) { uv[i] = new Vector2(0.0f, 0.0f); } int[] triangles = new int[triangles_num]; // adding triangles for (int y=0; y<height; y++) { for (int x=0; x<width; x++) { int tile_i = y*width + x; // index of the tile we're at int tri_i = tile_i * 4 * 3; // index in the triangle array int upperleft_vertex = cvertex + x + y*(width+1); int upperright_vertex = upperleft_vertex + 1; int lowerleft_vertex = upperleft_vertex + width+1; int lowerright_vertex = upperleft_vertex + 1 + width+1; // triangle 1 triangles[tri_i] = tile_i; // central vertex triangles[tri_i+1] = upperright_vertex; triangles[tri_i+2] = upperleft_vertex; // triangle 2 tri_i += 3; triangles[tri_i] = tile_i; // + width means one row below, aka the lower vertexes of the tile triangles[tri_i+1] = lowerright_vertex; triangles[tri_i+2] = upperright_vertex; // triangle 3 tri_i += 3; triangles[tri_i] = tile_i; triangles[tri_i+1] = lowerleft_vertex; triangles[tri_i+2] = lowerright_vertex; // triangle 4 tri_i += 3; triangles[tri_i] = tile_i; triangles[tri_i+1] = upperleft_vertex; triangles[tri_i+2] = lowerleft_vertex; } } Mesh mesh = new Mesh(); mesh.vertices = vertices; mesh.uv = uv; mesh.triangles = triangles; return mesh; } float CalculateCornerHeight (int x, int y, Vector3[] vertices, int width, int height) { float?[] tiles = new float?[] {null, null, null, null}; // get values of tiles around corner if (x - 1 >= 0 && y - 1 >= 0) { tiles[0] = vertices[x-1 + (y-1)*width].y; } if (x < width && y - 1 >= 0) { tiles[1] = vertices[x + (y-1)*width].y; } if (x - 1 >= 0 && y < height) { tiles[2] = vertices[x-1 + y*width].y; } if (x < width && y < height) { tiles[3] = vertices[x + y*width].y; } // get average value float sum = 0; float div = 0; foreach (var v in tiles) { if (v.HasValue) { sum += v.Value; div += 1; } } // if outside of grid, default to 0.0f if (div != 0) { return sum / div; } else { return 0.0f; } } // Update is called once per frame void Update () { if (Input.GetKeyUp(KeyCode.Space)) { RegenerateMap(); } } //TODO: reuse MemoryStream? Don't need to convert bytes to base64string? public void OnBeforeSerialize() { using (var stream = new MemoryStream()) { serializer.Serialize(stream, ruleset.generator); stream.Flush(); generator_serialized = Convert.ToBase64String(stream.ToArray()); } passes_serialized.Clear(); foreach (var pass in ruleset.passes) { using (var stream = new MemoryStream()) { serializer.Serialize(stream, pass); stream.Flush(); passes_serialized.Add(Convert.ToBase64String(stream.ToArray())); } } } public void OnAfterDeserialize() { ruleset = new Ruleset(); byte[] bytes = Convert.FromBase64String(generator_serialized); using (var stream = new MemoryStream(bytes)) { ruleset.generator = (IInitialMapGenerator)serializer.Deserialize(stream); } ruleset.passes.Capacity = passes_serialized.Count; foreach(var pass_serialized in passes_serialized) { bytes = Convert.FromBase64String(pass_serialized); using (var stream = new MemoryStream(bytes)) { ruleset.passes.Add((IMapPassEditor)serializer.Deserialize(stream)); } } } }
namespace BefunGen.AST.CodeGen { public enum NumberRep { StringmodeChar, // CANT REPRESENT EVERYTHING !! Base9, Factorization, Stringify, // CANT REPRESENT EVERYTHING !! Digit, // CANT REPRESENT EVERYTHING !! Boolean, // CANT REPRESENT EVERYTHING !! Best } public class CodeGenOptions { // Defines how Number Literals get represented public NumberRep NumberLiteralRepresentation; // Removes 2x Stringmodetoogle after each other from Expression (eg "" ) public bool StripDoubleStringmodeToogle; // Every NOP-Command is displayed as an Exit-Command public bool SetNOPCellsToCustom; public char CustomNOPSymbol; // When combining two CodePieces try to combine the two connecting columns/rows to a single one public bool CompressHorizontalCombining; public bool CompressVerticalCombining; // The aimed width of variable declarations - this is only estimated, long arrays can extend the width public int DefaultVarDeclarationWidth; // The Value of reserved for variable fields before initialization public char DefaultVarDeclarationSymbol; // The Value of reserved for temp_field before initialization public char DefaultTempSymbol; // The Value of reserved for temp_field_returnval before initialization public char DefaultResultTempSymbol; // When hard casting to bool force the value to be '0' or '1' public bool ExtendedBooleanCast; // Default Values for Init operations public byte DefaultNumeralValue; public char DefaultCharacterValue; public bool DefaultBooleanValue; // Values for the Display public char DefaultDisplayValue; public char DisplayBorder; public int DisplayBorderThickness; // If set to true you can't Out-Of-Bounce the Display - Set&Get is put into a modulo Width before public bool DisplayModuloAccess; // Calculate/Optimize Expressions at CompileTime public bool CompileTimeEvaluateExpressions; /* EvaluateExpression - Optimizations: * * RAND[0] --> 0 * 1 * EXPR --> EXPR * 0 * EXPR --> 0 * 0 [+,-] EXPR --> EXPR * LITERAL [+,*,-,/] LITERAL --> LITERAL * LITERAL [==,!=,>,<,>=,<=] LITERAL --> BOOL */ public bool RemUnreferencedMethods; public static CodeGenOptions getCGO_Debug() { CodeGenOptions c = new CodeGenOptions(); c.NumberLiteralRepresentation = NumberRep.Base9; c.StripDoubleStringmodeToogle = true; c.SetNOPCellsToCustom = true; c.CustomNOPSymbol = (char)164; c.CompressHorizontalCombining = true; c.CompressVerticalCombining = true; c.DefaultVarDeclarationWidth = 48; c.DefaultVarDeclarationSymbol = 'V'; c.DefaultTempSymbol = 'R'; c.DefaultResultTempSymbol = 'T'; c.ExtendedBooleanCast = false; c.DefaultNumeralValue = 0; c.DefaultCharacterValue = ' '; c.DefaultBooleanValue = false; c.DefaultDisplayValue = ' '; c.DisplayBorder = '#'; c.DisplayBorderThickness = 1; c.DisplayModuloAccess = false; c.CompileTimeEvaluateExpressions = true; c.RemUnreferencedMethods = false; return c; } public static CodeGenOptions getCGO_Release() { CodeGenOptions c = new CodeGenOptions(); c.NumberLiteralRepresentation = NumberRep.Best; c.StripDoubleStringmodeToogle = true; c.SetNOPCellsToCustom = false; c.CustomNOPSymbol = '@'; c.CompressHorizontalCombining = true; c.CompressVerticalCombining = true; c.DefaultVarDeclarationWidth = 48; c.DefaultVarDeclarationSymbol = ' '; c.DefaultTempSymbol = ' '; c.DefaultResultTempSymbol = ' '; c.ExtendedBooleanCast = false; c.DefaultNumeralValue = 0; c.DefaultCharacterValue = ' '; c.DefaultBooleanValue = false; c.DefaultDisplayValue = ' '; c.DisplayBorder = '#'; c.DisplayBorderThickness = 1; c.DisplayModuloAccess = false; c.CompileTimeEvaluateExpressions = true; c.RemUnreferencedMethods = true; return c; } public static int NumberRepToUINumber(NumberRep r) { switch (r) { case NumberRep.StringmodeChar: return -4; case NumberRep.Stringify: return -3; case NumberRep.Digit: return -2; case NumberRep.Boolean: return -1; case NumberRep.Base9: return 0; case NumberRep.Factorization: return 1; case NumberRep.Best: return 2; default: return int.MinValue; } } public static NumberRep UINumberToNumberRep(int r, NumberRep def) { switch (r) { case 0: return NumberRep.Base9; case 1: return NumberRep.Factorization; case 2: return NumberRep.Best; default: return def; } } } //Expressions are Left,0 in ... Right,0 out //Statements are Left,0 in ... Right,0 out //StatementLists order statements under each other (Y-0-Axis nearly top) //Methods enter at Left,0 in ... They can exit at multiple places } /* ::Jumping and the stack:: ############################# RIGHT LANE :> Jump to Codepoint - jump back - Stack flooded LEFT LANE :> Jump to Methodaddr - jump in - Stack unflooded EXIT::JUMP_IN ( doMethod(a, b) ) ######## [STACK] OWN_VARIABLES [STACK] OWN_CODEPOINTADDR [STACK] TARGET_PARAMETER [STACK] TARGET_ADRESS ("Left Lane Adress" -> MethodAdress) [STACK] 1 (FOR JUMP_IN -> "Left Lane") EXIT::JUMP_BACK ( Return x ) ######### IF (RETURN VALUE) [STACK] CALC RETURN VALUE TO STACK (ALWAYS -> VOID is also value (0) ); [STACK] Stack_Swap (Switch BackJumpAddr and ReturnVal) [STACK] 0 (FOR JUMP_BACK -> "Right Lane") IF (RETURN ARRAY) [STACK] CALC RETURN VALUE TO STACK (ALWAYS -> VOID is also value (0) ); PUT RETURNVAL to TMP_RETURN_FIELD PUT BACKJUMPADDR TO TMP_JMP_ADDR READ RETURNVAL BACK AGAIN READ BACKJUMPADDR BACK AGAIN [STACK] 0 (FOR JUMP_BACK -> "Right Lane") EXIT::JUMP_LABEL ( GOTO lbl1 ) ########## [STACK] TARGET_ADRESS ("Right Lane Adress" -> CodePointAdress) [STACK] 0 (FOR JUMP_BACK -> "Right Lane") (little "hacky") ROUNDABOUT_PATH ############### SWITCH BETWEEN LEFT/RIGHT LANE /-- RIGHT LANE: FLOOD STACK BINARY FROM TARGETADRESS -| \-- LEFT LANE: Do Nothing GO THROUGH LANES (Right: Flooded, Left: sub..sub..sub) ENTRY::JUMP_IN (From a jump in -> Left Lane) ########## INIT VARS (STANDARD VALUES) INIT PARAMS [FROM STACK] {DO METHOD} ENTRY::JUMP_BACK (From a jump back -> Right Lane) ########## SAVE RETURN VALUE FROM STACK SOMEWHERE ELSE (perhaps calculate max array size -> reserve global return value tmp space) RE-GET VARS FROM STACK PUT RETURN VALUE BACK TO STACK (If Statement_Call pop return value) ENTRY::JUMP_LABEL ( lbl1: ) ################# Do Nothing ... just go on ... stack is fine */ /* ########### RPOGRAM IDEAS ####### [X] Find way through Labyrinth thats written on display (recursive / Bruteforce) [X] Maze Generation [O] Solve Sudoku Thats inputted on Display (recursive Bruteforce) [X] Generate Sudoku on Display [O] Quicksort input [X] Befunge Interpreter [O] Generate Math Question and check answers [X] PrimzahlCalcer [X] GOL Klon [X] Square-It (+ KI) */
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.IO; using System.Threading; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; using Ionic.Zip; using WebsitePanel.Installer.Common; using System.Net; using System.Text.RegularExpressions; using System.Collections; using System.Threading.Tasks; using System.Reflection; using System.Diagnostics; namespace WebsitePanel.Installer.Core { public class LoaderEventArgs<T> : EventArgs { public string StatusMessage { get; set; } public T EventData { get; set; } public bool Cancellable { get; set; } } public static class LoaderFactory { /// <summary> /// Instantiates either CodeplexLoader or InstallerServiceLoader based on remote file format. /// </summary> /// <param name="remoteFile"></param> /// <returns></returns> public static Loader CreateFileLoader(string remoteFile) { Debug.Assert(!String.IsNullOrEmpty(remoteFile), "Remote file is empty"); if (remoteFile.StartsWith("http://websitepanel.codeplex.com/")) { return new CodeplexLoader(remoteFile); } else { return new Loader(remoteFile); } } } public class CodeplexLoader : Loader { public const string WEB_PI_USER_AGENT_HEADER = "PI-Integrator/3.0.0.0({0})"; private WebClient fileLoader; internal CodeplexLoader(string remoteFile) : base(remoteFile) { InitFileLoader(); } private void InitFileLoader() { fileLoader = new WebClient(); // Set HTTP header for Codeplex to allow direct downloads fileLoader.Headers.Add("User-Agent", String.Format(WEB_PI_USER_AGENT_HEADER, Assembly.GetExecutingAssembly().FullName)); } protected override Task GetDownloadFileTask(string remoteFile, string tmpFile, CancellationToken ct) { var downloadFileTask = new Task(() => { if (!File.Exists(tmpFile)) { // Mimic synchronous file download operation because we need to track the download progress // and be able to cancel the operation in progress AutoResetEvent autoEvent = new AutoResetEvent(false); if (fileLoader.IsBusy.Equals(true)) { return; } ct.Register(() => { fileLoader.CancelAsync(); }); Log.WriteStart("Downloading file"); Log.WriteInfo("Downloading file \"{0}\" to \"{1}\"", remoteFile, tmpFile); // Attach event handlers to track status of the download process fileLoader.DownloadProgressChanged += (obj, e) => { if (ct.IsCancellationRequested) return; RaiseOnProgressChangedEvent(e.ProgressPercentage); RaiseOnStatusChangedEvent(DownloadingSetupFilesMessage, String.Format(DownloadProgressMessage, e.BytesReceived / 1024, e.TotalBytesToReceive / 1024)); }; fileLoader.DownloadFileCompleted += (obj, e) => { if (ct.IsCancellationRequested == false) { RaiseOnProgressChangedEvent(100); RaiseOnStatusChangedEvent(DownloadingSetupFilesMessage, "100%"); } if (e.Cancelled) { CancelDownload(tmpFile); } autoEvent.Set(); }; fileLoader.DownloadFileAsync(new Uri(remoteFile), tmpFile); RaiseOnStatusChangedEvent(DownloadingSetupFilesMessage); autoEvent.WaitOne(); } }, ct); return downloadFileTask; } } /// <summary> /// Loader form. /// </summary> public class Loader { public const string ConnectingRemotServiceMessage = "Connecting..."; public const string DownloadingSetupFilesMessage = "Downloading setup files..."; public const string CopyingSetupFilesMessage = "Copying setup files..."; public const string PreparingSetupFilesMessage = "Please wait while Setup prepares the necessary files..."; public const string DownloadProgressMessage = "{0} KB of {1} KB"; public const string PrepareSetupProgressMessage = "{0}%"; private const int ChunkSize = 262144; private string remoteFile; private CancellationTokenSource cts; public event EventHandler<LoaderEventArgs<String>> StatusChanged; public event EventHandler<LoaderEventArgs<Exception>> OperationFailed; public event EventHandler<LoaderEventArgs<Int32>> ProgressChanged; public event EventHandler<EventArgs> OperationCompleted; internal Loader(string remoteFile) { this.remoteFile = remoteFile; } public void LoadAppDistributive() { ThreadPool.QueueUserWorkItem(q => LoadAppDistributiveInternal()); } protected void RaiseOnStatusChangedEvent(string statusMessage) { RaiseOnStatusChangedEvent(statusMessage, String.Empty); } protected void RaiseOnStatusChangedEvent(string statusMessage, string eventData) { RaiseOnStatusChangedEvent(statusMessage, eventData, true); } protected void RaiseOnStatusChangedEvent(string statusMessage, string eventData, bool cancellable) { if (StatusChanged == null) { return; } // No event data for status updates StatusChanged(this, new LoaderEventArgs<String> { StatusMessage = statusMessage, EventData = eventData, Cancellable = cancellable }); } protected void RaiseOnProgressChangedEvent(int eventData) { RaiseOnProgressChangedEvent(eventData, true); } protected void RaiseOnProgressChangedEvent(int eventData, bool cancellable) { if (ProgressChanged == null) { return; } // ProgressChanged(this, new LoaderEventArgs<int> { EventData = eventData, Cancellable = cancellable }); } protected void RaiseOnOperationFailedEvent(Exception ex) { if (OperationFailed == null) { return; } // OperationFailed(this, new LoaderEventArgs<Exception> { EventData = ex }); } protected void RaiseOnOperationCompletedEvent() { if (OperationCompleted == null) { return; } // OperationCompleted(this, EventArgs.Empty); } /// <summary> /// Executes a file download request asynchronously /// </summary> private void LoadAppDistributiveInternal() { try { string dataFolder; string tmpFolder; // Retrieve local storage configuration GetLocalStorageInfo(out dataFolder, out tmpFolder); // Initialize storage InitializeLocalStorage(dataFolder, tmpFolder); string fileToDownload = Path.GetFileName(remoteFile); string destinationFile = Path.Combine(dataFolder, fileToDownload); string tmpFile = Path.Combine(tmpFolder, fileToDownload); cts = new CancellationTokenSource(); CancellationToken token = cts.Token; try { // Download the file requested Task downloadFileTask = GetDownloadFileTask(remoteFile, tmpFile, token); // Move the file downloaded from temporary location to Data folder var moveFileTask = downloadFileTask.ContinueWith((t) => { if (File.Exists(tmpFile)) { // copy downloaded file to data folder RaiseOnStatusChangedEvent(CopyingSetupFilesMessage); // RaiseOnProgressChangedEvent(0); // Ensure that the target does not exist. if (File.Exists(destinationFile)) FileUtils.DeleteFile(destinationFile); File.Move(tmpFile, destinationFile); // RaiseOnProgressChangedEvent(100); } }, TaskContinuationOptions.NotOnCanceled); // Unzip file downloaded var unzipFileTask = moveFileTask.ContinueWith((t) => { if (File.Exists(destinationFile)) { RaiseOnStatusChangedEvent(PreparingSetupFilesMessage); // RaiseOnProgressChangedEvent(0); // UnzipFile(destinationFile, tmpFolder); // RaiseOnProgressChangedEvent(100); } }, token); // var notifyCompletionTask = unzipFileTask.ContinueWith((t) => { RaiseOnOperationCompletedEvent(); }, token); downloadFileTask.Start(); downloadFileTask.Wait(); } catch (AggregateException ae) { ae.Handle((e) => { // We handle cancellation requests if (e is OperationCanceledException) { CancelDownload(tmpFile); Log.WriteInfo("Download has been cancelled by the user"); return true; } // But other issues just being logged Log.WriteError("Could not download the file", e); return false; }); } } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Loader module error", ex); // RaiseOnOperationFailedEvent(ex); } } protected virtual Task GetDownloadFileTask(string sourceFile, string tmpFile, CancellationToken ct) { var downloadFileTask = new Task(() => { if (!File.Exists(tmpFile)) { var service = ServiceProviderProxy.GetInstallerWebService(); RaiseOnProgressChangedEvent(0); RaiseOnStatusChangedEvent(DownloadingSetupFilesMessage); Log.WriteStart("Downloading file"); Log.WriteInfo(string.Format("Downloading file \"{0}\" to \"{1}\"", sourceFile, tmpFile)); long downloaded = 0; long fileSize = service.GetFileSize(sourceFile); if (fileSize == 0) { throw new FileNotFoundException("Service returned empty file.", sourceFile); } byte[] content; while (downloaded < fileSize) { // Throw OperationCancelledException if there is an incoming cancel request ct.ThrowIfCancellationRequested(); content = service.GetFileChunk(sourceFile, (int)downloaded, ChunkSize); if (content == null) { throw new FileNotFoundException("Service returned NULL file content.", sourceFile); } FileUtils.AppendFileContent(tmpFile, content); downloaded += content.Length; // Update download progress RaiseOnStatusChangedEvent(DownloadingSetupFilesMessage, string.Format(DownloadProgressMessage, downloaded / 1024, fileSize / 1024)); RaiseOnProgressChangedEvent(Convert.ToInt32((downloaded * 100) / fileSize)); if (content.Length < ChunkSize) break; } RaiseOnStatusChangedEvent(DownloadingSetupFilesMessage, "100%"); Log.WriteEnd(string.Format("Downloaded {0} bytes", downloaded)); } }, ct); return downloadFileTask; } private static void InitializeLocalStorage(string dataFolder, string tmpFolder) { if (!Directory.Exists(dataFolder)) { Directory.CreateDirectory(dataFolder); Log.WriteInfo("Data directory created"); } if (Directory.Exists(tmpFolder)) { Directory.Delete(tmpFolder, true); } if (!Directory.Exists(tmpFolder)) { Directory.CreateDirectory(tmpFolder); Log.WriteInfo("Tmp directory created"); } } private static void GetLocalStorageInfo(out string dataFolder, out string tmpFolder) { dataFolder = FileUtils.GetDataDirectory(); tmpFolder = FileUtils.GetTempDirectory(); } private void UnzipFile(string zipFile, string destFolder) { try { int val = 0; // Negative value means no progress made yet int progress = -1; // Log.WriteStart("Unzipping file"); Log.WriteInfo(string.Format("Unzipping file \"{0}\" to the folder \"{1}\"", zipFile, destFolder)); long zipSize = 0; var zipInfo = ZipFile.Read(zipFile); try { foreach (ZipEntry entry in zipInfo) { if (!entry.IsDirectory) zipSize += entry.UncompressedSize; } } finally { if (zipInfo != null) { zipInfo.Dispose(); } } long unzipped = 0; // var zip = ZipFile.Read(zipFile); // try { foreach (ZipEntry entry in zip) { // entry.Extract(destFolder, ExtractExistingFileAction.OverwriteSilently); // if (!entry.IsDirectory) unzipped += entry.UncompressedSize; if (zipSize != 0) { val = Convert.ToInt32(unzipped * 100 / zipSize); // Skip to raise the progress event change when calculated progress // and the current progress value are even if (val == progress) { continue; } // RaiseOnStatusChangedEvent( PreparingSetupFilesMessage, String.Format(PrepareSetupProgressMessage, val), false); // RaiseOnProgressChangedEvent(val, false); } } // Notify client the operation can be cancelled at this time RaiseOnProgressChangedEvent(100); // Log.WriteEnd("Unzipped file"); } finally { if (zip != null) { zip.Dispose(); } } } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; // RaiseOnOperationFailedEvent(ex); } } /// <summary> /// Cleans up temporary file if the download process has been cancelled. /// </summary> /// <param name="tmpFile">Path to the temporary file to cleanup</param> protected virtual void CancelDownload(string tmpFile) { if (File.Exists(tmpFile)) { File.Delete(tmpFile); } } public void AbortOperation() { // Make sure we are in business if (cts != null) { cts.Cancel(); } } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using NUnit.Framework.Constraints; namespace OpenQA.Selenium { [TestFixture] public class TypingTest : DriverTestFixture { [Test] [Category("Javascript")] public void ShouldFireKeyPressEvents() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("a"); IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsTrue(text.Contains("press:"), "Text should contain 'press:'. Actual text: {0}", text); } [Test] [Category("Javascript")] public void ShouldFireKeyDownEvents() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("I"); IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsTrue(text.Contains("down:"), "Text should contain 'down:'. Actual text: {0}", text); } [Test] [Category("Javascript")] public void ShouldFireKeyUpEvents() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("a"); IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsTrue(text.Contains("up:"), "Text should contain 'up:'. Actual text: {0}", text); } [Test] public void ShouldTypeLowerCaseLetters() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("abc def"); Assert.AreEqual("abc def", keyReporter.GetAttribute("value")); } [Test] public void ShouldBeAbleToTypeCapitalLetters() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("ABC DEF"); Assert.AreEqual("ABC DEF", keyReporter.GetAttribute("value")); } [Test] public void ShouldBeAbleToTypeQuoteMarks() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("\""); Assert.AreEqual("\"", keyReporter.GetAttribute("value")); } [Test] public void ShouldBeAbleToTypeTheAtCharacter() { // simon: I tend to use a US/UK or AUS keyboard layout with English // as my primary language. There are consistent reports that we're // not handling i18nised keyboards properly. This test exposes this // in a lightweight manner when my keyboard is set to the DE mapping // and we're using IE. driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("@"); Assert.AreEqual("@", keyReporter.GetAttribute("value")); } [Test] public void ShouldBeAbleToMixUpperAndLowerCaseLetters() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("me@eXample.com"); Assert.AreEqual("me@eXample.com", keyReporter.GetAttribute("value")); } [Test] [Category("Javascript")] public void ArrowKeysShouldNotBePrintable() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys(Keys.ArrowLeft); Assert.AreEqual(string.Empty, keyReporter.GetAttribute("value")); } [Test] [IgnoreBrowser(Browser.HtmlUnit)] public void ShouldBeAbleToUseArrowKeys() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("Tet" + Keys.ArrowLeft + "s"); Assert.AreEqual("Test", keyReporter.GetAttribute("value")); } [Test] [Category("Javascript")] public void WillSimulateAKeyUpWhenEnteringTextIntoInputElements() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyUp")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); Assert.AreEqual("I like cheese", result.Text); } [Test] [Category("Javascript")] public void WillSimulateAKeyDownWhenEnteringTextIntoInputElements() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyDown")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here Assert.AreEqual("I like chees", result.Text); } [Test] [Category("Javascript")] public void WillSimulateAKeyPressWhenEnteringTextIntoInputElements() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyPress")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here Assert.AreEqual("I like chees", result.Text); } [Test] [Category("Javascript")] public void WillSimulateAKeyUpWhenEnteringTextIntoTextAreas() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyUpArea")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); Assert.AreEqual("I like cheese", result.Text); } [Test] [Category("Javascript")] public void WillSimulateAKeyDownWhenEnteringTextIntoTextAreas() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyDownArea")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here Assert.AreEqual("I like chees", result.Text); } [Test] [Category("Javascript")] public void WillSimulateAKeyPressWhenEnteringTextIntoTextAreas() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyPressArea")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here Assert.AreEqual("I like chees", result.Text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Firefox, "Firefox demands to have the focus on the window already.")] public void ShouldFireFocusKeyEventsInTheRightOrder() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("theworks")); element.SendKeys("a"); Assert.AreEqual("focus keydown keypress keyup", result.Text.Trim()); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IE, "Firefox-specific test. IE does not report key press event.")] [IgnoreBrowser(Browser.HtmlUnit, "firefox-specific")] [IgnoreBrowser(Browser.Chrome, "Firefox-specific test. Chrome does not report key press event.")] [IgnoreBrowser(Browser.PhantomJS, "Firefox-specific test. PhantomJS does not report key press event.")] public void ShouldReportKeyCodeOfArrowKeys() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys(Keys.ArrowDown); Assert.AreEqual("down: 40 press: 40 up: 40", result.Text.Trim()); element.SendKeys(Keys.ArrowUp); Assert.AreEqual("down: 38 press: 38 up: 38", result.Text.Trim()); element.SendKeys(Keys.ArrowLeft); Assert.AreEqual("down: 37 press: 37 up: 37", result.Text.Trim()); element.SendKeys(Keys.ArrowRight); Assert.AreEqual("down: 39 press: 39 up: 39", result.Text.Trim()); // And leave no rubbish/printable keys in the "keyReporter" Assert.AreEqual(string.Empty, element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void ShouldReportKeyCodeOfArrowKeysUpDownEvents() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys(Keys.ArrowDown); string text = result.Text.Trim(); Assert.IsTrue(text.Contains("down: 40"), "Text should contain 'down: 40'. Actual text: {}", text); Assert.IsTrue(text.Contains("up: 40"), "Text should contain 'up: 40'. Actual text: {}", text); element.SendKeys(Keys.ArrowUp); text = result.Text.Trim(); Assert.IsTrue(text.Trim().Contains("down: 38"), "Text should contain 'down: 38'. Actual text: {}", text); Assert.IsTrue(text.Trim().Contains("up: 38"), "Text should contain 'up: 38'. Actual text: {}", text); element.SendKeys(Keys.ArrowLeft); text = result.Text.Trim(); Assert.IsTrue(text.Trim().Contains("down: 37"), "Text should contain 'down: 37'. Actual text: {}", text); Assert.IsTrue(text.Trim().Contains("up: 37"), "Text should contain 'up: 37'. Actual text: {}", text); element.SendKeys(Keys.ArrowRight); text = result.Text.Trim(); Assert.IsTrue(text.Trim().Contains("down: 39"), "Text should contain 'down: 39'. Actual text: {}", text); Assert.IsTrue(text.Trim().Contains("up: 39"), "Text should contain 'up: 39'. Actual text: {}", text); // And leave no rubbish/printable keys in the "keyReporter" Assert.AreEqual(string.Empty, element.GetAttribute("value")); } [Test] [Category("Javascript")] public void NumericNonShiftKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); string numericLineCharsNonShifted = "`1234567890-=[]\\;,.'/42"; element.SendKeys(numericLineCharsNonShifted); Assert.AreEqual(numericLineCharsNonShifted, element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void NumericShiftKeys() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); string numericShiftsEtc = "~!@#$%^&*()_+{}:\"<>?|END~"; element.SendKeys(numericShiftsEtc); Assert.AreEqual(numericShiftsEtc, element.GetAttribute("value")); string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); } [Test] [Category("Javascript")] public void LowerCaseAlphaKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); String lowerAlphas = "abcdefghijklmnopqrstuvwxyz"; element.SendKeys(lowerAlphas); Assert.AreEqual(lowerAlphas, element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void UppercaseAlphaKeys() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); String upperAlphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; element.SendKeys(upperAlphas); Assert.AreEqual(upperAlphas, element.GetAttribute("value")); string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void AllPrintableKeys() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); String allPrintable = "!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFGHIJKLMNO" + "PQRSTUVWXYZ [\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; element.SendKeys(allPrintable); Assert.AreEqual(allPrintable, element.GetAttribute("value")); string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); } [Test] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void ArrowKeysAndPageUpAndDown() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("a" + Keys.Left + "b" + Keys.Right + Keys.Up + Keys.Down + Keys.PageUp + Keys.PageDown + "1"); Assert.AreEqual("ba1", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void HomeAndEndAndPageUpAndPageDownKeys() { // FIXME: macs don't have HOME keys, would PGUP work? if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) { return; } driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("abc" + Keys.Home + "0" + Keys.Left + Keys.Right + Keys.PageUp + Keys.PageDown + Keys.End + "1" + Keys.Home + "0" + Keys.PageUp + Keys.End + "111" + Keys.Home + "00"); Assert.AreEqual("0000abc1111", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void DeleteAndBackspaceKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("abcdefghi"); Assert.AreEqual("abcdefghi", element.GetAttribute("value")); element.SendKeys(Keys.Left + Keys.Left + Keys.Delete); Assert.AreEqual("abcdefgi", element.GetAttribute("value")); element.SendKeys(Keys.Left + Keys.Left + Keys.Backspace); Assert.AreEqual("abcdfgi", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void SpecialSpaceKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("abcd" + Keys.Space + "fgh" + Keys.Space + "ij"); Assert.AreEqual("abcd fgh ij", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void NumberpadKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("abcd" + Keys.Multiply + Keys.Subtract + Keys.Add + Keys.Decimal + Keys.Separator + Keys.NumberPad0 + Keys.NumberPad9 + Keys.Add + Keys.Semicolon + Keys.Equal + Keys.Divide + Keys.NumberPad3 + "abcd"); Assert.AreEqual("abcd*-+.,09+;=/3abcd", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void NumberpadAndFunctionKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("FUNCTION" + Keys.F4 + "-KEYS" + Keys.F4); element.SendKeys("" + Keys.F4 + "-TOO" + Keys.F4); Assert.AreEqual("FUNCTION-KEYS-TOO", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] [IgnoreBrowser(Browser.Safari, "Issue 4221")] public void ShiftSelectionDeletes() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("abcd efgh"); Assert.AreEqual(element.GetAttribute("value"), "abcd efgh"); //Could be chord problem element.SendKeys(Keys.Shift + Keys.Left + Keys.Left + Keys.Left); element.SendKeys(Keys.Delete); Assert.AreEqual("abcd e", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void ChordControlHomeShiftEndDelete() { // FIXME: macs don't have HOME keys, would PGUP work? if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) { return; } driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG"); element.SendKeys(Keys.Home); element.SendKeys("" + Keys.Shift + Keys.End + Keys.Delete); Assert.AreEqual(string.Empty, element.GetAttribute("value")); string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void ChordReveseShiftHomeSelectionDeletes() { // FIXME: macs don't have HOME keys, would PGUP work? if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) { return; } driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("done" + Keys.Home); Assert.AreEqual("done", element.GetAttribute("value")); //Sending chords element.SendKeys("" + Keys.Shift + "ALL " + Keys.Home); Assert.AreEqual("ALL done", element.GetAttribute("value")); element.SendKeys(Keys.Delete); Assert.AreEqual("done", element.GetAttribute("value"), "done"); element.SendKeys("" + Keys.End + Keys.Shift + Keys.Home); Assert.AreEqual("done", element.GetAttribute("value")); // Note: trailing SHIFT up here string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); element.SendKeys("" + Keys.Delete); Assert.AreEqual(string.Empty, element.GetAttribute("value")); } // control-x control-v here for cut & paste tests, these work on windows // and linux, but not on the MAC. [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] [IgnoreBrowser(Browser.WindowsPhone, "JavaScript-only implementations cannot use system clipboard")] public void ChordControlCutAndPaste() { // FIXME: macs don't have HOME keys, would PGUP work? if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) { return; } driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); IWebElement result = driver.FindElement(By.Id("result")); String paste = "!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG"; element.SendKeys(paste); Assert.AreEqual(paste, element.GetAttribute("value")); //Chords element.SendKeys("" + Keys.Home + Keys.Shift + Keys.End); string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); element.SendKeys(Keys.Control + "x"); Assert.AreEqual(string.Empty, element.GetAttribute("value")); element.SendKeys(Keys.Control + "v"); Assert.AreEqual(paste, element.GetAttribute("value")); element.SendKeys("" + Keys.Left + Keys.Left + Keys.Left + Keys.Shift + Keys.End); element.SendKeys(Keys.Control + "x" + "v"); Assert.AreEqual(paste, element.GetAttribute("value")); element.SendKeys(Keys.Home); element.SendKeys(Keys.Control + "v"); element.SendKeys(Keys.Control + "v" + "v"); element.SendKeys(Keys.Control + "v" + "v" + "v"); Assert.AreEqual("EFGEFGEFGEFGEFGEFG" + paste, element.GetAttribute("value")); element.SendKeys("" + Keys.End + Keys.Shift + Keys.Home + Keys.Null + Keys.Delete); Assert.AreEqual(element.GetAttribute("value"), string.Empty); } [Test] [Category("Javascript")] public void ShouldTypeIntoInputElementsThatHaveNoTypeAttribute() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("no-type")); element.SendKeys("Should Say Cheese"); Assert.AreEqual("Should Say Cheese", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Chrome, "ChromeDriver2 allows typing into elements that prevent keydown")] public void ShouldNotTypeIntoElementsThatPreventKeyDownEvents() { driver.Url = javascriptPage; IWebElement silent = driver.FindElement(By.Name("suppress")); silent.SendKeys("s"); Assert.AreEqual(string.Empty, silent.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IE, "Firefox-specific test. IE does not report key press event.")] [IgnoreBrowser(Browser.Chrome, "firefox-specific")] [IgnoreBrowser(Browser.PhantomJS, "firefox-specific")] [IgnoreBrowser(Browser.Safari, "firefox-specific")] [IgnoreBrowser(Browser.Opera, "firefox-specific")] [IgnoreBrowser(Browser.IPhone, "firefox-specific")] [IgnoreBrowser(Browser.Android, "firefox-specific")] public void GenerateKeyPressEventEvenWhenElementPreventsDefault() { driver.Url = javascriptPage; IWebElement silent = driver.FindElement(By.Name("suppress")); IWebElement result = driver.FindElement(By.Id("result")); silent.SendKeys("s"); string text = result.Text; Assert.IsTrue(text.Contains("press"), "Text should contain 'press'. Actual text: {0}", text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.Safari, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.PhantomJS, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.Android, "Does not support contentEditable")] [IgnoreBrowser(Browser.IPhone, "Does not support contentEditable")] [IgnoreBrowser(Browser.Opera, "Does not support contentEditable")] [IgnoreBrowser(Browser.Chrome, "ChromeDriver2 does not support contentEditable yet")] [IgnoreBrowser(Browser.WindowsPhone, "Cannot type on contentEditable with synthetic events")] public void TypingIntoAnIFrameWithContentEditableOrDesignModeSet() { driver.Url = richTextPage; driver.SwitchTo().Frame("editFrame"); IWebElement element = driver.SwitchTo().ActiveElement(); element.SendKeys("Fishy"); driver.SwitchTo().DefaultContent(); IWebElement trusted = driver.FindElement(By.Id("istrusted")); IWebElement id = driver.FindElement(By.Id("tagId")); Assert.That(trusted.Text, Is.EqualTo("[true]").Or.EqualTo("[n/a]").Or.EqualTo("[]")); Assert.That(id.Text, Is.EqualTo("[frameHtml]").Or.EqualTo("[theBody]")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.Android, "Does not support contentEditable")] [IgnoreBrowser(Browser.IPhone, "Does not support contentEditable")] [IgnoreBrowser(Browser.Opera, "Does not support contentEditable")] [IgnoreBrowser(Browser.Chrome, "ChromeDriver 2 does not support contentEditable")] [IgnoreBrowser(Browser.WindowsPhone, "Cannot type on contentEditable with synthetic events")] public void NonPrintableCharactersShouldWorkWithContentEditableOrDesignModeSet() { driver.Url = richTextPage; // not tested on mac // FIXME: macs don't have HOME keys, would PGUP work? if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) { return; } driver.SwitchTo().Frame("editFrame"); IWebElement element = driver.SwitchTo().ActiveElement(); //Chords element.SendKeys("Dishy" + Keys.Backspace + Keys.Left + Keys.Left); element.SendKeys(Keys.Left + Keys.Left + "F" + Keys.Delete + Keys.End + "ee!"); Assert.AreEqual(element.Text, "Fishee!"); } [Test] public void ShouldBeAbleToTypeOnAnEmailInputField() { driver.Url = formsPage; IWebElement email = driver.FindElement(By.Id("email")); email.SendKeys("foobar"); Assert.AreEqual("foobar", email.GetAttribute("value")); } [Test] [IgnoreBrowser(Browser.HtmlUnit, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.Safari, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.PhantomJS, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.Android, "Does not support contentEditable")] [IgnoreBrowser(Browser.IPhone, "Does not support contentEditable")] [IgnoreBrowser(Browser.Opera, "Does not support contentEditable")] [IgnoreBrowser(Browser.Chrome, "ChromeDriver2 does not support contentEditable yet")] [IgnoreBrowser(Browser.WindowsPhone, "Cannot type on contentEditable with synthetic events")] public void testShouldBeAbleToTypeIntoEmptyContentEditableElement() { driver.Url = readOnlyPage; IWebElement editable = driver.FindElement(By.Id("content-editable")); editable.Clear(); editable.SendKeys("cheese"); // requires focus on OS X Assert.AreEqual("cheese", editable.Text); } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.LayoutRenderers; using NLog.Targets; using Xunit.Extensions; namespace NLog.UnitTests.Config { using System; using System.Globalization; using System.Threading; using Xunit; using NLog.Config; public class CultureInfoTests : NLogTestBase { [Fact] public void WhenInvariantCultureDefinedThenDefaultCultureIsInvariantCulture() { var configuration = CreateConfigurationFromString("<nlog useInvariantCulture='true'></nlog>"); Assert.Equal(CultureInfo.InvariantCulture, configuration.DefaultCultureInfo); } [Fact] public void DifferentConfigurations_UseDifferentDefaultCulture() { var currentCulture = CultureInfo.CurrentCulture; try { // set the current thread culture to be definitely different from the InvariantCulture Thread.CurrentThread.CurrentCulture = GetCultureInfo("de-DE"); var configurationTemplate = @"<nlog useInvariantCulture='{0}'> <targets> <target name='debug' type='Debug' layout='${{message}}' /> </targets> <rules> <logger name='*' writeTo='debug'/> </rules> </nlog>"; // configuration with current culture var configuration1 = CreateConfigurationFromString(string.Format(configurationTemplate, false)); Assert.Null(configuration1.DefaultCultureInfo); // configuration with invariant culture var configuration2 = CreateConfigurationFromString(string.Format(configurationTemplate, true)); Assert.Equal(CultureInfo.InvariantCulture, configuration2.DefaultCultureInfo); Assert.NotEqual(configuration1.DefaultCultureInfo, configuration2.DefaultCultureInfo); var testNumber = 3.14; var testDate = DateTime.Now; const string formatString = "{0},{1:d}"; AssertMessageFormattedWithCulture(configuration1, CultureInfo.CurrentCulture, formatString, testNumber, testDate); AssertMessageFormattedWithCulture(configuration2, CultureInfo.InvariantCulture, formatString, testNumber, testDate); } finally { // restore current thread culture Thread.CurrentThread.CurrentCulture = currentCulture; } } private void AssertMessageFormattedWithCulture(LoggingConfiguration configuration, CultureInfo culture, string formatString, params object[] parameters) { var expected = string.Format(culture, formatString, parameters); using (var logFactory = new LogFactory(configuration)) { var logger = logFactory.GetLogger("test"); logger.Debug(formatString, parameters); Assert.Equal(expected, GetDebugLastMessage("debug", configuration)); } } [Fact] public void EventPropRendererCultureTest() { string cultureName = "de-DE"; string expected = "1,23"; // with decimal comma var logEventInfo = CreateLogEventInfo(cultureName); logEventInfo.Properties["ADouble"] = 1.23; var renderer = new EventPropertiesLayoutRenderer(); renderer.Item = "ADouble"; string output = renderer.Render(logEventInfo); Assert.Equal(expected, output); } [Fact] public void EventContextRendererCultureTest() { string cultureName = "de-DE"; string expected = "1,23"; // with decimal comma var logEventInfo = CreateLogEventInfo(cultureName); logEventInfo.Properties["ADouble"] = 1.23; #pragma warning disable 618 var renderer = new EventContextLayoutRenderer(); #pragma warning restore 618 renderer.Item = "ADouble"; string output = renderer.Render(logEventInfo); Assert.Equal(expected, output); } [Fact] public void ProcessInfoLayoutRendererCultureTest() { string cultureName = "de-DE"; string expected = "."; // dot as date separator (01.10.2008) string output = string.Empty; var logEventInfo = CreateLogEventInfo(cultureName); if (IsTravis()) { Console.WriteLine("[SKIP] CultureInfoTests.ProcessInfoLayoutRendererCultureTest because we are running in Travis"); } else { var renderer = new ProcessInfoLayoutRenderer(); renderer.Property = ProcessInfoProperty.StartTime; renderer.Format = "d"; output = renderer.Render(logEventInfo); Assert.Contains(expected, output); Assert.DoesNotContain("/", output); Assert.DoesNotContain("-", output); } var renderer2 = new ProcessInfoLayoutRenderer(); renderer2.Property = ProcessInfoProperty.PriorityClass; renderer2.Format = "d"; output = renderer2.Render(logEventInfo); Assert.True(output.Length >= 1); Assert.True("012345678".IndexOf(output[0]) > 0); } [Fact] public void AllEventPropRendererCultureTest() { string cultureName = "de-DE"; string expected = "ADouble=1,23"; // with decimal comma var logEventInfo = CreateLogEventInfo(cultureName); logEventInfo.Properties["ADouble"] = 1.23; var renderer = new AllEventPropertiesLayoutRenderer(); string output = renderer.Render(logEventInfo); Assert.Equal(expected, output); } [Theory] [InlineData(typeof(TimeLayoutRenderer))] [InlineData(typeof(ProcessTimeLayoutRenderer))] public void DateTimeCultureTest(Type rendererType) { string cultureName = "de-DE"; string expected = ","; // decimal comma as separator for ticks var logEventInfo = CreateLogEventInfo(cultureName); var renderer = Activator.CreateInstance(rendererType) as LayoutRenderer; Assert.NotNull(renderer); string output = renderer.Render(logEventInfo); Assert.Contains(expected, output); Assert.DoesNotContain(".", output); } private static LogEventInfo CreateLogEventInfo(string cultureName) { var logEventInfo = new LogEventInfo( LogLevel.Info, "SomeName", CultureInfo.GetCultureInfo(cultureName), "SomeMessage", null); return logEventInfo; } /// <summary> /// expected: exactly the same exception message + stack trace regardless of the CurrentUICulture /// </summary> [Fact] public void ExceptionTest() { var target = new MemoryTarget { Layout = @"${exception:format=tostring}" }; SimpleConfigurator.ConfigureForTargetLogging(target); var logger = LogManager.GetCurrentClassLogger(); try { throw new InvalidOperationException(); } catch (Exception ex) { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US", false); Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false); logger.Error(ex, ""); #if !NETSTANDARD Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE", false); Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE", false); #endif logger.Error(ex, ""); Assert.Equal(2, target.Logs.Count); Assert.NotNull(target.Logs[0]); Assert.NotNull(target.Logs[1]); Assert.Equal(target.Logs[0], target.Logs[1]); } } } }
using System; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Crypto.Utilities; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Utilities; namespace Gnu.MP.BrickCoinProtocol.BouncyCastle.Crypto.Digests { /** * Base class for SHA-384 and SHA-512. */ internal abstract class LongDigest : IDigest, IMemoable { private int MyByteLength = 128; private byte[] xBuf; private int xBufOff; private long byteCount1; private long byteCount2; internal ulong H1, H2, H3, H4, H5, H6, H7, H8; private ulong[] W = new ulong[80]; private int wOff; /** * Constructor for variable length word */ internal LongDigest() { xBuf = new byte[8]; Reset(); } /** * Copy constructor. We are using copy constructors in place * of the object.Clone() interface as this interface is not * supported by J2ME. */ internal LongDigest( LongDigest t) { xBuf = new byte[t.xBuf.Length]; CopyIn(t); } protected void CopyIn(LongDigest t) { Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length); xBufOff = t.xBufOff; byteCount1 = t.byteCount1; byteCount2 = t.byteCount2; H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.W, 0, W, 0, t.W.Length); wOff = t.wOff; } public void Update( byte input) { xBuf[xBufOff++] = input; if(xBufOff == xBuf.Length) { ProcessWord(xBuf, 0); xBufOff = 0; } byteCount1++; } public void BlockUpdate( byte[] input, int inOff, int length) { // // fill the current word // while((xBufOff != 0) && (length > 0)) { Update(input[inOff]); inOff++; length--; } // // process whole words. // while(length > xBuf.Length) { ProcessWord(input, inOff); inOff += xBuf.Length; length -= xBuf.Length; byteCount1 += xBuf.Length; } // // load in the remainder. // while(length > 0) { Update(input[inOff]); inOff++; length--; } } public void Finish() { AdjustByteCounts(); long lowBitLength = byteCount1 << 3; long hiBitLength = byteCount2; // // add the pad bytes. // Update((byte)128); while(xBufOff != 0) { Update((byte)0); } ProcessLength(lowBitLength, hiBitLength); ProcessBlock(); } public virtual void Reset() { byteCount1 = 0; byteCount2 = 0; xBufOff = 0; for(int i = 0; i < xBuf.Length; i++) { xBuf[i] = 0; } wOff = 0; Array.Clear(W, 0, W.Length); } internal void ProcessWord( byte[] input, int inOff) { W[wOff] = Pack.BE_To_UInt64(input, inOff); if(++wOff == 16) { ProcessBlock(); } } /** * adjust the byte counts so that byteCount2 represents the * upper long (less 3 bits) word of the byte count. */ private void AdjustByteCounts() { if(byteCount1 > 0x1fffffffffffffffL) { byteCount2 += (long)((ulong)byteCount1 >> 61); byteCount1 &= 0x1fffffffffffffffL; } } internal void ProcessLength( long lowW, long hiW) { if(wOff > 14) { ProcessBlock(); } W[14] = (ulong)hiW; W[15] = (ulong)lowW; } internal void ProcessBlock() { AdjustByteCounts(); // // expand 16 word block into 80 word blocks. // for(int ti = 16; ti <= 79; ++ti) { W[ti] = Sigma1(W[ti - 2]) + W[ti - 7] + Sigma0(W[ti - 15]) + W[ti - 16]; } // // set up working variables. // ulong a = H1; ulong b = H2; ulong c = H3; ulong d = H4; ulong e = H5; ulong f = H6; ulong g = H7; ulong h = H8; int t = 0; for(int i = 0; i < 10; i++) { // t = 8 * i h += Sum1(e) + Ch(e, f, g) + K[t] + W[t++]; d += h; h += Sum0(a) + Maj(a, b, c); // t = 8 * i + 1 g += Sum1(d) + Ch(d, e, f) + K[t] + W[t++]; c += g; g += Sum0(h) + Maj(h, a, b); // t = 8 * i + 2 f += Sum1(c) + Ch(c, d, e) + K[t] + W[t++]; b += f; f += Sum0(g) + Maj(g, h, a); // t = 8 * i + 3 e += Sum1(b) + Ch(b, c, d) + K[t] + W[t++]; a += e; e += Sum0(f) + Maj(f, g, h); // t = 8 * i + 4 d += Sum1(a) + Ch(a, b, c) + K[t] + W[t++]; h += d; d += Sum0(e) + Maj(e, f, g); // t = 8 * i + 5 c += Sum1(h) + Ch(h, a, b) + K[t] + W[t++]; g += c; c += Sum0(d) + Maj(d, e, f); // t = 8 * i + 6 b += Sum1(g) + Ch(g, h, a) + K[t] + W[t++]; f += b; b += Sum0(c) + Maj(c, d, e); // t = 8 * i + 7 a += Sum1(f) + Ch(f, g, h) + K[t] + W[t++]; e += a; a += Sum0(b) + Maj(b, c, d); } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // wOff = 0; Array.Clear(W, 0, 16); } /* SHA-384 and SHA-512 functions (as for SHA-256 but for longs) */ private static ulong Ch(ulong x, ulong y, ulong z) { return (x & y) ^ (~x & z); } private static ulong Maj(ulong x, ulong y, ulong z) { return (x & y) ^ (x & z) ^ (y & z); } private static ulong Sum0(ulong x) { return ((x << 36) | (x >> 28)) ^ ((x << 30) | (x >> 34)) ^ ((x << 25) | (x >> 39)); } private static ulong Sum1(ulong x) { return ((x << 50) | (x >> 14)) ^ ((x << 46) | (x >> 18)) ^ ((x << 23) | (x >> 41)); } private static ulong Sigma0(ulong x) { return ((x << 63) | (x >> 1)) ^ ((x << 56) | (x >> 8)) ^ (x >> 7); } private static ulong Sigma1(ulong x) { return ((x << 45) | (x >> 19)) ^ ((x << 3) | (x >> 61)) ^ (x >> 6); } /* SHA-384 and SHA-512 Constants * (represent the first 64 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ internal static readonly ulong[] K = { 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 }; public int GetByteLength() { return MyByteLength; } public abstract string AlgorithmName { get; } public abstract int GetDigestSize(); public abstract int DoFinal(byte[] output, int outOff); public abstract IMemoable Copy(); public abstract void Reset(IMemoable t); } }
/* * 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.Cache { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Cache.Query.Continuous; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cache.Expiry; using Apache.Ignite.Core.Impl.Cache.Query; using Apache.Ignite.Core.Impl.Cache.Query.Continuous; using Apache.Ignite.Core.Impl.Client; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Transactions; /// <summary> /// Native cache wrapper. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] internal class CacheImpl<TK, TV> : PlatformTargetAdapter, ICache<TK, TV>, ICacheInternal, ICacheLockInternal { /** Ignite instance. */ private readonly IIgniteInternal _ignite; /** Flag: skip store. */ private readonly bool _flagSkipStore; /** Flag: keep binary. */ private readonly bool _flagKeepBinary; /** Flag: allow atomic operations in transactions. */ private readonly bool _flagAllowAtomicOpsInTx; /** Flag: no-retries.*/ private readonly bool _flagNoRetries; /** Flag: partition recover.*/ private readonly bool _flagPartitionRecover; /** Transaction manager. */ private readonly CacheTransactionManager _txManager; /** Pre-allocated delegate. */ private readonly Func<IBinaryStream, Exception> _readException; /// <summary> /// Constructor. /// </summary> /// <param name="target">Target.</param> /// <param name="flagSkipStore">Skip store flag.</param> /// <param name="flagKeepBinary">Keep binary flag.</param> /// <param name="flagNoRetries">No-retries mode flag.</param> /// <param name="flagPartitionRecover">Partition recover mode flag.</param> /// <param name="flagAllowAtomicOpsInTx">Allow atomic operations in transactions flag.</param> public CacheImpl(IPlatformTargetInternal target, bool flagSkipStore, bool flagKeepBinary, bool flagNoRetries, bool flagPartitionRecover, bool flagAllowAtomicOpsInTx) : base(target) { _ignite = target.Marshaller.Ignite; _flagSkipStore = flagSkipStore; _flagKeepBinary = flagKeepBinary; _flagNoRetries = flagNoRetries; _flagPartitionRecover = flagPartitionRecover; _flagAllowAtomicOpsInTx = flagAllowAtomicOpsInTx; _txManager = GetConfiguration().AtomicityMode == CacheAtomicityMode.Transactional ? new CacheTransactionManager(_ignite.GetIgnite().GetTransactions()) : null; _readException = stream => ReadException(Marshaller.StartUnmarshal(stream)); } /** <inheritDoc /> */ public IIgnite Ignite { get { return _ignite.GetIgnite(); } } /// <summary> /// Performs async operation. /// </summary> private Task DoOutOpAsync<T1>(CacheOp op, T1 val1) { return DoOutOpAsync<object, T1>((int) op, val1); } /// <summary> /// Performs async operation. /// </summary> private Task<TR> DoOutOpAsync<T1, TR>(CacheOp op, T1 val1) { return DoOutOpAsync<T1, TR>((int) op, val1); } /// <summary> /// Performs async operation. /// </summary> private Task DoOutOpAsync<T1, T2>(CacheOp op, T1 val1, T2 val2) { return DoOutOpAsync<T1, T2, object>((int) op, val1, val2); } /// <summary> /// Performs async operation. /// </summary> private Task<TR> DoOutOpAsync<T1, T2, TR>(CacheOp op, T1 val1, T2 val2) { return DoOutOpAsync<T1, T2, TR>((int) op, val1, val2); } /// <summary> /// Performs async operation. /// </summary> private Task DoOutOpAsync(CacheOp op, Action<BinaryWriter> writeAction = null) { return DoOutOpAsync<object>(op, writeAction); } /// <summary> /// Performs async operation. /// </summary> private Task<T> DoOutOpAsync<T>(CacheOp op, Action<BinaryWriter> writeAction = null, Func<BinaryReader, T> convertFunc = null) { return DoOutOpAsync((int)op, writeAction, IsKeepBinary, convertFunc); } /** <inheritDoc /> */ public string Name { get { return DoInOp<string>((int)CacheOp.GetName); } } /** <inheritDoc /> */ public CacheConfiguration GetConfiguration() { return DoInOp((int) CacheOp.GetConfig, stream => new CacheConfiguration( BinaryUtils.Marshaller.StartUnmarshal(stream), ClientSocket.CurrentProtocolVersion)); } /** <inheritDoc /> */ public bool IsEmpty() { return GetSize() == 0; } /** <inheritDoc /> */ public ICache<TK, TV> WithSkipStore() { if (_flagSkipStore) return this; return new CacheImpl<TK, TV>(DoOutOpObject((int) CacheOp.WithSkipStore), true, _flagKeepBinary, true, _flagPartitionRecover, _flagAllowAtomicOpsInTx); } /// <summary> /// Skip store flag getter. /// </summary> internal bool IsSkipStore { get { return _flagSkipStore; } } /** <inheritDoc /> */ public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>() { if (_flagKeepBinary) { var result = this as ICache<TK1, TV1>; if (result == null) throw new InvalidOperationException( "Can't change type of binary cache. WithKeepBinary has been called on an instance of " + "binary cache with incompatible generic arguments."); return result; } return new CacheImpl<TK1, TV1>(DoOutOpObject((int) CacheOp.WithKeepBinary), _flagSkipStore, true, _flagNoRetries, _flagPartitionRecover, _flagAllowAtomicOpsInTx); } /** <inheritDoc /> */ public ICache<TK, TV> WithAllowAtomicOpsInTx() { if (_flagAllowAtomicOpsInTx) return this; return new CacheImpl<TK, TV>(DoOutOpObject((int)CacheOp.WithSkipStore), true, _flagKeepBinary, _flagSkipStore, _flagPartitionRecover, true); } /** <inheritDoc /> */ public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc) { IgniteArgumentCheck.NotNull(plc, "plc"); var cache0 = DoOutOpObject((int)CacheOp.WithExpiryPolicy, w => ExpiryPolicySerializer.WritePolicy(w, plc)); return new CacheImpl<TK, TV>(cache0, _flagSkipStore, _flagKeepBinary, _flagNoRetries, _flagPartitionRecover, _flagAllowAtomicOpsInTx); } /** <inheritDoc /> */ public bool IsKeepBinary { get { return _flagKeepBinary; } } /** <inheritDoc /> */ public bool IsAllowAtomicOpsInTx { get { return _flagAllowAtomicOpsInTx; } } /** <inheritDoc /> */ public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args) { DoOutInOpX((int) CacheOp.LoadCache, writer => WriteLoadCacheData(writer, p, args), _readException); } /** <inheritDoc /> */ public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args) { return DoOutOpAsync(CacheOp.LoadCacheAsync, writer => WriteLoadCacheData(writer, p, args)); } /** <inheritDoc /> */ public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args) { DoOutInOpX((int) CacheOp.LocLoadCache, writer => WriteLoadCacheData(writer, p, args), _readException); } /** <inheritDoc /> */ public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args) { return DoOutOpAsync(CacheOp.LocLoadCacheAsync, writer => WriteLoadCacheData(writer, p, args)); } /// <summary> /// Writes the load cache data to the writer. /// </summary> private void WriteLoadCacheData(BinaryWriter writer, ICacheEntryFilter<TK, TV> p, object[] args) { if (p != null) { var p0 = new CacheEntryFilterHolder(p, (k, v) => p.Invoke(new CacheEntry<TK, TV>((TK) k, (TV) v)), Marshaller, IsKeepBinary); writer.WriteObjectDetached(p0); } else { writer.WriteObjectDetached<CacheEntryFilterHolder>(null); } if (args != null && args.Length > 0) { writer.WriteInt(args.Length); foreach (var o in args) { writer.WriteObjectDetached(o); } } else { writer.WriteInt(0); } } /** <inheritDoc /> */ public void LoadAll(IEnumerable<TK> keys, bool replaceExistingValues) { LoadAllAsync(keys, replaceExistingValues).Wait(); } /** <inheritDoc /> */ public Task LoadAllAsync(IEnumerable<TK> keys, bool replaceExistingValues) { return DoOutOpAsync(CacheOp.LoadAll, writer => { writer.WriteBoolean(replaceExistingValues); writer.WriteEnumerable(keys); }); } /** <inheritDoc /> */ public bool ContainsKey(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp(CacheOp.ContainsKey, key); } /** <inheritDoc /> */ public Task<bool> ContainsKeyAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOpAsync<TK, bool>(CacheOp.ContainsKeyAsync, key); } /** <inheritDoc /> */ public bool ContainsKeys(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOp(CacheOp.ContainsKeys, writer => writer.WriteEnumerable(keys)); } /** <inheritDoc /> */ public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOpAsync<bool>(CacheOp.ContainsKeysAsync, writer => writer.WriteEnumerable(keys)); } /** <inheritDoc /> */ public TV LocalPeek(TK key, params CachePeekMode[] modes) { IgniteArgumentCheck.NotNull(key, "key"); TV res; if (TryLocalPeek(key, out res)) return res; throw GetKeyNotFoundException(); } /** <inheritDoc /> */ public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes) { IgniteArgumentCheck.NotNull(key, "key"); var res = DoOutInOpX((int)CacheOp.Peek, w => { w.WriteObjectDetached(key); w.WriteInt(IgniteUtils.EncodePeekModes(modes)); }, (s, r) => r == True ? new CacheResult<TV>(Unmarshal<TV>(s)) : new CacheResult<TV>(), _readException); value = res.Success ? res.Value : default(TV); return res.Success; } /** <inheritDoc /> */ public TV this[TK key] { get { return Get(key); } set { Put(key, value); } } /** <inheritDoc /> */ public TV Get(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOpX((int) CacheOp.Get, w => w.Write(key), (stream, res) => { if (res != True) throw GetKeyNotFoundException(); return Unmarshal<TV>(stream); }, _readException); } /** <inheritDoc /> */ public Task<TV> GetAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOpAsync(CacheOp.GetAsync, w => w.WriteObject(key), reader => { if (reader != null) return reader.ReadObject<TV>(); throw GetKeyNotFoundException(); }); } /** <inheritDoc /> */ public bool TryGet(TK key, out TV value) { IgniteArgumentCheck.NotNull(key, "key"); var res = DoOutInOpNullable(CacheOp.Get, key); value = res.Value; return res.Success; } /** <inheritDoc /> */ public Task<CacheResult<TV>> TryGetAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOpAsync(CacheOp.GetAsync, w => w.WriteObject(key), reader => GetCacheResult(reader)); } /** <inheritDoc /> */ public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutInOpX((int) CacheOp.GetAll, writer => writer.WriteEnumerable(keys), (s, r) => r == True ? ReadGetAllDictionary(Marshaller.StartUnmarshal(s, _flagKeepBinary)) : null, _readException); } /** <inheritDoc /> */ public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOpAsync(CacheOp.GetAllAsync, w => w.WriteEnumerable(keys), r => ReadGetAllDictionary(r)); } /** <inheritdoc /> */ public void Put(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); DoOutOp(CacheOp.Put, key, val); } /** <inheritDoc /> */ public Task PutAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync(CacheOp.PutAsync, key, val); } /** <inheritDoc /> */ public CacheResult<TV> GetAndPut(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutInOpNullable(CacheOp.GetAndPut, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync(CacheOp.GetAndPutAsync, w => { w.WriteObjectDetached(key); w.WriteObjectDetached(val); }, r => GetCacheResult(r)); } /** <inheritDoc /> */ public CacheResult<TV> GetAndReplace(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutInOpNullable(CacheOp.GetAndReplace, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync(CacheOp.GetAndReplaceAsync, w => { w.WriteObjectDetached(key); w.WriteObjectDetached(val); }, r => GetCacheResult(r)); } /** <inheritDoc /> */ public CacheResult<TV> GetAndRemove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); StartTx(); return DoOutInOpNullable(CacheOp.GetAndRemove, key); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndRemoveAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); StartTx(); return DoOutOpAsync(CacheOp.GetAndRemoveAsync, w => w.WriteObject(key), r => GetCacheResult(r)); } /** <inheritdoc /> */ public bool PutIfAbsent(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOp(CacheOp.PutIfAbsent, key, val); } /** <inheritDoc /> */ public Task<bool> PutIfAbsentAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync<TK, TV, bool>(CacheOp.PutIfAbsentAsync, key, val); } /** <inheritdoc /> */ public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutInOpNullable(CacheOp.GetAndPutIfAbsent, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync(CacheOp.GetAndPutIfAbsentAsync, w => { w.WriteObjectDetached(key); w.WriteObjectDetached(val); }, r => GetCacheResult(r)); } /** <inheritdoc /> */ public bool Replace(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOp(CacheOp.Replace2, key, val); } /** <inheritDoc /> */ public Task<bool> ReplaceAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync<TK, TV, bool>(CacheOp.Replace2Async, key, val); } /** <inheritdoc /> */ public bool Replace(TK key, TV oldVal, TV newVal) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(oldVal, "oldVal"); IgniteArgumentCheck.NotNull(newVal, "newVal"); StartTx(); return DoOutOp(CacheOp.Replace3, key, oldVal, newVal); } /** <inheritDoc /> */ public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(oldVal, "oldVal"); IgniteArgumentCheck.NotNull(newVal, "newVal"); StartTx(); return DoOutOpAsync<bool>(CacheOp.Replace3Async, w => { w.WriteObjectDetached(key); w.WriteObjectDetached(oldVal); w.WriteObjectDetached(newVal); }); } /** <inheritdoc /> */ public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals) { IgniteArgumentCheck.NotNull(vals, "vals"); StartTx(); DoOutOp(CacheOp.PutAll, writer => writer.WriteDictionary(vals)); } /** <inheritDoc /> */ public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals) { IgniteArgumentCheck.NotNull(vals, "vals"); StartTx(); return DoOutOpAsync(CacheOp.PutAllAsync, writer => writer.WriteDictionary(vals)); } /** <inheritdoc /> */ public void LocalEvict(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp(CacheOp.LocEvict, writer => writer.WriteEnumerable(keys)); } /** <inheritdoc /> */ public void Clear() { DoOutInOp((int) CacheOp.ClearCache); } /** <inheritDoc /> */ public Task ClearAsync() { return DoOutOpAsync(CacheOp.ClearCacheAsync); } /** <inheritdoc /> */ public void Clear(TK key) { IgniteArgumentCheck.NotNull(key, "key"); DoOutOp(CacheOp.Clear, key); } /** <inheritDoc /> */ public Task ClearAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOpAsync(CacheOp.ClearAsync, key); } /** <inheritdoc /> */ public void ClearAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp(CacheOp.ClearAll, writer => writer.WriteEnumerable(keys)); } /** <inheritDoc /> */ public Task ClearAllAsync(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOpAsync(CacheOp.ClearAllAsync, writer => writer.WriteEnumerable(keys)); } /** <inheritdoc /> */ public void LocalClear(TK key) { IgniteArgumentCheck.NotNull(key, "key"); DoOutOp(CacheOp.LocalClear, key); } /** <inheritdoc /> */ public void LocalClearAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp(CacheOp.LocalClearAll, writer => writer.WriteEnumerable(keys)); } /** <inheritdoc /> */ public bool Remove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); StartTx(); return DoOutOp(CacheOp.RemoveObj, key); } /** <inheritDoc /> */ public Task<bool> RemoveAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); StartTx(); return DoOutOpAsync<TK, bool>(CacheOp.RemoveObjAsync, key); } /** <inheritDoc /> */ public bool Remove(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOp(CacheOp.RemoveBool, key, val); } /** <inheritDoc /> */ public Task<bool> RemoveAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync<TK, TV, bool>(CacheOp.RemoveBoolAsync, key, val); } /** <inheritDoc /> */ public void RemoveAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); StartTx(); DoOutOp(CacheOp.RemoveAll, writer => writer.WriteEnumerable(keys)); } /** <inheritDoc /> */ public Task RemoveAllAsync(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); StartTx(); return DoOutOpAsync(CacheOp.RemoveAllAsync, writer => writer.WriteEnumerable(keys)); } /** <inheritDoc /> */ public void RemoveAll() { StartTx(); DoOutInOp((int) CacheOp.RemoveAll2); } /** <inheritDoc /> */ public Task RemoveAllAsync() { StartTx(); return DoOutOpAsync(CacheOp.RemoveAll2Async); } /** <inheritDoc /> */ public int GetLocalSize(params CachePeekMode[] modes) { return Size0(true, modes); } /** <inheritDoc /> */ public int GetSize(params CachePeekMode[] modes) { return Size0(false, modes); } /** <inheritDoc /> */ public Task<int> GetSizeAsync(params CachePeekMode[] modes) { var modes0 = IgniteUtils.EncodePeekModes(modes); return DoOutOpAsync<int>(CacheOp.SizeAsync, w => w.WriteInt(modes0)); } /// <summary> /// Internal size routine. /// </summary> /// <param name="loc">Local flag.</param> /// <param name="modes">peek modes</param> /// <returns>Size.</returns> private int Size0(bool loc, params CachePeekMode[] modes) { var modes0 = IgniteUtils.EncodePeekModes(modes); var op = loc ? CacheOp.SizeLoc : CacheOp.Size; return (int) DoOutInOp((int) op, modes0); } /** <inheritdoc /> */ public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(processor, "processor"); StartTx(); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutInOpX((int) CacheOp.Invoke, writer => { writer.WriteObjectDetached(key); writer.WriteObjectDetached(holder); }, (input, res) => res == True ? Unmarshal<TRes>(input) : default(TRes), _readException); } /** <inheritDoc /> */ public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(processor, "processor"); StartTx(); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutOpAsync(CacheOp.InvokeAsync, writer => { writer.WriteObjectDetached(key); writer.WriteObjectDetached(holder); }, r => { if (r == null) return default(TRes); var hasError = r.ReadBoolean(); if (hasError) throw ReadException(r); return r.ReadObject<TRes>(); }); } /** <inheritdoc /> */ public ICollection<ICacheEntryProcessorResult<TK, TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(keys, "keys"); IgniteArgumentCheck.NotNull(processor, "processor"); StartTx(); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutInOpX((int) CacheOp.InvokeAll, writer => { writer.WriteEnumerable(keys); writer.Write(holder); }, (input, res) => res == True ? ReadInvokeAllResults<TRes>(Marshaller.StartUnmarshal(input, IsKeepBinary)) : null, _readException); } /** <inheritDoc /> */ public Task<ICollection<ICacheEntryProcessorResult<TK, TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(keys, "keys"); IgniteArgumentCheck.NotNull(processor, "processor"); StartTx(); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutOpAsync(CacheOp.InvokeAllAsync, writer => { writer.WriteEnumerable(keys); writer.Write(holder); }, input => ReadInvokeAllResults<TRes>(input)); } /** <inheritDoc /> */ public T DoOutInOpExtension<T>(int extensionId, int opCode, Action<IBinaryRawWriter> writeAction, Func<IBinaryRawReader, T> readFunc) { return DoOutInOpX((int) CacheOp.Extension, writer => { writer.WriteInt(extensionId); writer.WriteInt(opCode); writeAction(writer); }, (input, res) => res == True ? readFunc(Marshaller.StartUnmarshal(input)) : default(T), _readException); } /** <inheritdoc /> */ public ICacheLock Lock(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOpX((int) CacheOp.Lock, w => w.Write(key), (stream, res) => new CacheLock(stream.ReadInt(), this), _readException); } /** <inheritdoc /> */ public ICacheLock LockAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutInOpX((int) CacheOp.LockAll, w => w.WriteEnumerable(keys), (stream, res) => new CacheLock(stream.ReadInt(), this), _readException); } /** <inheritdoc /> */ public bool IsLocalLocked(TK key, bool byCurrentThread) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp(CacheOp.IsLocalLocked, writer => { writer.Write(key); writer.WriteBoolean(byCurrentThread); }); } /** <inheritDoc /> */ public ICacheMetrics GetMetrics() { return DoInOp((int) CacheOp.GlobalMetrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return new CacheMetricsImpl(reader); }); } /** <inheritDoc /> */ public ICacheMetrics GetMetrics(IClusterGroup clusterGroup) { IgniteArgumentCheck.NotNull(clusterGroup, "clusterGroup"); var prj = clusterGroup as ClusterGroupImpl; if (prj == null) throw new ArgumentException("Unexpected IClusterGroup implementation: " + clusterGroup.GetType()); return prj.GetCacheMetrics(Name); } /** <inheritDoc /> */ public ICacheMetrics GetLocalMetrics() { return DoInOp((int) CacheOp.LocalMetrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return new CacheMetricsImpl(reader); }); } /** <inheritDoc /> */ public Task Rebalance() { return DoOutOpAsync(CacheOp.Rebalance); } /** <inheritDoc /> */ public ICache<TK, TV> WithNoRetries() { if (_flagNoRetries) return this; return new CacheImpl<TK, TV>(DoOutOpObject((int) CacheOp.WithNoRetries), _flagSkipStore, _flagKeepBinary, true, _flagPartitionRecover, _flagAllowAtomicOpsInTx); } /** <inheritDoc /> */ public ICache<TK, TV> WithPartitionRecover() { if (_flagPartitionRecover) return this; return new CacheImpl<TK, TV>(DoOutOpObject((int) CacheOp.WithPartitionRecover), _flagSkipStore, _flagKeepBinary, _flagNoRetries, true, _flagAllowAtomicOpsInTx); } /** <inheritDoc /> */ public ICollection<int> GetLostPartitions() { return DoInOp((int) CacheOp.GetLostPartitions, s => { var cnt = s.ReadInt(); var res = new List<int>(cnt); if (cnt > 0) { for (var i = 0; i < cnt; i++) { res.Add(s.ReadInt()); } } return res; }); } #region Queries /** <inheritDoc /> */ public IFieldsQueryCursor Query(SqlFieldsQuery qry) { var cursor = QueryFieldsInternal(qry); return new FieldsQueryCursor(cursor, _flagKeepBinary, (reader, count) => ReadFieldsArrayList(reader, count)); } /** <inheritDoc /> */ public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry) { return Query(qry, (reader, count) => (IList) ReadFieldsArrayList(reader, count)); } /// <summary> /// Reads the fields array list. /// </summary> private static List<object> ReadFieldsArrayList(IBinaryRawReader reader, int count) { var res = new List<object>(count); for (var i = 0; i < count; i++) res.Add(reader.ReadObject<object>()); return res; } /** <inheritDoc /> */ public IQueryCursor<T> Query<T>(SqlFieldsQuery qry, Func<IBinaryRawReader, int, T> readerFunc) { var cursor = QueryFieldsInternal(qry); return new FieldsQueryCursor<T>(cursor, _flagKeepBinary, readerFunc); } private IPlatformTargetInternal QueryFieldsInternal(SqlFieldsQuery qry) { IgniteArgumentCheck.NotNull(qry, "qry"); if (string.IsNullOrEmpty(qry.Sql)) throw new ArgumentException("Sql cannot be null or empty"); return DoOutOpObject((int) CacheOp.QrySqlFields, writer => { writer.WriteBoolean(qry.Local); writer.WriteString(qry.Sql); writer.WriteInt(qry.PageSize); QueryBase.WriteQueryArgs(writer, qry.Arguments); writer.WriteBoolean(qry.EnableDistributedJoins); writer.WriteBoolean(qry.EnforceJoinOrder); writer.WriteBoolean(qry.Lazy); // Lazy flag. writer.WriteInt((int) qry.Timeout.TotalMilliseconds); writer.WriteBoolean(qry.ReplicatedOnly); writer.WriteBoolean(qry.Colocated); writer.WriteString(qry.Schema); // Schema }); } /** <inheritDoc /> */ public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry) { IgniteArgumentCheck.NotNull(qry, "qry"); var cursor = DoOutOpObject((int) qry.OpId, writer => qry.Write(writer, IsKeepBinary)); return new QueryCursor<TK, TV>(cursor, _flagKeepBinary); } /** <inheritdoc /> */ public IContinuousQueryHandle QueryContinuous(ContinuousQuery<TK, TV> qry) { IgniteArgumentCheck.NotNull(qry, "qry"); return QueryContinuousImpl(qry, null); } /** <inheritdoc /> */ public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry) { IgniteArgumentCheck.NotNull(qry, "qry"); IgniteArgumentCheck.NotNull(initialQry, "initialQry"); return QueryContinuousImpl(qry, initialQry); } /// <summary> /// QueryContinuous implementation. /// </summary> private IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuousImpl(ContinuousQuery<TK, TV> qry, QueryBase initialQry) { qry.Validate(); return new ContinuousQueryHandleImpl<TK, TV>(qry, Marshaller, _flagKeepBinary, writeAction => DoOutOpObject((int) CacheOp.QryContinuous, writeAction), initialQry); } #endregion #region Enumerable support /** <inheritdoc /> */ public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(CachePeekMode[] peekModes) { return new CacheEnumerable<TK, TV>(this, IgniteUtils.EncodePeekModes(peekModes)); } /** <inheritdoc /> */ public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator() { return new CacheEnumeratorProxy<TK, TV>(this, false, 0); } /** <inheritdoc /> */ IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Create real cache enumerator. /// </summary> /// <param name="loc">Local flag.</param> /// <param name="peekModes">Peek modes for local enumerator.</param> /// <returns>Cache enumerator.</returns> internal CacheEnumerator<TK, TV> CreateEnumerator(bool loc, int peekModes) { if (loc) { var target = DoOutOpObject((int) CacheOp.LocIterator, (IBinaryStream s) => s.WriteInt(peekModes)); return new CacheEnumerator<TK, TV>(target, _flagKeepBinary); } return new CacheEnumerator<TK, TV>(DoOutOpObject((int) CacheOp.Iterator), _flagKeepBinary); } #endregion /** <inheritDoc /> */ protected override T Unmarshal<T>(IBinaryStream stream) { return Marshaller.Unmarshal<T>(stream, _flagKeepBinary); } /// <summary> /// Reads results of InvokeAll operation. /// </summary> /// <typeparam name="T">The type of the result.</typeparam> /// <param name="reader">Stream.</param> /// <returns>Results of InvokeAll operation.</returns> private ICollection<ICacheEntryProcessorResult<TK, T>> ReadInvokeAllResults<T>(BinaryReader reader) { var count = reader.ReadInt(); if (count == -1) return null; var results = new List<ICacheEntryProcessorResult<TK, T>>(count); for (var i = 0; i < count; i++) { var key = reader.ReadObject<TK>(); var hasError = reader.ReadBoolean(); results.Add(hasError ? new CacheEntryProcessorResult<TK, T>(key, ReadException(reader)) : new CacheEntryProcessorResult<TK, T>(key, reader.ReadObject<T>())); } return results; } /// <summary> /// Reads the exception, either in binary wrapper form, or as a pair of strings. /// </summary> /// <param name="reader">The stream.</param> /// <returns>Exception.</returns> private Exception ReadException(BinaryReader reader) { var item = reader.ReadObject<object>(); var clsName = item as string; if (clsName == null) return new CacheEntryProcessorException((Exception) item); var msg = reader.ReadObject<string>(); var trace = reader.ReadObject<string>(); var inner = reader.ReadBoolean() ? reader.ReadObject<Exception>() : null; return ExceptionUtils.GetException(_ignite, clsName, msg, trace, reader, inner); } /// <summary> /// Read dictionary returned by GET_ALL operation. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Dictionary.</returns> private static ICollection<ICacheEntry<TK, TV>> ReadGetAllDictionary(BinaryReader reader) { if (reader == null) return null; IBinaryStream stream = reader.Stream; if (stream.ReadBool()) { int size = stream.ReadInt(); var res = new List<ICacheEntry<TK, TV>>(size); for (int i = 0; i < size; i++) { TK key = reader.ReadObject<TK>(); TV val = reader.ReadObject<TV>(); res.Add(new CacheEntry<TK, TV>(key, val)); } return res; } return null; } /// <summary> /// Gets the cache result. /// </summary> private static CacheResult<TV> GetCacheResult(BinaryReader reader) { var res = reader == null ? new CacheResult<TV>() : new CacheResult<TV>(reader.ReadObject<TV>()); return res; } /// <summary> /// Throws the key not found exception. /// </summary> private static KeyNotFoundException GetKeyNotFoundException() { return new KeyNotFoundException("The given key was not present in the cache."); } /// <summary> /// Does the out op. /// </summary> private bool DoOutOp<T1>(CacheOp op, T1 x) { return DoOutInOpX((int) op, w => { w.Write(x); }, _readException); } /// <summary> /// Does the out op. /// </summary> private bool DoOutOp<T1, T2>(CacheOp op, T1 x, T2 y) { return DoOutInOpX((int) op, w => { w.WriteObjectDetached(x); w.WriteObjectDetached(y); }, _readException); } /// <summary> /// Does the out op. /// </summary> private bool DoOutOp<T1, T2, T3>(CacheOp op, T1 x, T2 y, T3 z) { return DoOutInOpX((int) op, w => { w.WriteObjectDetached(x); w.WriteObjectDetached(y); w.WriteObjectDetached(z); }, _readException); } /// <summary> /// Does the out op. /// </summary> private bool DoOutOp(CacheOp op, Action<BinaryWriter> write) { return DoOutInOpX((int) op, write, _readException); } /// <summary> /// Does the out-in op. /// </summary> private CacheResult<TV> DoOutInOpNullable(CacheOp cacheOp, TK x) { return DoOutInOpX((int)cacheOp, w => w.Write(x), (stream, res) => res == True ? new CacheResult<TV>(Unmarshal<TV>(stream)) : new CacheResult<TV>(), _readException); } /// <summary> /// Does the out-in op. /// </summary> private CacheResult<TV> DoOutInOpNullable<T1, T2>(CacheOp cacheOp, T1 x, T2 y) { return DoOutInOpX((int)cacheOp, w => { w.WriteObjectDetached(x); w.WriteObjectDetached(y); }, (stream, res) => res == True ? new CacheResult<TV>(Unmarshal<TV>(stream)) : new CacheResult<TV>(), _readException); } /** <inheritdoc /> */ public void Enter(long id) { DoOutInOp((int) CacheOp.EnterLock, id); } /** <inheritdoc /> */ public bool TryEnter(long id, TimeSpan timeout) { return DoOutOp((int) CacheOp.TryEnterLock, (IBinaryStream s) => { s.WriteLong(id); s.WriteLong((long) timeout.TotalMilliseconds); }) == True; } /** <inheritdoc /> */ public void Exit(long id) { DoOutInOp((int) CacheOp.ExitLock, id); } /** <inheritdoc /> */ public void Close(long id) { DoOutInOp((int) CacheOp.CloseLock, id); } /// <summary> /// Starts a transaction when applicable. /// </summary> private void StartTx() { if (_txManager != null) _txManager.StartTx(); } /** <inheritdoc /> */ public IQueryMetrics GetQueryMetrics() { return DoInOp((int)CacheOp.QueryMetrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return new QueryMetricsImpl(reader); }); } /** <inheritdoc /> */ public void ResetQueryMetrics() { DoOutInOp((int)CacheOp.ResetQueryMetrics); } } }
using System; using System.Globalization; using System.Text; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1 { /** * Generalized time object. */ public class DerGeneralizedTime : Asn1Object { private readonly string time; /** * return a generalized time from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerGeneralizedTime GetInstance( object obj) { if (obj == null || obj is DerGeneralizedTime) { return (DerGeneralizedTime)obj; } throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj"); } /** * return a Generalized Time object from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerGeneralizedTime GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerGeneralizedTime) { return GetInstance(o); } return new DerGeneralizedTime(((Asn1OctetString)o).GetOctets()); } /** * The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z * for local time, or Z+-HHMM on the end, for difference between local * time and UTC time. The fractional second amount f must consist of at * least one number with trailing zeroes removed. * * @param time the time string. * @exception ArgumentException if string is an illegal format. */ public DerGeneralizedTime( string time) { this.time = time; try { ToDateTime(); } catch (FormatException e) { throw new ArgumentException("invalid date string: " + e.Message); } } /** * base constructor from a local time object */ public DerGeneralizedTime( DateTime time) { this.time = time.ToString(@"yyyyMMddHHmmss\Z"); } internal DerGeneralizedTime( byte[] bytes) { // // explicitly convert to characters // this.time = Strings.FromAsciiByteArray(bytes); } /** * Return the time. * @return The time string as it appeared in the encoded object. */ public string TimeString { get { return time; } } /** * return the time - always in the form of * YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm). * <p> * Normally in a certificate we would expect "Z" rather than "GMT", * however adding the "GMT" means we can just use: * <pre> * dateF = new SimpleDateFormat("yyyyMMddHHmmssz"); * </pre> * To read in the time and Get a date which is compatible with our local * time zone.</p> */ public string GetTime() { // // standardise the format. // if (time[time.Length - 1] == 'Z') { return time.Substring(0, time.Length - 1) + "GMT+00:00"; } else { int signPos = time.Length - 5; char sign = time[signPos]; if (sign == '-' || sign == '+') { return time.Substring(0, signPos) + "GMT" + time.Substring(signPos, 3) + ":" + time.Substring(signPos + 3); } else { signPos = time.Length - 3; sign = time[signPos]; if (sign == '-' || sign == '+') { return time.Substring(0, signPos) + "GMT" + time.Substring(signPos) + ":00"; } } } return time + CalculateGmtOffset(); } private string CalculateGmtOffset() { char sign = '+'; DateTime time = ToDateTime(); #if SILVERLIGHT || NETFX_CORE long offset = time.Ticks - time.ToUniversalTime().Ticks; if (offset < 0) { sign = '-'; offset = -offset; } int hours = (int)(offset / TimeSpan.TicksPerHour); int minutes = (int)(offset / TimeSpan.TicksPerMinute) % 60; #else // Note: GetUtcOffset incorporates Daylight Savings offset TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(time); if (offset.CompareTo(TimeSpan.Zero) < 0) { sign = '-'; offset = offset.Duration(); } int hours = offset.Hours; int minutes = offset.Minutes; #endif return "GMT" + sign + Convert(hours) + ":" + Convert(minutes); } private static string Convert( int time) { if (time < 10) { return "0" + time; } return time.ToString(); } public DateTime ToDateTime() { string formatStr; string d = time; bool makeUniversal = false; if (d.EndsWith("Z")) { if (HasFractionalSeconds) { int fCount = d.Length - d.IndexOf('.') - 2; formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"\Z"; } else { formatStr = @"yyyyMMddHHmmss\Z"; } } else if (time.IndexOf('-') > 0 || time.IndexOf('+') > 0) { d = GetTime(); makeUniversal = true; if (HasFractionalSeconds) { int fCount = d.IndexOf("GMT") - 1 - d.IndexOf('.'); formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"'GMT'zzz"; } else { formatStr = @"yyyyMMddHHmmss'GMT'zzz"; } } else { if (HasFractionalSeconds) { int fCount = d.Length - 1 - d.IndexOf('.'); formatStr = @"yyyyMMddHHmmss." + FString(fCount); } else { formatStr = @"yyyyMMddHHmmss"; } // TODO? // dateF.setTimeZone(new SimpleTimeZone(0, TimeZone.getDefault().getID())); } return ParseDateString(d, formatStr, makeUniversal); } private string FString( int count) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < count; ++i) { sb.Append('f'); } return sb.ToString(); } private DateTime ParseDateString( string dateStr, string formatStr, bool makeUniversal) { DateTime dt = DateTime.ParseExact( dateStr, formatStr, DateTimeFormatInfo.InvariantInfo); return makeUniversal ? dt.ToUniversalTime() : dt; } private bool HasFractionalSeconds { get { return time.IndexOf('.') == 14; } } private byte[] GetOctets() { return Strings.ToAsciiByteArray(time); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.GeneralizedTime, GetOctets()); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerGeneralizedTime other = asn1Object as DerGeneralizedTime; if (other == null) return false; return this.time.Equals(other.time); } protected override int Asn1GetHashCode() { return time.GetHashCode(); } } }
// Copyright (c) 2015, Ben Hopkins (kode80) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using UnityEngine; using System.Collections; [ExecuteInEditMode] [RequireComponent(typeof(Camera))] public class SSR : MonoBehaviour { [Header("Downsample:")] [Range( 0.0f, 8.0f)] public int backfaceDepthDownsample = 0; [Range( 0.0f, 8.0f)] public int ssrDownsample = 0; [Range( 0.0f, 8.0f)] public int blurDownsample = 0; [Header("Raycast:")] [Range( 1.0f, 300.0f)] public int iterations = 20; [Range( 0.0f, 32.0f)] public int binarySearchIterations; [Range( 1.0f, 64.0f)] public int pixelStride = 1; public float pixelStrideZCutoff = 100.0f; public float pixelZSizeOffset = 0.1f; public float maxRayDistance = 10.0f; [Header("Reflection Fading:")] [Range( 0.0f, 1.0f)] public float screenEdgeFadeStart = 0.75f; [Range( 0.0f, 1.0f)] public float eyeFadeStart = 0.0f; [Range( 0.0f, 1.0f)] public float eyeFadeEnd = 1.0f; [Header("Roughness:")] [Range( 0.0f, 16.0f)] public int maxBlurRadius = 8; [Header("Blur Quality:")] [Range( 2.0f, 4.0f)] public int BlurQuality = 2; private Shader _backfaceDepthShader; private Material _ssrMaterial; private Material _blurMaterial; private Material _combinerMaterial; private RenderTexture _backFaceDepthTexture; private Camera _camera; private Camera _backFaceCamera; void OnEnable() { CreateMaterialsIfNeeded(); _camera.depthTextureMode |= DepthTextureMode.Depth; } void OnDisable() { DestroyMaterials(); if( _backFaceCamera) { DestroyImmediate( _backFaceCamera.gameObject); _backFaceCamera = null; } } void Reset() { _camera = GetComponent<Camera>(); } void Start () { CreateMaterialsIfNeeded(); } void Awake() { _camera = GetComponent<Camera>(); } void OnPreCull() { int downsampleBackFaceDepth = backfaceDepthDownsample + 1; int width = _camera.pixelWidth / downsampleBackFaceDepth; int height = _camera.pixelHeight / downsampleBackFaceDepth; _backFaceDepthTexture = RenderTexture.GetTemporary( width, height, 16, RenderTextureFormat.RFloat); if( _backFaceCamera == null) { GameObject cameraGameObject = new GameObject( "BackFaceDepthCamera"); cameraGameObject.hideFlags = HideFlags.HideAndDontSave; _backFaceCamera = cameraGameObject.AddComponent<Camera>(); } _backFaceCamera.CopyFrom( _camera); _backFaceCamera.renderingPath = RenderingPath.Forward; _backFaceCamera.enabled = false; _backFaceCamera.SetReplacementShader( Shader.Find( "kode80/BackFaceDepth"), null); _backFaceCamera.backgroundColor = new Color( 1.0f, 1.0f, 1.0f, 1.0f); _backFaceCamera.clearFlags = CameraClearFlags.SolidColor; //_backFaceCamera.cullingMask = LayerMask.GetMask( "Everything"); _backFaceCamera.targetTexture = _backFaceDepthTexture; _backFaceCamera.Render(); } [ImageEffectOpaque] void OnRenderImage( RenderTexture source, RenderTexture destination) { CreateMaterialsIfNeeded(); UpdateMaterialsPublicProperties(); int downsampleSSR = ssrDownsample + 1; int dsSSRWidth = source.width / downsampleSSR; int dsSSRHeight = source.height / downsampleSSR; bool debugDepth = false; if( debugDepth) { Graphics.Blit( _backFaceDepthTexture, destination); RenderTexture.ReleaseTemporary( _backFaceDepthTexture); return; } FilterMode filterMode = FilterMode.Trilinear; RenderTexture rtSSR; if( _camera.hdr) { rtSSR = RenderTexture.GetTemporary( dsSSRWidth, dsSSRHeight, 0, RenderTextureFormat.DefaultHDR); } else { rtSSR = RenderTexture.GetTemporary( dsSSRWidth, dsSSRHeight, 0, RenderTextureFormat.Default); } rtSSR.filterMode = filterMode; if( _backFaceDepthTexture) { _ssrMaterial.SetTexture( "_BackFaceDepthTex", _backFaceDepthTexture); } Graphics.Blit( source, rtSSR, _ssrMaterial); if( maxBlurRadius > 0) { int downsampleBlur = blurDownsample + 1; int dsBlurWidth = source.width / downsampleBlur; int dsBlurHeight = source.height / downsampleBlur; RenderTexture rtBlurX = null; if( _camera.hdr) { rtBlurX = RenderTexture.GetTemporary( dsBlurWidth, dsBlurHeight, 0, RenderTextureFormat.DefaultHDR); } else { rtBlurX = RenderTexture.GetTemporary( dsBlurWidth, dsBlurHeight, 0, RenderTextureFormat.Default); } rtBlurX.filterMode = filterMode; _blurMaterial.SetVector( "_TexelOffsetScale", new Vector4 ((float)maxBlurRadius / source.width, 0,0,0)); Graphics.Blit( rtSSR, rtBlurX, _blurMaterial); RenderTexture rtBlurY; if( _camera.hdr) { rtBlurY = RenderTexture.GetTemporary( dsBlurWidth, dsBlurHeight, 0, RenderTextureFormat.DefaultHDR); } else { rtBlurY = RenderTexture.GetTemporary( dsBlurWidth, dsBlurHeight, 0, RenderTextureFormat.Default); } rtBlurY.filterMode = filterMode; _blurMaterial.SetVector( "_TexelOffsetScale", new Vector4( 0, (float)maxBlurRadius/source.height, 0,0)); Graphics.Blit( rtBlurX, rtBlurY, _blurMaterial); RenderTexture.ReleaseTemporary( rtBlurX); RenderTexture.ReleaseTemporary( rtSSR); rtSSR = rtBlurY; } _combinerMaterial.SetTexture( "_BlurTex", rtSSR); Graphics.Blit( source, destination, _combinerMaterial); RenderTexture.ReleaseTemporary( rtSSR); RenderTexture.ReleaseTemporary( _backFaceDepthTexture); } private void CreateMaterialsIfNeeded() { if( _ssrMaterial == null) { _ssrMaterial = new Material( Shader.Find( "kode80/SSR")); _ssrMaterial.hideFlags = HideFlags.HideAndDontSave; } if( _blurMaterial == null) { _blurMaterial = new Material( Shader.Find( "kode80/BilateralBlur")); _blurMaterial.hideFlags = HideFlags.HideAndDontSave; } if( _combinerMaterial == null) { _combinerMaterial = new Material( Shader.Find( "kode80/SSRBlurCombiner")); _combinerMaterial.hideFlags = HideFlags.HideAndDontSave; } } private void DestroyMaterials() { DestroyImmediate( _ssrMaterial); _ssrMaterial = null; DestroyImmediate( _blurMaterial); _blurMaterial = null; DestroyImmediate( _combinerMaterial); _combinerMaterial = null; } private void UpdateMaterialsPublicProperties() { if( _ssrMaterial) { _ssrMaterial.SetFloat( "_PixelStride", pixelStride); _ssrMaterial.SetFloat( "_PixelStrideZCuttoff", pixelStrideZCutoff); _ssrMaterial.SetFloat( "_PixelZSize", pixelZSizeOffset); _ssrMaterial.SetFloat( "_Iterations", iterations); _ssrMaterial.SetFloat( "_BinarySearchIterations", binarySearchIterations); _ssrMaterial.SetFloat( "_MaxRayDistance", maxRayDistance); _blurMaterial.SetFloat( "_BlurQuality", BlurQuality); _ssrMaterial.SetFloat( "_ScreenEdgeFadeStart", screenEdgeFadeStart); _ssrMaterial.SetFloat( "_EyeFadeStart", eyeFadeStart); _ssrMaterial.SetFloat( "_EyeFadeEnd", eyeFadeEnd); int downsampleSSR = ssrDownsample + 1; int width = _camera.pixelWidth / downsampleSSR; int height = _camera.pixelHeight / downsampleSSR; Matrix4x4 trs = Matrix4x4.TRS( new Vector3( 0.5f, 0.5f, 0.0f), Quaternion.identity, new Vector3( 0.5f, 0.5f, 1.0f)); Matrix4x4 scrScale = Matrix4x4.Scale( new Vector3( width, height, 1.0f)); Matrix4x4 projection = _camera.projectionMatrix; Matrix4x4 m = scrScale * trs * projection; _ssrMaterial.SetVector( "_RenderBufferSize", new Vector4( width, height, 0.0f, 0.0f)); _ssrMaterial.SetVector( "_OneDividedByRenderBufferSize", new Vector4( 1.0f / width, 1.0f / height, 0.0f, 0.0f)); _ssrMaterial.SetMatrix( "_CameraProjectionMatrix", m); _ssrMaterial.SetMatrix( "_CameraInverseProjectionMatrix", projection.inverse); _ssrMaterial.SetMatrix( "_NormalMatrix", _camera.worldToCameraMatrix); } if( _blurMaterial) { _blurMaterial.SetFloat( "_DepthBias", 0.305f); _blurMaterial.SetFloat( "_NormalBias", 0.29f); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace STEM_Db.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Runtime.InteropServices; namespace LuaInterface { #pragma warning disable 414 public class MonoPInvokeCallbackAttribute : System.Attribute { private Type type; public MonoPInvokeCallbackAttribute(Type t) { type = t; } } #pragma warning restore 414 public enum LuaTypes : int { LUA_TNONE = -1, LUA_TNIL = 0, LUA_TBOOLEAN = 1, LUA_TLIGHTUSERDATA = 2, LUA_TNUMBER = 3, LUA_TSTRING = 4, LUA_TTABLE = 5, LUA_TFUNCTION = 6, LUA_TUSERDATA = 7, LUA_TTHREAD = 8, } public enum LuaGCOptions { LUA_GCSTOP = 0, LUA_GCRESTART = 1, LUA_GCCOLLECT = 2, LUA_GCCOUNT = 3, LUA_GCCOUNTB = 4, LUA_GCSTEP = 5, LUA_GCSETPAUSE = 6, LUA_GCSETSTEPMUL = 7, } public enum LuaThreadStatus : int { LUA_YIELD = 1, LUA_ERRRUN = 2, LUA_ERRSYNTAX = 3, LUA_ERRMEM = 4, LUA_ERRERR = 5, } public sealed class LuaIndexes { #if LUA_OLD // for lua5.1 or luajit public static int LUA_REGISTRYINDEX = -10000; public static int LUA_GLOBALSINDEX = -10002; #else // for lua5.3 public static int LUA_REGISTRYINDEX = -1000000 - 1000; #endif } [StructLayout(LayoutKind.Sequential)] public struct ReaderInfo { public String chunkData; public bool finished; } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int LuaCSFunction(IntPtr luaState); #else public delegate int LuaCSFunction(IntPtr luaState); #endif public delegate string LuaChunkReader(IntPtr luaState, ref ReaderInfo data, ref uint size); public delegate int LuaFunctionCallback(IntPtr luaState); public class LuaDLL { public static int LUA_MULTRET = -1; #if UNITY_IPHONE && !UNITY_EDITOR const string LUADLL = "__Internal"; #else const string LUADLL = "slua"; #endif #if UNITY_ANDROID && !UNITY_EDITOR [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void freeObj(IntPtr data); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void getAsset(string fileName, out IntPtr data, out int size); #endif [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_openextlibs(IntPtr L); // Thread Funcs [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tothread(IntPtr L, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_xmove(IntPtr from, IntPtr to, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_newthread(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_status(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pushthread(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gc(IntPtr luaState, LuaGCOptions what, int data); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_typename(IntPtr luaState, int type); public static string lua_typenamestr(IntPtr luaState, LuaTypes type) { IntPtr p = lua_typename(luaState, (int)type); return Marshal.PtrToStringAnsi(p); } public static string luaL_typename(IntPtr luaState, int stackPos) { return LuaDLL.lua_typenamestr(luaState, LuaDLL.lua_type(luaState, stackPos)); } public static bool lua_isfunction(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TFUNCTION; } public static bool lua_islightuserdata(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TLIGHTUSERDATA; } public static bool lua_istable(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TTABLE; } public static bool lua_isthread(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TTHREAD; } [Obsolete] public static void luaL_error(IntPtr luaState, string message) { //LuaDLL.lua_pushstring(luaState, message); //LuaDLL.lua_error(luaState); } [Obsolete] public static void luaL_error(IntPtr luaState, string fmt, params object[] args) { //string str = string.Format(fmt, args); //luaL_error(luaState, str); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern string luaL_gsub(IntPtr luaState, string str, string pattern, string replacement); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_isuserdata(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rawequal(IntPtr luaState, int stackPos1, int stackPos2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setfield(IntPtr luaState, int stackPos, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_callmeta(IntPtr luaState, int stackPos, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_newstate(); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_close(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_openlibs(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadstring(IntPtr luaState, string chunk); public static int luaL_dostring(IntPtr luaState, string chunk) { int result = LuaDLL.luaL_loadstring(luaState, chunk); if (result != 0) return result; return LuaDLL.lua_pcall(luaState, 0, -1, 0); } public static int lua_dostring(IntPtr luaState, string chunk) { return LuaDLL.luaL_dostring(luaState, chunk); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_createtable(IntPtr luaState, int narr, int nrec); public static void lua_newtable(IntPtr luaState) { LuaDLL.lua_createtable(luaState, 0, 0); } #if LUA_OLD [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_resume(IntPtr L, int narg); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_lessthan(IntPtr luaState, int stackPos1, int stackPos2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfenv(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_yield(IntPtr L, int nresults); public static void lua_getglobal(IntPtr luaState, string name) { LuaDLL.lua_pushstring(luaState, name); LuaDLL.lua_gettable(luaState, LuaIndexes.LUA_GLOBALSINDEX); } public static void lua_setglobal(IntPtr luaState, string name) { LuaDLL.lua_pushstring(luaState, name); LuaDLL.lua_insert(luaState, -2); LuaDLL.lua_settable(luaState, LuaIndexes.LUA_GLOBALSINDEX); } public static void lua_pushglobaltable(IntPtr l) { LuaDLL.lua_pushvalue(l, LuaIndexes.LUA_GLOBALSINDEX); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_insert(IntPtr luaState, int newTop); public static int lua_rawlen(IntPtr luaState, int stackPos) { return LuaDLLWrapper.luaS_objlen(luaState, stackPos); } public static int lua_strlen(IntPtr luaState, int stackPos) { return lua_rawlen(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_call(IntPtr luaState, int nArgs, int nResults); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumber(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tointeger(IntPtr luaState, int index); public static int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name) { return LuaDLLWrapper.luaLS_loadbuffer(luaState, buff, size, name); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_remove(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr luaState, int tableIndex, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr luaState, IntPtr i); public static void lua_pushinteger(IntPtr luaState, int i) { lua_pushinteger(luaState, (IntPtr)i); } public static int luaL_checkinteger(IntPtr luaState, int stackPos) { luaL_checktype(luaState, stackPos, LuaTypes.LUA_TNUMBER); return lua_tointeger(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_replace(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_setfenv(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_equal(IntPtr luaState, int index1, int index2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadfile(IntPtr luaState, string filename); #else [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getglobal(IntPtr luaState, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setglobal(IntPtr luaState, string name); public static void lua_insert(IntPtr luaState, int newTop) { lua_rotate(luaState, newTop, 1); } public static void lua_pushglobaltable(IntPtr l) { lua_rawgeti(l, LuaIndexes.LUA_REGISTRYINDEX, 2); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rotate(IntPtr luaState, int index, int n); public static int lua_rawlen(IntPtr luaState, int stackPos) { return LuaDLLWrapper.luaS_rawlen(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadbufferx(IntPtr luaState, byte[] buff, int size, string name, IntPtr x); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_callk(IntPtr luaState, int nArgs, int nResults, int ctx, IntPtr k); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcallk(IntPtr luaState, int nArgs, int nResults, int errfunc, int ctx, IntPtr k); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc); public static int lua_call(IntPtr luaState, int nArgs, int nResults) { return lua_callk(luaState, nArgs, nResults, 0, IntPtr.Zero); } public static int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc) { return luaS_pcall(luaState, nArgs, nResults, errfunc); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumberx(IntPtr luaState, int index, IntPtr x); public static double lua_tonumber(IntPtr luaState, int index) { return lua_tonumberx(luaState, index, IntPtr.Zero); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern Int64 lua_tointegerx(IntPtr luaState, int index, IntPtr x); public static int lua_tointeger(IntPtr luaState, int index) { return (int)lua_tointegerx(luaState, index, IntPtr.Zero); } public static int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name) { return luaL_loadbufferx(luaState, buff, size, name, IntPtr.Zero); } public static void lua_remove(IntPtr l, int idx) { lua_rotate(l, (idx), -1); lua_pop(l, 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, Int64 index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr luaState, int tableIndex, Int64 index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr luaState, Int64 i); public static Int64 luaL_checkinteger(IntPtr luaState, int stackPos) { luaL_checktype(luaState, stackPos, LuaTypes.LUA_TNUMBER); return lua_tointegerx(luaState, stackPos, IntPtr.Zero); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_yield(IntPtr luaState, int nrets); public static int lua_yield(IntPtr luaState, int nrets) { return luaS_yield(luaState, nrets); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_resume(IntPtr L, IntPtr from, int narg); public static void lua_replace(IntPtr luaState, int index) { lua_copy(luaState, -1, (index)); lua_pop(luaState, 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_copy(IntPtr luaState, int from, int toidx); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_isinteger(IntPtr luaState, int p); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_compare(IntPtr luaState, int index1, int index2, int op); public static int lua_equal(IntPtr luaState, int index1, int index2) { return lua_compare(luaState, index1, index2, 0); } #endif [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settop(IntPtr luaState, int newTop); public static void lua_pop(IntPtr luaState, int amount) { LuaDLL.lua_settop(luaState, -(amount) - 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_gettable(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawget(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settable(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawset(IntPtr luaState, int index); #if LUA_OLD [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_setmetatable(IntPtr luaState, int objIndex); #else [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setmetatable(IntPtr luaState, int objIndex); #endif [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_getmetatable(IntPtr luaState, int objIndex); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushvalue(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gettop(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern LuaTypes lua_type(IntPtr luaState, int index); public static bool lua_isnil(IntPtr luaState, int index) { return (LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TNIL); } public static bool lua_isnumber(IntPtr luaState, int index) { return LuaDLLWrapper.lua_isnumber(luaState, index) > 0; } public static bool lua_isboolean(IntPtr luaState, int index) { return LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TBOOLEAN; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_ref(IntPtr luaState, int registryIndex); public static void lua_getref(IntPtr luaState, int reference) { LuaDLL.lua_rawgeti(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_unref(IntPtr luaState, int registryIndex, int reference); public static void lua_unref(IntPtr luaState, int reference) { LuaDLL.luaL_unref(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference); } public static bool lua_isstring(IntPtr luaState, int index) { return LuaDLLWrapper.lua_isstring(luaState, index) > 0; } public static bool lua_iscfunction(IntPtr luaState, int index) { return LuaDLLWrapper.lua_iscfunction(luaState, index) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnil(IntPtr luaState); public static void luaL_checktype(IntPtr luaState, int p, LuaTypes t) { LuaTypes ct = LuaDLL.lua_type(luaState, p); if (ct != t) { throw new Exception(string.Format("arg {0} expect {1}, got {2}", p, lua_typenamestr(luaState, t), lua_typenamestr(luaState, ct))); } } public static void lua_pushcfunction(IntPtr luaState, LuaCSFunction function) { IntPtr fn = Marshal.GetFunctionPointerForDelegate(function); lua_pushcclosure(luaState, fn, 0); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_tocfunction(IntPtr luaState, int index); public static bool lua_toboolean(IntPtr luaState, int index) { return LuaDLLWrapper.lua_toboolean(luaState, index) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaS_tolstring32(IntPtr luaState, int index, out int strLen); public static string lua_tostring(IntPtr luaState, int index) { int strlen; IntPtr str = luaS_tolstring32(luaState, index, out strlen); // fix il2cpp 64 bit if (str != IntPtr.Zero) { return Marshal.PtrToStringAnsi(str, strlen); } return null; } public static byte[] lua_tobytes(IntPtr luaState, int index) { int strlen; IntPtr str = luaS_tolstring32(luaState, index, out strlen); // fix il2cpp 64 bit if (str != IntPtr.Zero) { byte[] bytes = new byte[strlen]; Marshal.Copy(str, bytes,0,strlen); return bytes; } return null; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_atpanic(IntPtr luaState, LuaCSFunction panicf); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnumber(IntPtr luaState, double number); public static void lua_pushboolean(IntPtr luaState, bool value) { LuaDLLWrapper.lua_pushboolean(luaState, value ? 1 : 0); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushstring(IntPtr luaState, string str); public static void lua_pushlstring(IntPtr luaState, byte[] str, int size) { LuaDLLWrapper.luaS_pushlstring(luaState, str, size); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_newmetatable(IntPtr luaState, string meta); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfield(IntPtr luaState, int stackPos, string meta); public static void luaL_getmetatable(IntPtr luaState, string meta) { LuaDLL.lua_getfield(luaState, LuaIndexes.LUA_REGISTRYINDEX, meta); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_checkudata(IntPtr luaState, int stackPos, string meta); public static bool luaL_getmetafield(IntPtr luaState, int stackPos, string field) { return LuaDLLWrapper.luaL_getmetafield(luaState, stackPos, field) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_load(IntPtr luaState, LuaChunkReader chunkReader, ref ReaderInfo data, string chunkName); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_error(IntPtr luaState); public static bool lua_checkstack(IntPtr luaState, int extra) { return LuaDLLWrapper.lua_checkstack(luaState, extra) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_next(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushlightuserdata(IntPtr luaState, IntPtr udata); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_where(IntPtr luaState, int level); public static double luaL_checknumber(IntPtr luaState, int stackPos) { luaL_checktype(luaState, stackPos, LuaTypes.LUA_TNUMBER); return lua_tonumber(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_concat(IntPtr luaState, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_newuserdata(IntPtr luaState, int val); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_rawnetobj(IntPtr luaState, int obj); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_touserdata(IntPtr luaState, int index); public static int lua_absindex(IntPtr luaState, int index) { return index > 0 ? index : lua_gettop(luaState) + index + 1; } public static int lua_upvalueindex(int i) { #if LUA_OLD return LuaIndexes.LUA_GLOBALSINDEX - i; #else return LuaIndexes.LUA_REGISTRYINDEX - i; #endif } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushcclosure(IntPtr l, IntPtr f, int nup); public static void lua_pushcclosure(IntPtr l, LuaCSFunction f, int nup) { IntPtr fn = Marshal.GetFunctionPointerForDelegate(f); lua_pushcclosure(l, fn, nup); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkVector2(IntPtr l, int p, out float x, out float y); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkVector3(IntPtr l, int p, out float x, out float y, out float z); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkVector4(IntPtr l, int p, out float x, out float y, out float z, out float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkQuaternion(IntPtr l, int p, out float x, out float y, out float z, out float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkColor(IntPtr l, int p, out float x, out float y, out float z, out float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushVector2(IntPtr l, float x, float y); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushVector3(IntPtr l, float x, float y, float z); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushVector4(IntPtr l, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushQuaternion(IntPtr l, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushColor(IntPtr l, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_setDataVec(IntPtr l, int p, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkluatype(IntPtr l, int p, string t); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_pushobject(IntPtr l, int index, string t, bool gco, int cref); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_getcacheud(IntPtr l, int index, int cref); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_subclassof(IntPtr l, int index, string t); } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Razor.Editor; using Microsoft.AspNet.Razor.Generator; using Microsoft.AspNet.Razor.Parser; using Microsoft.AspNet.Razor.Parser.SyntaxTree; using Microsoft.AspNet.Razor.Text; using Microsoft.AspNet.Razor.Tokenizer; using Microsoft.AspNet.Razor.Tokenizer.Symbols; namespace Microsoft.AspNet.Razor.Test.Framework { public static class SpanFactoryExtensions { public static UnclassifiedCodeSpanConstructor EmptyCSharp(this SpanFactory self) { return new UnclassifiedCodeSpanConstructor( self.Span(SpanKind.Code, new CSharpSymbol(self.LocationTracker.CurrentLocation, String.Empty, CSharpSymbolType.Unknown))); } public static SpanConstructor EmptyHtml(this SpanFactory self) { return self.Span(SpanKind.Markup, new HtmlSymbol(self.LocationTracker.CurrentLocation, String.Empty, HtmlSymbolType.Unknown)) .With(new MarkupCodeGenerator()); } public static UnclassifiedCodeSpanConstructor Code(this SpanFactory self, string content) { return new UnclassifiedCodeSpanConstructor( self.Span(SpanKind.Code, content, markup: false)); } public static SpanConstructor CodeTransition(this SpanFactory self) { return self.Span(SpanKind.Transition, SyntaxConstants.TransitionString, markup: false).Accepts(AcceptedCharacters.None); } public static SpanConstructor CodeTransition(this SpanFactory self, string content) { return self.Span(SpanKind.Transition, content, markup: false).Accepts(AcceptedCharacters.None); } public static SpanConstructor CodeTransition(this SpanFactory self, CSharpSymbolType type) { return self.Span(SpanKind.Transition, SyntaxConstants.TransitionString, type).Accepts(AcceptedCharacters.None); } public static SpanConstructor CodeTransition(this SpanFactory self, string content, CSharpSymbolType type) { return self.Span(SpanKind.Transition, content, type).Accepts(AcceptedCharacters.None); } public static SpanConstructor MarkupTransition(this SpanFactory self) { return self.Span(SpanKind.Transition, SyntaxConstants.TransitionString, markup: true).Accepts(AcceptedCharacters.None); } public static SpanConstructor MarkupTransition(this SpanFactory self, string content) { return self.Span(SpanKind.Transition, content, markup: true).Accepts(AcceptedCharacters.None); } public static SpanConstructor MarkupTransition(this SpanFactory self, HtmlSymbolType type) { return self.Span(SpanKind.Transition, SyntaxConstants.TransitionString, type).Accepts(AcceptedCharacters.None); } public static SpanConstructor MarkupTransition(this SpanFactory self, string content, HtmlSymbolType type) { return self.Span(SpanKind.Transition, content, type).Accepts(AcceptedCharacters.None); } public static SpanConstructor MetaCode(this SpanFactory self, string content) { return self.Span(SpanKind.MetaCode, content, markup: false); } public static SpanConstructor MetaCode(this SpanFactory self, string content, CSharpSymbolType type) { return self.Span(SpanKind.MetaCode, content, type); } public static SpanConstructor MetaMarkup(this SpanFactory self, string content) { return self.Span(SpanKind.MetaCode, content, markup: true); } public static SpanConstructor MetaMarkup(this SpanFactory self, string content, HtmlSymbolType type) { return self.Span(SpanKind.MetaCode, content, type); } public static SpanConstructor Comment(this SpanFactory self, string content, CSharpSymbolType type) { return self.Span(SpanKind.Comment, content, type); } public static SpanConstructor Comment(this SpanFactory self, string content, HtmlSymbolType type) { return self.Span(SpanKind.Comment, content, type); } public static SpanConstructor Markup(this SpanFactory self, string content) { return self.Span(SpanKind.Markup, content, markup: true).With(new MarkupCodeGenerator()); } public static SpanConstructor Markup(this SpanFactory self, params string[] content) { return self.Span(SpanKind.Markup, content, markup: true).With(new MarkupCodeGenerator()); } public static SourceLocation GetLocationAndAdvance(this SourceLocationTracker self, string content) { SourceLocation ret = self.CurrentLocation; self.UpdateLocation(content); return ret; } } public class SpanFactory { public Func<ITextDocument, ITokenizer> MarkupTokenizerFactory { get; set; } public Func<ITextDocument, ITokenizer> CodeTokenizerFactory { get; set; } public SourceLocationTracker LocationTracker { get; private set; } public static SpanFactory CreateCsHtml() { return new SpanFactory() { MarkupTokenizerFactory = doc => new HtmlTokenizer(doc), CodeTokenizerFactory = doc => new CSharpTokenizer(doc) }; } public SpanFactory() { LocationTracker = new SourceLocationTracker(); } public SpanConstructor Span(SpanKind kind, string content, CSharpSymbolType type) { return CreateSymbolSpan(kind, content, st => new CSharpSymbol(st, content, type)); } public SpanConstructor Span(SpanKind kind, string content, HtmlSymbolType type) { return CreateSymbolSpan(kind, content, st => new HtmlSymbol(st, content, type)); } public SpanConstructor Span(SpanKind kind, string content, bool markup) { return new SpanConstructor(kind, Tokenize(new[] { content }, markup)); } public SpanConstructor Span(SpanKind kind, string[] content, bool markup) { return new SpanConstructor(kind, Tokenize(content, markup)); } public SpanConstructor Span(SpanKind kind, params ISymbol[] symbols) { return new SpanConstructor(kind, symbols); } private SpanConstructor CreateSymbolSpan(SpanKind kind, string content, Func<SourceLocation, ISymbol> ctor) { SourceLocation start = LocationTracker.CurrentLocation; LocationTracker.UpdateLocation(content); return new SpanConstructor(kind, new[] { ctor(start) }); } public void Reset() { LocationTracker.CurrentLocation = SourceLocation.Zero; } private IEnumerable<ISymbol> Tokenize(IEnumerable<string> contentFragments, bool markup) { return contentFragments.SelectMany(fragment => Tokenize(fragment, markup)); } private IEnumerable<ISymbol> Tokenize(string content, bool markup) { ITokenizer tok = MakeTokenizer(markup, new SeekableTextReader(content)); ISymbol sym; ISymbol last = null; while ((sym = tok.NextSymbol()) != null) { OffsetStart(sym, LocationTracker.CurrentLocation); last = sym; yield return sym; } LocationTracker.UpdateLocation(content); } private ITokenizer MakeTokenizer(bool markup, SeekableTextReader seekableTextReader) { if (markup) { return MarkupTokenizerFactory(seekableTextReader); } else { return CodeTokenizerFactory(seekableTextReader); } } private void OffsetStart(ISymbol sym, SourceLocation sourceLocation) { sym.OffsetStart(sourceLocation); } } public static class SpanConstructorExtensions { public static SpanConstructor Accepts(this SpanConstructor self, AcceptedCharacters accepted) { return self.With(eh => eh.AcceptedCharacters = accepted); } public static SpanConstructor AutoCompleteWith(this SpanConstructor self, string autoCompleteString) { return AutoCompleteWith(self, autoCompleteString, atEndOfSpan: false); } public static SpanConstructor AutoCompleteWith(this SpanConstructor self, string autoCompleteString, bool atEndOfSpan) { return self.With(new AutoCompleteEditHandler(SpanConstructor.TestTokenizer) { AutoCompleteString = autoCompleteString, AutoCompleteAtEndOfSpan = atEndOfSpan }); } public static SpanConstructor WithEditorHints(this SpanConstructor self, EditorHints hints) { return self.With(eh => eh.EditorHints = hints); } } public class UnclassifiedCodeSpanConstructor { SpanConstructor _self; public UnclassifiedCodeSpanConstructor(SpanConstructor self) { _self = self; } public SpanConstructor AsMetaCode() { _self.Builder.Kind = SpanKind.MetaCode; return _self; } public SpanConstructor AsStatement() { return _self.With(new StatementCodeGenerator()); } public SpanConstructor AsExpression() { return _self.With(new ExpressionCodeGenerator()); } public SpanConstructor AsImplicitExpression(ISet<string> keywords) { return AsImplicitExpression(keywords, acceptTrailingDot: false); } public SpanConstructor AsImplicitExpression(ISet<string> keywords, bool acceptTrailingDot) { return _self.With(new ImplicitExpressionEditHandler(SpanConstructor.TestTokenizer, keywords, acceptTrailingDot)) .With(new ExpressionCodeGenerator()); } public SpanConstructor AsFunctionsBody() { return _self.With(new TypeMemberCodeGenerator()); } public SpanConstructor AsNamespaceImport(string ns, int namespaceKeywordLength) { return _self.With(new AddImportCodeGenerator(ns, namespaceKeywordLength)); } public SpanConstructor Hidden() { return _self.With(SpanCodeGenerator.Null); } public SpanConstructor AsBaseType(string baseType) { return _self.With(new SetBaseTypeCodeGenerator(baseType)); } public SpanConstructor AsRazorDirectiveAttribute(string key, string value) { return _self.With(new RazorDirectiveAttributeCodeGenerator(key, value)); } public SpanConstructor As(ISpanCodeGenerator codeGenerator) { return _self.With(codeGenerator); } } public class SpanConstructor { public SpanBuilder Builder { get; private set; } internal static IEnumerable<ISymbol> TestTokenizer(string str) { yield return new RawTextSymbol(SourceLocation.Zero, str); } public SpanConstructor(SpanKind kind, IEnumerable<ISymbol> symbols) { Builder = new SpanBuilder(); Builder.Kind = kind; Builder.EditHandler = SpanEditHandler.CreateDefault(TestTokenizer); foreach (ISymbol sym in symbols) { Builder.Accept(sym); } } private Span Build() { return Builder.Build(); } public SpanConstructor With(ISpanCodeGenerator generator) { Builder.CodeGenerator = generator; return this; } public SpanConstructor With(SpanEditHandler handler) { Builder.EditHandler = handler; return this; } public SpanConstructor With(Action<ISpanCodeGenerator> generatorConfigurer) { generatorConfigurer(Builder.CodeGenerator); return this; } public SpanConstructor With(Action<SpanEditHandler> handlerConfigurer) { handlerConfigurer(Builder.EditHandler); return this; } public static implicit operator Span(SpanConstructor self) { return self.Build(); } public SpanConstructor Hidden() { Builder.CodeGenerator = SpanCodeGenerator.Null; return this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using System.IO; using Sandbox.Common; using Sandbox.Common.ObjectBuilders; using Sandbox.Definitions; using Sandbox.Engine; using Sandbox.Engine.Physics; using Sandbox.Engine.Multiplayer; using Sandbox.Game; using Sandbox.Game.Entities; using Sandbox.ModAPI; using Sandbox.ModAPI.Interfaces; using VRage.Common.Utils; using VRageMath; using VRage; using VRage.ObjectBuilders; using VRage.Game.Components; using VRage.ModAPI; using Sandbox.Game.EntityComponents; using VRage.Game.ObjectBuilders.Definitions; using VRage.Game; namespace Cython.PowerTransmission { [MySessionComponentDescriptor(MyUpdateOrder.BeforeSimulation | MyUpdateOrder.AfterSimulation | MyUpdateOrder.Simulation)] public class TransmitterLogic: MySessionComponentBase { MyObjectBuilder_SessionComponent m_sessionComponent; bool m_init = false; readonly string m_saveFileName = "PowerTransmitters.sav"; public static PTSaveFile transmittersSaveFile = new PTSaveFile(); List<long> m_dictionaryCopy = new List<long>(); public override MyObjectBuilder_SessionComponent GetObjectBuilder () { return m_sessionComponent; } public override void UpdateBeforeSimulation () { if(!m_init) init(); } public override void UpdateAfterSimulation () { m_dictionaryCopy.Clear (); foreach (var grid in TransmissionManager.totalPowerPerGrid) { m_dictionaryCopy.Add (grid.Key); } foreach (var grid in m_dictionaryCopy) { TransmissionManager.totalPowerPerGrid [grid] = 0f; } base.UpdateAfterSimulation (); } protected override void UnloadData () { if(m_init) { MyAPIGateway.Multiplayer.UnregisterMessageHandler(5910, handleMessage); } } void init() { MyAPIGateway.Multiplayer.RegisterMessageHandler(5910, handleMessage); loadPTSaveFile(); m_init = true; } void loadPTSaveFile() { if (MyAPIGateway.Utilities.FileExistsInLocalStorage (m_saveFileName, typeof(TransmitterLogic))) { if (MyAPIGateway.Multiplayer.IsServer || !MyAPIGateway.Multiplayer.MultiplayerActive) { try { string buffer; using (TextReader file = MyAPIGateway.Utilities.ReadFileInLocalStorage (m_saveFileName, typeof(TransmitterLogic))) { buffer = file.ReadToEnd (); } TransmitterLogic.transmittersSaveFile = MyAPIGateway.Utilities.SerializeFromXML<PTSaveFile> (buffer); } catch (InvalidOperationException e) { } } } foreach(var ptInfo in TransmitterLogic.transmittersSaveFile.Transmitters) { if(MyAPIGateway.Entities.EntityExists(ptInfo.Id)) { IMyEntity transmitter = MyAPIGateway.Entities.GetEntityById(ptInfo.Id); if(ptInfo.Type.Equals("R")) { var RPT = transmitter.GameLogic.GetAs<RadialPowerTransmitter>(); RPT.m_sender = ptInfo.Sender; RPT.m_info.sender = ptInfo.Sender; RPT.m_channel = ptInfo.ChannelTarget; RPT.m_info.channel = ptInfo.ChannelTarget; RPT.m_transmittedPower = ptInfo.Power; } else { var OPT = transmitter.GameLogic.GetAs<OpticalPowerTransmitter>(); OPT.m_sender = ptInfo.Sender; OPT.m_info.sender = ptInfo.Sender; OPT.m_id = ptInfo.ChannelTarget; OPT.m_targetId = ptInfo.ChannelTarget; OPT.m_info.id = ptInfo.ChannelTarget; OPT.m_transmittedPower = ptInfo.Power; } } } } void savePTSaveFile() { if(MyAPIGateway.Multiplayer != null) { if (MyAPIGateway.Multiplayer.IsServer || !MyAPIGateway.Multiplayer.MultiplayerActive) { try { using (TextWriter saveFile = MyAPIGateway.Utilities.WriteFileInLocalStorage (m_saveFileName, typeof(TransmitterLogic))) { saveFile.Write(MyAPIGateway.Utilities.SerializeToXML<PTSaveFile> (TransmitterLogic.transmittersSaveFile)); } } catch (InvalidOperationException e) { } } } } public override void SaveData () { savePTSaveFile(); } void handleMessage(byte[] message) { int id = BitConverter.ToInt32(message, 0); // rpt if(id == 0) { long entityId = BitConverter.ToInt64(message, 4); bool value = BitConverter.ToBoolean(message, 12); IMyEntity refinery; if(MyAPIGateway.Entities.TryGetEntityById(entityId, out refinery)) { var RPT = refinery.GameLogic.GetAs<RadialPowerTransmitter>(); RPT.m_sender = value; RPT.m_info.sender = value; } } else if(id == 1) { long entityId = BitConverter.ToInt64(message, 4); uint value = BitConverter.ToUInt32(message, 12); IMyEntity rptEntity; if(MyAPIGateway.Entities.TryGetEntityById(entityId, out rptEntity)) { var RPT = rptEntity.GameLogic.GetAs<RadialPowerTransmitter>(); RPT.m_channel = value; RPT.m_info.channel = value; } } else if(id == 2) { long entityId = BitConverter.ToInt64(message, 4); float value = BitConverter.ToSingle(message, 12); IMyEntity rptEntity; if(MyAPIGateway.Entities.TryGetEntityById(entityId, out rptEntity)) { var RPT = rptEntity.GameLogic.GetAs<RadialPowerTransmitter>(); RPT.m_transmittedPower = value; } } // opt else if(id == 3) { long entityId = BitConverter.ToInt64(message, 4); bool value = BitConverter.ToBoolean(message, 12); IMyEntity refinery; if(MyAPIGateway.Entities.TryGetEntityById(entityId, out refinery)) { var OPT = refinery.GameLogic.GetAs<OpticalPowerTransmitter>(); OPT.m_sender = value; OPT.m_info.sender = value; } } else if(id == 4) { long entityId = BitConverter.ToInt64(message, 4); uint value = BitConverter.ToUInt32(message, 12); IMyEntity rptEntity; if(MyAPIGateway.Entities.TryGetEntityById(entityId, out rptEntity)) { var OPT = rptEntity.GameLogic.GetAs<OpticalPowerTransmitter>(); if(OPT.m_sender) { OPT.m_targetId = value; } else { OPT.m_id = value; OPT.m_info.id = value; } } } else if(id == 5) { long entityId = BitConverter.ToInt64(message, 4); float value = BitConverter.ToSingle(message, 12); IMyEntity rptEntity; if(MyAPIGateway.Entities.TryGetEntityById(entityId, out rptEntity)) { var OPT = rptEntity.GameLogic.GetAs<OpticalPowerTransmitter>(); OPT.m_transmittedPower = value; } } else if(id == 10) { if(MyAPIGateway.Multiplayer.IsServer) { ulong senderId = BitConverter.ToUInt64(message, 4); long entityId = BitConverter.ToInt64(message, 12); IMyEntity rptEntity; if(MyAPIGateway.Entities.TryGetEntityById(entityId, out rptEntity)) { var RPT = rptEntity.GameLogic.GetAs<RadialPowerTransmitter>(); byte[] answer = new byte[21]; byte[] answerId = BitConverter.GetBytes(10); byte[] answerEntityId = BitConverter.GetBytes(entityId); byte[] answerChannel = BitConverter.GetBytes(RPT.m_channel); byte[] answerPower = BitConverter.GetBytes(RPT.m_transmittedPower); for(int i = 0; i < 4; i++) answer[i] = answerId[i]; for(int i = 0; i < 8; i++) answer[i] = answerEntityId[i]; answer[4] = BitConverter.GetBytes(RPT.m_sender)[0]; for(int i = 0; i < 4; i++) answer[i+13] = answerChannel[i]; for(int i = 0; i < 4; i++) answer[i+17] = answerPower[i]; MyAPIGateway.Multiplayer.SendMessageTo(5910, answer, senderId, true); } } else { long entityId = BitConverter.ToInt64(message, 4); IMyEntity rptEntity; if(MyAPIGateway.Entities.TryGetEntityById(entityId, out rptEntity)) { var RPT = rptEntity.GameLogic.GetAs<RadialPowerTransmitter>(); bool sender = BitConverter.ToBoolean(message, 12); uint channel = BitConverter.ToUInt32(message, 13); float power = BitConverter.ToSingle(message, 17); RPT.m_sender = sender; RPT.m_info.sender = sender; RPT.m_channel = channel; RPT.m_info.channel = channel; RPT.m_transmittedPower = power; } } } else if(id == 11) { if(MyAPIGateway.Multiplayer.IsServer) { ulong senderId = BitConverter.ToUInt64(message, 4); long entityId = BitConverter.ToInt64(message, 12); IMyEntity rptEntity; if(MyAPIGateway.Entities.TryGetEntityById(entityId, out rptEntity)) { var OPT = rptEntity.GameLogic.GetAs<OpticalPowerTransmitter>(); byte[] answer = new byte[25]; byte[] answerId = BitConverter.GetBytes(11); byte[] answerEntityId = BitConverter.GetBytes(entityId); byte[] answerThisId = BitConverter.GetBytes(OPT.m_id); byte[] answerTargetId = BitConverter.GetBytes(OPT.m_targetId); byte[] answerPower = BitConverter.GetBytes(OPT.m_transmittedPower); for(int i = 0; i < 4; i++) answer[i] = answerId[i]; for(int i = 0; i < 8; i++) answer[i] = answerEntityId[i]; answer[4] = BitConverter.GetBytes(OPT.m_sender)[0]; for(int i = 0; i < 4; i++) answer[i+13] = answerThisId[i]; for(int i = 0; i < 4; i++) answer[i+17] = answerTargetId[i]; for(int i = 0; i < 4; i++) answer[i+21] = answerPower[i]; MyAPIGateway.Multiplayer.SendMessageTo(5910, answer, senderId, true); } } else { long entityId = BitConverter.ToInt64(message, 4); IMyEntity rptEntity; if(MyAPIGateway.Entities.TryGetEntityById(entityId, out rptEntity)) { var OPT = rptEntity.GameLogic.GetAs<OpticalPowerTransmitter>(); bool sender = BitConverter.ToBoolean(message, 12); uint thisId = BitConverter.ToUInt32(message, 13); uint targetId = BitConverter.ToUInt32(message, 17); float power = BitConverter.ToSingle(message, 21); OPT.m_sender = sender; OPT.m_info.sender = sender; OPT.m_id = thisId; OPT.m_info.id = thisId; OPT.m_targetId = targetId; OPT.m_transmittedPower = power; } } } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Diagnostics; using OpenLiveWriter.HtmlParser.Parser.FormAgent; namespace OpenLiveWriter.BlogClient.Clients { /// <summary> /// Helper class for making REST-ful XML HTTP requests. /// </summary> public class XmlRestRequestHelper { public XmlRestRequestHelper() { } public XmlDocument Get(ref Uri uri, HttpRequestFilter filter, params string[] parameters) { WebHeaderCollection responseHeaders; return Get(ref uri, filter, out responseHeaders, parameters); } /// <summary> /// Retrieve the specified URI, using the given filter, with the supplied parameters (if any). /// The parameters parameter should be an even number of strings, where each odd element is /// a param name and each following even element is the corresponding param value. For example, /// to retrieve http://www.vox.com/atom?svc=post&id=100, you would say: /// /// Get("http://www.vox.com/atom", "svc", "post", "id", "100"); /// /// If a param value is null or empty string, that param will not be included in the final URL /// (i.e. the corresponding param name will also be dropped). /// </summary> public virtual XmlDocument Get(ref Uri uri, HttpRequestFilter filter, out WebHeaderCollection responseHeaders, params string[] parameters) { return SimpleRequest("GET", ref uri, filter, out responseHeaders, parameters); } /// <summary> /// Performs an HTTP DELETE on the URL and contains no body, returns the body as an XmlDocument if there is one /// </summary> public virtual XmlDocument Delete(Uri uri, HttpRequestFilter filter, out WebHeaderCollection responseHeaders) { return SimpleRequest("DELETE", ref uri, filter, out responseHeaders, new string[] { }); } private static XmlDocument SimpleRequest(string method, ref Uri uri, HttpRequestFilter filter, out WebHeaderCollection responseHeaders, params string[] parameters) { string absUri = UrlHelper.SafeToAbsoluteUri(uri); if (parameters.Length > 0) { FormData formData = new FormData(true, parameters); if (absUri.IndexOf('?') == -1) absUri += "?" + formData.ToString(); else absUri += "&" + formData.ToString(); } RedirectHelper.SimpleRequest simpleRequest = new RedirectHelper.SimpleRequest(method, filter); HttpWebResponse response = RedirectHelper.GetResponse(absUri, new RedirectHelper.RequestFactory(simpleRequest.Create)); try { uri = response.ResponseUri; responseHeaders = response.Headers; return ParseXmlResponse(response); } finally { if (response != null) response.Close(); } } /// <summary> /// Performs an HTTP PUT with the specified XML document as the request body. /// </summary> public XmlDocument Put(ref Uri uri, string etag, HttpRequestFilter filter, string contentType, XmlDocument doc, string encoding, bool ignoreResponse) { WebHeaderCollection responseHeaders; return Put(ref uri, etag, filter, contentType, doc, encoding, ignoreResponse, out responseHeaders); } /// <summary> /// Performs an HTTP PUT with the specified XML document as the request body. /// </summary> public XmlDocument Put(ref Uri uri, string etag, HttpRequestFilter filter, string contentType, XmlDocument doc, string encoding, bool ignoreResponse, out WebHeaderCollection responseHeaders) { return Send("PUT", ref uri, etag, filter, contentType, doc, encoding, null, ignoreResponse, out responseHeaders); } /// <summary> /// Performs an HTTP POST with the specified XML document as the request body. /// </summary> public XmlDocument Post(ref Uri uri, HttpRequestFilter filter, string contentType, XmlDocument doc, string encoding) { WebHeaderCollection responseHeaders; return Post(ref uri, filter, contentType, doc, encoding, out responseHeaders); } /// <summary> /// Performs an HTTP POST with the specified XML document as the request body. /// </summary> public XmlDocument Post(ref Uri uri, HttpRequestFilter filter, string contentType, XmlDocument doc, string encoding, out WebHeaderCollection responseHeaders) { return Send("POST", ref uri, null, filter, contentType, doc, encoding, null, false, out responseHeaders); } /// <summary> /// Performs a multipart MIME HTTP POST with the specified XML document as the request body and filename as the payload. /// </summary> public XmlDocument Post(ref Uri uri, HttpRequestFilter filter, string contentType, XmlDocument doc, string encoding, string filename, out WebHeaderCollection responseHeaders) { return Send("POST", ref uri, null, filter, contentType, doc, encoding, filename, false, out responseHeaders); } protected virtual XmlDocument MultipartSend(string method, ref Uri uri, string etag, HttpRequestFilter filter, string contentType, XmlDocument doc, string encoding, string filename, bool ignoreResponse, out WebHeaderCollection responseHeaders) { throw new NotImplementedException(); } protected virtual XmlDocument Send(string method, ref Uri uri, string etag, HttpRequestFilter filter, string contentType, XmlDocument doc, string encoding, string filename, bool ignoreResponse, out WebHeaderCollection responseHeaders) { if (!String.IsNullOrEmpty(filename)) { return MultipartSend(method, ref uri, etag, filter, contentType, doc, encoding, filename, ignoreResponse, out responseHeaders); } string absUri = UrlHelper.SafeToAbsoluteUri(uri); Debug.WriteLine("XML Request to " + absUri + ":\r\n" + doc.InnerXml); SendFactory sf = new SendFactory(etag, method, filter, contentType, doc, encoding); HttpWebResponse response = RedirectHelper.GetResponse(absUri, new RedirectHelper.RequestFactory(sf.Create)); try { responseHeaders = response.Headers; uri = response.ResponseUri; if (ignoreResponse || response.StatusCode == HttpStatusCode.NoContent) { return null; } else { XmlDocument xmlDocResponse = ParseXmlResponse(response); return xmlDocResponse; } } finally { if (response != null) response.Close(); } } private struct SendFactory { private readonly string _etag; private readonly string _method; private readonly HttpRequestFilter _filter; private readonly string _contentType; private readonly XmlDocument _doc; private readonly Encoding _encodingToUse; public SendFactory(string etag, string method, HttpRequestFilter filter, string contentType, XmlDocument doc, string encoding) { _etag = etag; _method = method; _filter = filter; _contentType = contentType; _doc = doc; //select the encoding _encodingToUse = new UTF8Encoding(false, false); try { _encodingToUse = StringHelper.GetEncoding(encoding, _encodingToUse); } catch (Exception ex) { Trace.Fail("Error while getting transport encoding: " + ex.ToString()); } } public HttpWebRequest Create(string uri) { HttpWebRequest request = HttpRequestHelper.CreateHttpWebRequest(uri, true); request.Method = _method; // request.KeepAlive = true; // request.Pipelined = true; if (_etag != null && _etag != "") request.Headers["If-match"] = _etag; if (_contentType != null) request.ContentType = _contentType; if (_filter != null) _filter(request); if (ApplicationDiagnostics.VerboseLogging) Trace.WriteLine( string.Format(CultureInfo.InvariantCulture, "XML REST request:\r\n{0} {1}\r\n{2}\r\n{3}", _method, uri, (_etag != null && _etag != "") ? "If-match: " + _etag : "(no etag)", _doc.OuterXml)); using (Stream s = request.GetRequestStream()) { XmlTextWriter writer = new XmlTextWriter(s, _encodingToUse); writer.Formatting = Formatting.Indented; writer.Indentation = 1; writer.IndentChar = ' '; writer.WriteStartDocument(); _doc.DocumentElement.WriteTo(writer); writer.Close(); } return request; } } public class MultipartMimeSendFactory { private readonly string _filename; private readonly XmlDocument _xmlDoc; private readonly Encoding _encoding; private readonly HttpRequestFilter _filter; private readonly MultipartMimeRequestHelper _multipartMimeRequestHelper; public MultipartMimeSendFactory(HttpRequestFilter filter, XmlDocument xmlRequest, string filename, string encoding, MultipartMimeRequestHelper multipartMimeRequestHelper) { if (xmlRequest == null) throw new ArgumentNullException(); // Add boundary to params _filename = filename; _xmlDoc = xmlRequest; _filter = filter; _multipartMimeRequestHelper = multipartMimeRequestHelper; //select the encoding _encoding = new UTF8Encoding(false, false); try { _encoding = StringHelper.GetEncoding(encoding, _encoding); } catch (Exception ex) { Trace.Fail("Error while getting transport encoding: " + ex.ToString()); } } public HttpWebRequest Create(string uri) { HttpWebRequest req = HttpRequestHelper.CreateHttpWebRequest(uri, true); _multipartMimeRequestHelper.Init(req); if (_filter != null) _filter(req); _multipartMimeRequestHelper.Open(); _multipartMimeRequestHelper.AddXmlRequest(_xmlDoc); _multipartMimeRequestHelper.AddFile(_filename); _multipartMimeRequestHelper.Close(); using (CancelableStream stream = new CancelableStream(new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read))) { return _multipartMimeRequestHelper.SendRequest(stream); } } } protected static XmlDocument ParseXmlResponse(HttpWebResponse response) { MemoryStream ms = new MemoryStream(); using (Stream s = response.GetResponseStream()) { StreamHelper.Transfer(s, ms); } ms.Seek(0, SeekOrigin.Begin); try { if (ApplicationDiagnostics.VerboseLogging) Trace.WriteLine("XML REST response:\r\n" + UrlHelper.SafeToAbsoluteUri(response.ResponseUri) + "\r\n" + new StreamReader(ms, Encoding.UTF8).ReadToEnd()); } catch (Exception e) { Trace.Fail("Failed to log REST response: " + e.ToString()); } ms.Seek(0, SeekOrigin.Begin); if (ms.Length == 0) return null; try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(ms); XmlHelper.ApplyBaseUri(xmlDoc, response.ResponseUri); return xmlDoc; } catch (Exception e) { Trace.Fail("Malformed XML document: " + e.ToString()); return null; } } } }