context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using IglooCastle.Core.Elements; using System; using System.Linq; using System.Reflection; namespace IglooCastle.Core.Printers { internal sealed class TypePrinter : PrinterBase<TypeElement> { public TypePrinter(Documentation documentation) : base(documentation) { } public override string Print(TypeElement type, bool typeLinks = true) { if (type.IsArray) { return Print(type.GetElementType(), typeLinks) + "[]"; } if (type.IsByRef) { return Print(type.GetElementType(), typeLinks); } if (type.IsNullable) { return Print(type.GetNullableType(), typeLinks) + "?"; } string result; if (type.IsGenericType && !type.IsGenericParameter && !type.IsGenericTypeDefinition) { result = DoPrint(type.GetGenericTypeDefinition(), typeLinks); } else { result = DoPrint(type, typeLinks); } if (type.IsGenericType) { result += "&lt;"; result += string.Join(", ", type.GetGenericArguments().Select(t => Print(t, typeLinks))); result += "&gt;"; } return result; } private string DoPrint(TypeElement type, bool typeLinks) { string link = type.Link(); string text = link != null ? ShortName(type) : FullName(type); if (link != null && typeLinks) { return string.Format("<a href=\"{0}\">{1}</a>", link.Escape(), text); } else { return text; } } private string FullName(TypeElement type) { if (type.IsGenericParameter) { return type.Name; } if (type.IsGenericType) { return type.Member.FullName.Split('`')[0]; } return SystemTypes.Alias(type.Member) ?? type.Member.FullName ?? ShortName(type); } private string ShortName(TypeElement type) { if (type.IsNested && !type.IsGenericParameter) { TypeElement containerType = type.DeclaringType; return ShortName(containerType) + "." + type.Name; } if (type.IsGenericType) { return type.Name.Split('`')[0]; } return SystemTypes.Alias(type.Member) ?? type.Name; } [Flags] public enum NameComponents { Name = 0, GenericArguments = 1, Namespace = 2 } public string Name(TypeElement type, NameComponents nameComponents) { string name = ShortName(type); if (type.IsGenericType && ((nameComponents & NameComponents.GenericArguments) == NameComponents.GenericArguments)) { name = name + "&lt;" + string.Join(", ", type.GetGenericArguments().Select(t => t.Name)) + "&gt;"; } if ((nameComponents & NameComponents.Namespace) == NameComponents.Namespace) { name = type.Namespace + "." + name; } return name; } private string GenericArgumentSyntaxPrefix(TypeElement genericArgument) { var g = genericArgument.GenericParameterAttributes; if ((g & GenericParameterAttributes.Contravariant) == GenericParameterAttributes.Contravariant) { return "in"; } if ((g & GenericParameterAttributes.Covariant) == GenericParameterAttributes.Covariant) { return "out"; } return string.Empty; } private string GenericArgumentSyntax(TypeElement genericArgument) { return " ".JoinNonEmpty(GenericArgumentSyntaxPrefix(genericArgument), genericArgument.Name); } private string NameForSyntax(TypeElement type) { string name = ShortName(type); if (type.IsGenericType) { name += "&lt;" + string.Join(", ", type.GetGenericArguments().Select(GenericArgumentSyntax)) + "&gt;"; } return name; } private TypeElement BaseTypeForSyntax(TypeElement type) { if (type.IsValueType) { return null; } TypeElement baseType = type.BaseType; if (baseType != null && baseType.BaseType == null) { // every class derives from System.Object, that's not interesting return null; } return baseType; } public override string Syntax(TypeElement type, bool typeLinks = true) { string result = " ".JoinNonEmpty( SyntaxOfAttributes(type, typeLinks), "public", type.IsInterface || type.IsValueType ? "" : (type.IsStatic ? "static" : (type.IsSealed ? "sealed" : type.IsAbstract ? "abstract" : "")), type.IsClass ? "class" : type.IsEnum ? "enum" : type.IsInterface ? "interface" : "struct", NameForSyntax(type)); TypeElement baseType = BaseTypeForSyntax(type); var interfaces = type.GetInterfaces(); var baseTypes = new[] { baseType }.Concat(interfaces).Where(t => t != null).ToArray(); if (baseTypes.Any()) { result = result + " : " + string.Join(", ", baseTypes.Select(t => Print(t, typeLinks))); } return result; } public override string Signature(TypeElement element, bool typeLinks = true) { throw new NotImplementedException(); } public override string Format(TypeElement element, string format) { if (format != "n" && format != "s" && format != "f") { return base.Format(element, format); } TypePrinter.NameComponents nameComponents = TypePrinter.NameComponents.Name; if (format != "n") { nameComponents |= TypePrinter.NameComponents.GenericArguments; } if (format == "f") { nameComponents = nameComponents | TypePrinter.NameComponents.Namespace; } return Name(element, nameComponents); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition.Primitives; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using Microsoft.Internal; using Microsoft.Internal.Collections; namespace System.ComponentModel.Composition { /// <summary> /// The exception that is thrown when one or more errors occur during composition. /// </summary> [DebuggerTypeProxy(typeof(CompositionExceptionDebuggerProxy))] [DebuggerDisplay("{Message}")] public class CompositionException : Exception { private const string ErrorsKey = "Errors"; private ReadOnlyCollection<CompositionError> _errors; #if FEATURE_SERIALIZATION private struct CompositionExceptionData : ISafeSerializationData { public CompositionError[] _errors; void ISafeSerializationData.CompleteDeserialization(object obj) { CompositionException exception = obj as CompositionException; exception._errors = new ReadOnlyCollection<CompositionError>(_errors); } } #endif /// <summary> /// Initializes a new instance of the <see cref="CompositionException"/> class. /// </summary> public CompositionException() : this((string)null, (Exception)null, (IEnumerable<CompositionError>)null) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionException"/> class /// with the specified error message. /// </summary> /// <param name="message"> /// A <see cref="String"/> containing a message that describes the /// <see cref="CompositionException"/>; or <see langword="null"/> to set /// the <see cref="Exception.Message"/> property to its default value. /// </param> public CompositionException(string message) : this(message, (Exception)null, (IEnumerable<CompositionError>)null) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionException"/> class /// with the specified error message and exception that is the cause of the /// exception. /// </summary> /// <param name="message"> /// A <see cref="String"/> containing a message that describes the /// <see cref="CompositionException"/>; or <see langword="null"/> to set /// the <see cref="Exception.Message"/> property to its default value. /// </param> /// <param name="innerException"> /// The <see cref="Exception"/> that is the underlying cause of the /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set /// the <see cref="Exception.InnerException"/> property to <see langword="null"/>. /// </param> public CompositionException(string message, Exception innerException) : this(message, innerException, (IEnumerable<CompositionError>)null) { } internal CompositionException(CompositionError error) : this(new CompositionError[] { error }) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionException"/> class /// with the specified errors. /// </summary> /// <param name="errors"> /// An <see cref="IEnumerable{T}"/> of <see cref="CompositionError"/> objects /// representing the errors that are the cause of the /// <see cref="CompositionException"/>; or <see langword="null"/> to set the /// <see cref="Errors"/> property to an empty <see cref="IEnumerable{T}"/>. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="errors"/> contains an element that is <see langword="null"/>. /// </exception> public CompositionException(IEnumerable<CompositionError> errors) : this((string)null, (Exception)null, errors) { } internal CompositionException(string message, Exception innerException, IEnumerable<CompositionError> errors) : base(message, innerException) { Requires.NullOrNotNullElements(errors, "errors"); #if FEATURE_SERIALIZATION SerializeObjectState += delegate(object exception, SafeSerializationEventArgs eventArgs) { var data = new CompositionExceptionData(); if(_errors != null) { data._errors = _errors.Select(error => new CompositionError( error.Id, error.Description, error.Element.ToSerializableElement(), error.Exception)).ToArray(); } else { data._errors = new CompositionError[0]; } eventArgs.AddSerializedState(data); }; #endif _errors = new ReadOnlyCollection<CompositionError>(errors == null ? new CompositionError[0] : errors.ToArray<CompositionError>()); } /// <summary> /// Gets the errors that are the cause of the exception. /// </summary> /// <value> /// An <see cref="IEnumerable{T}"/> of <see cref="CompositionError"/> objects /// representing the errors that are the cause of the /// <see cref="CompositionException"/>. /// </value> public ReadOnlyCollection<CompositionError> Errors { get { return _errors; } } /// <summary> /// Gets a message that describes the exception. /// </summary> /// <value> /// A <see cref="String"/> containing a message that describes the /// <see cref="CompositionException"/>. /// </value> public override string Message { get { if (Errors.Count == 0) { // If there are no errors, then we simply return base.Message, // which will either use the default Exception message, or if // one was specified; the user supplied message. return base.Message; } return BuildDefaultMessage(); } } public ReadOnlyCollection<Exception> RootCauses { get { var errors = new List<Exception>(); // In here return a collection of all of the exceptions in the Errors collection foreach (var error in Errors) { if (error.Exception != null) { var ce = error.Exception as CompositionException; if (ce != null) { if (ce.RootCauses.Count > 0) { errors.AddRange(ce.RootCauses); continue; } } errors.Add(error.Exception); } } return errors.ToReadOnlyCollection<Exception>(); } } private string BuildDefaultMessage() { IEnumerable<IEnumerable<CompositionError>> paths = CalculatePaths(this); StringBuilder writer = new StringBuilder(); WriteHeader(writer, Errors.Count, paths.Count()); WritePaths(writer, paths); return writer.ToString(); } private static void WriteHeader(StringBuilder writer, int errorsCount, int pathCount) { if (errorsCount > 1 && pathCount > 1) { // The composition produced multiple composition errors, with {0} root causes. The root causes are provided below. writer.AppendFormat( CultureInfo.CurrentCulture, SR.CompositionException_MultipleErrorsWithMultiplePaths, pathCount); } else if (errorsCount == 1 && pathCount > 1) { // The composition produced a single composition error, with {0} root causes. The root causes are provided below. writer.AppendFormat( CultureInfo.CurrentCulture, SR.CompositionException_SingleErrorWithMultiplePaths, pathCount); } else { Assumes.IsTrue(errorsCount == 1); Assumes.IsTrue(pathCount == 1); // The composition produced a single composition error. The root cause is provided below. writer.AppendFormat( CultureInfo.CurrentCulture, SR.CompositionException_SingleErrorWithSinglePath, pathCount); } writer.Append(' '); writer.AppendLine(SR.CompositionException_ReviewErrorProperty); } private static void WritePaths(StringBuilder writer, IEnumerable<IEnumerable<CompositionError>> paths) { int ordinal = 0; foreach (IEnumerable<CompositionError> path in paths) { ordinal++; WritePath(writer, path, ordinal); } } private static void WritePath(StringBuilder writer, IEnumerable<CompositionError> path, int ordinal) { writer.AppendLine(); writer.Append(ordinal.ToString(CultureInfo.CurrentCulture)); writer.Append(SR.CompositionException_PathsCountSeparator); writer.Append(' '); WriteError(writer, path.First()); foreach (CompositionError error in path.Skip(1)) { writer.AppendLine(); writer.Append(SR.CompositionException_ErrorPrefix); writer.Append(' '); WriteError(writer, error); } } private static void WriteError(StringBuilder writer, CompositionError error) { writer.AppendLine(error.Description); if (error.Element != null) { WriteElementGraph(writer, error.Element); } } private static void WriteElementGraph(StringBuilder writer, ICompositionElement element) { // Writes the composition element and its origins in the format: // Element: Export --> Part --> PartDefinition --> Catalog writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_ElementPrefix, element.DisplayName); while ((element = element.Origin) != null) { writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_OriginFormat, SR.CompositionException_OriginSeparator, element.DisplayName); } writer.AppendLine(); } private static IEnumerable<IEnumerable<CompositionError>> CalculatePaths(CompositionException exception) { List<IEnumerable<CompositionError>> paths = new List<IEnumerable<CompositionError>>(); VisitContext context = new VisitContext(); context.Path = new Stack<CompositionError>(); context.LeafVisitor = path => { // Take a snapshot of the path paths.Add(path.Copy()); }; VisitCompositionException(exception, context); return paths; } private static void VisitCompositionException(CompositionException exception, VisitContext context) { foreach (CompositionError error in exception.Errors) { VisitError(error, context); } if (exception.InnerException != null) { VisitException(exception.InnerException, context); } } private static void VisitError(CompositionError error, VisitContext context) { context.Path.Push(error); if (error.Exception == null) { // This error is a root cause, so write // out the stack from this point context.LeafVisitor(context.Path); } else { VisitException(error.Exception, context); } context.Path.Pop(); } private static void VisitException(Exception exception, VisitContext context) { CompositionException composition = exception as CompositionException; if (composition != null) { VisitCompositionException(composition, context); } else { VisitError(new CompositionError(exception.Message, exception.InnerException), context); } } private struct VisitContext { public Stack<CompositionError> Path; public Action<Stack<CompositionError>> LeafVisitor; } } }
//----------------------------------------------------------------------- // <copyright file="GraphMergeSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Reactive.Streams; using Xunit; using Xunit.Abstractions; // ReSharper disable InvokeAsExtensionMethod namespace Akka.Streams.Tests.Dsl { public class GraphMergeSpec : TwoStreamsSetup<int> { public GraphMergeSpec(ITestOutputHelper helper) : base(helper) { } protected override Fixture CreateFixture(GraphDsl.Builder<NotUsed> builder) => new MergeFixture(builder); private sealed class MergeFixture : Fixture { public MergeFixture(GraphDsl.Builder<NotUsed> builder) : base(builder) { var merge = builder.Add(new Merge<int, int>(2)); Left = merge.In(0); Right = merge.In(1); Out = merge.Out; } public override Inlet<int> Left { get; } public override Inlet<int> Right { get; } public override Outlet<int> Out { get; } } [Fact] public void A_Merge_must_work_in_the_happy_case() { this.AssertAllStagesStopped(() => { // Different input sizes(4 and 6) var source1 = Source.From(Enumerable.Range(0, 4)); var source2 = Source.From(Enumerable.Range(4, 6)); var source3 = Source.From(new List<int>()); var probe = this.CreateManualSubscriberProbe<int>(); RunnableGraph.FromGraph(GraphDsl.Create(b => { var m1 = b.Add(new Merge<int>(2)); var m2 = b.Add(new Merge<int>(2)); var sink = Sink.FromSubscriber(probe); b.From(source1).To(m1.In(0)); b.From(m1.Out).Via(Flow.Create<int>().Select(x => x*2)).To(m2.In(0)); b.From(m2.Out).Via(Flow.Create<int>().Select(x => x / 2).Select(x=>x+1)).To(sink); b.From(source2).To(m1.In(1)); b.From(source3).To(m2.In(1)); return ClosedShape.Instance; })).Run(Materializer); var subscription = probe.ExpectSubscription(); var collected = new List<int>(); for (var i = 1; i <= 10; i++) { subscription.Request(1); collected.Add(probe.ExpectNext()); } collected.ShouldAllBeEquivalentTo(Enumerable.Range(1,10)); probe.ExpectComplete(); }, Materializer); } [Fact] public void A_Merge_must_work_with_one_way_merge() { var task = Source.FromGraph(GraphDsl.Create(b => { var merge = b.Add(new Merge<int>(1)); var source = b.Add(Source.From(Enumerable.Range(1, 3))); b.From(source).To(merge.In(0)); return new SourceShape<int>(merge.Out); })).RunAggregate(new List<int>(), (list, i) => { list.Add(i); return list; }, Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 3)); } [Fact] public void A_Merge_must_work_with_n_way_merge() { var source1 = Source.Single(1); var source2 = Source.Single(2); var source3 = Source.Single(3); var source4 = Source.Single(4); var source5 = Source.Single(5); var source6 = Source.Empty<int>(); var probe = this.CreateManualSubscriberProbe<int>(); RunnableGraph.FromGraph(GraphDsl.Create(b => { var merge = b.Add(new Merge<int>(6)); b.From(source1).To(merge.In(0)); b.From(source2).To(merge.In(1)); b.From(source3).To(merge.In(2)); b.From(source4).To(merge.In(3)); b.From(source5).To(merge.In(4)); b.From(source6).To(merge.In(5)); b.From(merge.Out).To(Sink.FromSubscriber(probe)); return ClosedShape.Instance; })).Run(Materializer); var subscription = probe.ExpectSubscription(); var collected = new List<int>(); for (var i = 1; i <= 5; i++) { subscription.Request(1); collected.Add(probe.ExpectNext()); } collected.ShouldAllBeEquivalentTo(Enumerable.Range(1, 5)); probe.ExpectComplete(); } [Fact] public void A_Merge_must_work_with_one_immediately_completed_and_one_nonempty_publisher() { this.AssertAllStagesStopped(() => { var subscriber1 = Setup(CompletedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4))); var subscription1 = subscriber1.ExpectSubscription(); subscription1.Request(4); subscriber1.ExpectNext(1, 2, 3, 4).ExpectComplete(); var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), CompletedPublisher<int>()); var subscription2 = subscriber2.ExpectSubscription(); subscription2.Request(4); subscriber2.ExpectNext(1, 2, 3, 4).ExpectComplete(); }, Materializer); } [Fact] public void A_Merge_must_work_with_one_delayed_completed_and_one_nonempty_publisher() { this.AssertAllStagesStopped(() => { var subscriber1 = Setup(SoonToCompletePublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4))); var subscription1 = subscriber1.ExpectSubscription(); subscription1.Request(4); subscriber1.ExpectNext(1, 2, 3, 4).ExpectComplete(); var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), SoonToCompletePublisher<int>()); var subscription2 = subscriber2.ExpectSubscription(); subscription2.Request(4); subscriber2.ExpectNext(1, 2, 3, 4).ExpectComplete(); }, Materializer); } [Fact(Skip = "This is nondeterministic, multiple scenarios can happen")] public void A_Merge_must_work_with_one_immediately_failed_and_one_nonempty_publisher() { this.AssertAllStagesStopped(() => { }, Materializer); } [Fact(Skip = "This is nondeterministic, multiple scenarios can happen")] public void A_Merge_must_work_with_one_delayed_failed_and_one_nonempty_publisher() { this.AssertAllStagesStopped(() => { }, Materializer); } [Fact] public void A_Merge_must_pass_along_early_cancellation() { this.AssertAllStagesStopped(() => { var up1 = this.CreateManualPublisherProbe<int>(); var up2 = this.CreateManualPublisherProbe<int>(); var down = this.CreateManualSubscriberProbe<int>(); var src1 = Source.AsSubscriber<int>(); var src2 = Source.AsSubscriber<int>(); var t = RunnableGraph.FromGraph(GraphDsl.Create(src1, src2, Tuple.Create, (b, s1, s2) => { var merge = b.Add(new Merge<int>(2)); var sink = Sink.FromSubscriber(down) .MapMaterializedValue<Tuple<ISubscriber<int>, ISubscriber<int>>>(_ => null); b.From(s1.Outlet).To(merge.In(0)); b.From(s2.Outlet).To(merge.In(1)); b.From(merge.Out).To(sink); return ClosedShape.Instance; })).Run(Materializer); var downstream = down.ExpectSubscription(); downstream.Cancel(); up1.Subscribe(t.Item1); up2.Subscribe(t.Item2); var upSub1 = up1.ExpectSubscription(); upSub1.ExpectCancellation(); var upSub2 = up2.ExpectSubscription(); upSub2.ExpectCancellation(); }, Materializer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; namespace System.Net.NetworkInformation { /// <summary> /// A storage structure for the information parsed out of the /// /proc/net/snmp file, related to ICMPv4 protocol statistics. /// </summary> internal struct Icmpv4StatisticsTable { public int InMsgs; public int InErrors; public int InCsumErrors; public int InDestUnreachs; public int InTimeExcds; public int InParmProbs; public int InSrcQuenchs; public int InRedirects; public int InEchos; public int InEchoReps; public int InTimestamps; public int InTimeStampReps; public int InAddrMasks; public int InAddrMaskReps; public int OutMsgs; public int OutErrors; public int OutDestUnreachs; public int OutTimeExcds; public int OutParmProbs; public int OutSrcQuenchs; public int OutRedirects; public int OutEchos; public int OutEchoReps; public int OutTimestamps; public int OutTimestampReps; public int OutAddrMasks; public int OutAddrMaskReps; } /// <summary> /// A storage structure for the information parsed out of the /// /proc/net/snmp6 file, related to ICMPv6 protocol statistics. /// </summary> internal struct Icmpv6StatisticsTable { public int InDestUnreachs; public int OutDestUnreachs; public int InEchoReplies; public int InEchos; public int OutEchoReplies; public int OutEchos; public int InErrors; public int OutErrors; public int InGroupMembQueries; public int OutInGroupMembQueries; public int InGroupMembReductions; public int OutGroupMembReductions; public int InGroupMembResponses; public int OutGroupMembResponses; public int InMsgs; public int OutMsgs; public int InNeighborAdvertisements; public int OutNeighborAdvertisements; public int InNeighborSolicits; public int OutNeighborSolicits; public int InPktTooBigs; public int OutPktTooBigs; public int InParmProblems; public int OutParmProblems; public int InRedirects; public int OutRedirects; public int InRouterSolicits; public int OutRouterSolicits; public int InRouterAdvertisements; public int OutRouterAdvertisements; public int InTimeExcds; public int OutTimeExcds; } internal struct TcpGlobalStatisticsTable { public int RtoAlgorithm; public int RtoMin; public int RtoMax; public int MaxConn; public int ActiveOpens; public int PassiveOpens; public int AttemptFails; public int EstabResets; public int CurrEstab; public int InSegs; public int OutSegs; public int RetransSegs; public int InErrs; public int OutRsts; public int InCsumErrors; } internal struct UdpGlobalStatisticsTable { public int InDatagrams; public int NoPorts; public int InErrors; public int OutDatagrams; public int RcvbufErrors; public int SndbufErrors; public int InCsumErrors; } /// <summary> /// Storage structure for IP Global statistics from /proc/net/snmp /// </summary> internal struct IPGlobalStatisticsTable { // Information exposed in the snmp (ipv4) and snmp6 (ipv6) files under /proc/net // Each piece corresponds to a data item defined in the MIB-II specification: // http://www.ietf.org/rfc/rfc1213.txt // Each field's comment indicates the name as it appears in the snmp (snmp6) file. // In the snmp6 file, each name is prefixed with "IP6". public bool Forwarding; // Forwarding public int DefaultTtl; // DefaultTTL public int InReceives; // InReceives public int InHeaderErrors; // InHdrErrors public int InAddressErrors; // InAddrErrors public int ForwardedDatagrams; // ForwDatagrams (IP6OutForwDatagrams) public int InUnknownProtocols; // InUnknownProtos public int InDiscards; // InDiscards public int InDelivers; // InDelivers public int OutRequests; // OutRequestscat public int OutDiscards; // OutDiscards public int OutNoRoutes; // OutNoRoutes public int ReassemblyTimeout; // ReasmTimeout public int ReassemblyRequireds; // ReasmReqds public int ReassemblyOKs; // ReasmOKs public int ReassemblyFails; // ReasmFails public int FragmentOKs; // FragOKs public int FragmentFails; // FragFails public int FragmentCreates; // FragCreates } internal struct IPInterfaceStatisticsTable { // Receive section public uint BytesReceived; public uint PacketsReceived; public uint ErrorsReceived; public uint IncomingPacketsDropped; public uint FifoBufferErrorsReceived; public uint PacketFramingErrorsReceived; public uint CompressedPacketsReceived; public uint MulticastFramesReceived; // Transmit section public uint BytesTransmitted; public uint PacketsTransmitted; public uint ErrorsTransmitted; public uint OutgoingPacketsDropped; public uint FifoBufferErrorsTransmitted; public uint CollisionsDetected; public uint CarrierLosses; public uint CompressedPacketsTransmitted; } internal static partial class StringParsingHelpers { // Parses ICMP v4 statistics from /proc/net/snmp public static Icmpv4StatisticsTable ParseIcmpv4FromSnmpFile(string filePath) { string fileContents = File.ReadAllText(filePath); int firstIpHeader = fileContents.IndexOf("Icmp:", StringComparison.Ordinal); int secondIpHeader = fileContents.IndexOf("Icmp:", firstIpHeader + 1, StringComparison.Ordinal); int endOfSecondLine = fileContents.IndexOf(Environment.NewLine, secondIpHeader, StringComparison.Ordinal); string icmpData = fileContents.Substring(secondIpHeader, endOfSecondLine - secondIpHeader); StringParser parser = new StringParser(icmpData, ' '); parser.MoveNextOrFail(); // Skip Icmp: return new Icmpv4StatisticsTable() { InMsgs = parser.ParseNextInt32(), InErrors = parser.ParseNextInt32(), InCsumErrors = parser.ParseNextInt32(), InDestUnreachs = parser.ParseNextInt32(), InTimeExcds = parser.ParseNextInt32(), InParmProbs = parser.ParseNextInt32(), InSrcQuenchs = parser.ParseNextInt32(), InRedirects = parser.ParseNextInt32(), InEchos = parser.ParseNextInt32(), InEchoReps = parser.ParseNextInt32(), InTimestamps = parser.ParseNextInt32(), InTimeStampReps = parser.ParseNextInt32(), InAddrMasks = parser.ParseNextInt32(), InAddrMaskReps = parser.ParseNextInt32(), OutMsgs = parser.ParseNextInt32(), OutErrors = parser.ParseNextInt32(), OutDestUnreachs = parser.ParseNextInt32(), OutTimeExcds = parser.ParseNextInt32(), OutParmProbs = parser.ParseNextInt32(), OutSrcQuenchs = parser.ParseNextInt32(), OutRedirects = parser.ParseNextInt32(), OutEchos = parser.ParseNextInt32(), OutEchoReps = parser.ParseNextInt32(), OutTimestamps = parser.ParseNextInt32(), OutTimestampReps = parser.ParseNextInt32(), OutAddrMasks = parser.ParseNextInt32(), OutAddrMaskReps = parser.ParseNextInt32() }; } public static Icmpv6StatisticsTable ParseIcmpv6FromSnmp6File(string filePath) { string fileContents = File.ReadAllText(filePath); RowConfigReader reader = new RowConfigReader(fileContents); return new Icmpv6StatisticsTable() { InMsgs = reader.GetNextValueAsInt32("Icmp6InMsgs"), InErrors = reader.GetNextValueAsInt32("Icmp6InErrors"), OutMsgs = reader.GetNextValueAsInt32("Icmp6OutMsgs"), OutErrors = reader.GetNextValueAsInt32("Icmp6OutErrors"), InDestUnreachs = reader.GetNextValueAsInt32("Icmp6InDestUnreachs"), InPktTooBigs = reader.GetNextValueAsInt32("Icmp6InPktTooBigs"), InTimeExcds = reader.GetNextValueAsInt32("Icmp6InTimeExcds"), InParmProblems = reader.GetNextValueAsInt32("Icmp6InParmProblems"), InEchos = reader.GetNextValueAsInt32("Icmp6InEchos"), InEchoReplies = reader.GetNextValueAsInt32("Icmp6InEchoReplies"), InGroupMembQueries = reader.GetNextValueAsInt32("Icmp6InGroupMembQueries"), InGroupMembResponses = reader.GetNextValueAsInt32("Icmp6InGroupMembResponses"), InGroupMembReductions = reader.GetNextValueAsInt32("Icmp6InGroupMembReductions"), InRouterSolicits = reader.GetNextValueAsInt32("Icmp6InRouterSolicits"), InRouterAdvertisements = reader.GetNextValueAsInt32("Icmp6InRouterAdvertisements"), InNeighborSolicits = reader.GetNextValueAsInt32("Icmp6InNeighborSolicits"), InNeighborAdvertisements = reader.GetNextValueAsInt32("Icmp6InNeighborAdvertisements"), InRedirects = reader.GetNextValueAsInt32("Icmp6InRedirects"), OutDestUnreachs = reader.GetNextValueAsInt32("Icmp6OutDestUnreachs"), OutPktTooBigs = reader.GetNextValueAsInt32("Icmp6OutPktTooBigs"), OutTimeExcds = reader.GetNextValueAsInt32("Icmp6OutTimeExcds"), OutParmProblems = reader.GetNextValueAsInt32("Icmp6OutParmProblems"), OutEchos = reader.GetNextValueAsInt32("Icmp6OutEchos"), OutEchoReplies = reader.GetNextValueAsInt32("Icmp6OutEchoReplies"), OutInGroupMembQueries = reader.GetNextValueAsInt32("Icmp6OutGroupMembQueries"), OutGroupMembResponses = reader.GetNextValueAsInt32("Icmp6OutGroupMembResponses"), OutGroupMembReductions = reader.GetNextValueAsInt32("Icmp6OutGroupMembReductions"), OutRouterSolicits = reader.GetNextValueAsInt32("Icmp6OutRouterSolicits"), OutRouterAdvertisements = reader.GetNextValueAsInt32("Icmp6OutRouterAdvertisements"), OutNeighborSolicits = reader.GetNextValueAsInt32("Icmp6OutNeighborSolicits"), OutNeighborAdvertisements = reader.GetNextValueAsInt32("Icmp6OutNeighborAdvertisements"), OutRedirects = reader.GetNextValueAsInt32("Icmp6OutRedirects") }; } public static IPGlobalStatisticsTable ParseIPv4GlobalStatisticsFromSnmpFile(string filePath) { string fileContents = File.ReadAllText(filePath); int firstIpHeader = fileContents.IndexOf("Ip:", StringComparison.Ordinal); int secondIpHeader = fileContents.IndexOf("Ip:", firstIpHeader + 1, StringComparison.Ordinal); int endOfSecondLine = fileContents.IndexOf(Environment.NewLine, secondIpHeader, StringComparison.Ordinal); string ipData = fileContents.Substring(secondIpHeader, endOfSecondLine - secondIpHeader); StringParser parser = new StringParser(ipData, ' '); parser.MoveNextOrFail(); // Skip Ip: // According to RFC 1213, "1" indicates "acting as a gateway". "2" indicates "NOT acting as a gateway". return new IPGlobalStatisticsTable() { Forwarding = parser.MoveAndExtractNext() == "1", DefaultTtl = parser.ParseNextInt32(), InReceives = parser.ParseNextInt32(), InHeaderErrors = parser.ParseNextInt32(), InAddressErrors = parser.ParseNextInt32(), ForwardedDatagrams = parser.ParseNextInt32(), InUnknownProtocols = parser.ParseNextInt32(), InDiscards = parser.ParseNextInt32(), InDelivers = parser.ParseNextInt32(), OutRequests = parser.ParseNextInt32(), OutDiscards = parser.ParseNextInt32(), OutNoRoutes = parser.ParseNextInt32(), ReassemblyTimeout = parser.ParseNextInt32(), ReassemblyRequireds = parser.ParseNextInt32(), ReassemblyOKs = parser.ParseNextInt32(), ReassemblyFails = parser.ParseNextInt32(), FragmentOKs = parser.ParseNextInt32(), FragmentFails = parser.ParseNextInt32(), FragmentCreates = parser.ParseNextInt32(), }; } internal static IPGlobalStatisticsTable ParseIPv6GlobalStatisticsFromSnmp6File(string filePath) { // Read the remainder of statistics from snmp6. string fileContents = File.ReadAllText(filePath); RowConfigReader reader = new RowConfigReader(fileContents); return new IPGlobalStatisticsTable() { InReceives = reader.GetNextValueAsInt32("Ip6InReceives"), InHeaderErrors = reader.GetNextValueAsInt32("Ip6InHdrErrors"), InAddressErrors = reader.GetNextValueAsInt32("Ip6InAddrErrors"), InUnknownProtocols = reader.GetNextValueAsInt32("Ip6InUnknownProtos"), InDiscards = reader.GetNextValueAsInt32("Ip6InDiscards"), InDelivers = reader.GetNextValueAsInt32("Ip6InDelivers"), ForwardedDatagrams = reader.GetNextValueAsInt32("Ip6OutForwDatagrams"), OutRequests = reader.GetNextValueAsInt32("Ip6OutRequests"), OutDiscards = reader.GetNextValueAsInt32("Ip6OutDiscards"), OutNoRoutes = reader.GetNextValueAsInt32("Ip6OutNoRoutes"), ReassemblyTimeout = reader.GetNextValueAsInt32("Ip6ReasmTimeout"), ReassemblyRequireds = reader.GetNextValueAsInt32("Ip6ReasmReqds"), ReassemblyOKs = reader.GetNextValueAsInt32("Ip6ReasmOKs"), ReassemblyFails = reader.GetNextValueAsInt32("Ip6ReasmFails"), FragmentOKs = reader.GetNextValueAsInt32("Ip6FragOKs"), FragmentFails = reader.GetNextValueAsInt32("Ip6FragFails"), FragmentCreates = reader.GetNextValueAsInt32("Ip6FragCreates"), }; } internal static TcpGlobalStatisticsTable ParseTcpGlobalStatisticsFromSnmpFile(string filePath) { // NOTE: There is no information in the snmp6 file regarding TCP statistics, // so the statistics are always pulled from /proc/net/snmp. string fileContents = File.ReadAllText(filePath); int firstTcpHeader = fileContents.IndexOf("Tcp:", StringComparison.Ordinal); int secondTcpHeader = fileContents.IndexOf("Tcp:", firstTcpHeader + 1, StringComparison.Ordinal); int endOfSecondLine = fileContents.IndexOf(Environment.NewLine, secondTcpHeader, StringComparison.Ordinal); string tcpData = fileContents.Substring(secondTcpHeader, endOfSecondLine - secondTcpHeader); StringParser parser = new StringParser(tcpData, ' '); parser.MoveNextOrFail(); // Skip Tcp: return new TcpGlobalStatisticsTable() { RtoAlgorithm = parser.ParseNextInt32(), RtoMin = parser.ParseNextInt32(), RtoMax = parser.ParseNextInt32(), MaxConn = parser.ParseNextInt32(), ActiveOpens = parser.ParseNextInt32(), PassiveOpens = parser.ParseNextInt32(), AttemptFails = parser.ParseNextInt32(), EstabResets = parser.ParseNextInt32(), CurrEstab = parser.ParseNextInt32(), InSegs = parser.ParseNextInt32(), OutSegs = parser.ParseNextInt32(), RetransSegs = parser.ParseNextInt32(), InErrs = parser.ParseNextInt32(), OutRsts = parser.ParseNextInt32(), InCsumErrors = parser.ParseNextInt32() }; } internal static UdpGlobalStatisticsTable ParseUdpv4GlobalStatisticsFromSnmpFile(string filePath) { string fileContents = File.ReadAllText(filePath); int firstUdpHeader = fileContents.IndexOf("Udp:", StringComparison.Ordinal); int secondUdpHeader = fileContents.IndexOf("Udp:", firstUdpHeader + 1, StringComparison.Ordinal); int endOfSecondLine = fileContents.IndexOf(Environment.NewLine, secondUdpHeader, StringComparison.Ordinal); string tcpData = fileContents.Substring(secondUdpHeader, endOfSecondLine - secondUdpHeader); StringParser parser = new StringParser(tcpData, ' '); parser.MoveNextOrFail(); // Skip Udp: return new UdpGlobalStatisticsTable() { InDatagrams = parser.ParseNextInt32(), NoPorts = parser.ParseNextInt32(), InErrors = parser.ParseNextInt32(), OutDatagrams = parser.ParseNextInt32(), RcvbufErrors = parser.ParseNextInt32(), SndbufErrors = parser.ParseNextInt32(), InCsumErrors = parser.ParseNextInt32() }; } internal static UdpGlobalStatisticsTable ParseUdpv6GlobalStatisticsFromSnmp6File(string filePath) { string fileContents = File.ReadAllText(filePath); RowConfigReader reader = new RowConfigReader(fileContents); return new UdpGlobalStatisticsTable() { InDatagrams = reader.GetNextValueAsInt32("Udp6InDatagrams"), NoPorts = reader.GetNextValueAsInt32("Udp6NoPorts"), InErrors = reader.GetNextValueAsInt32("Udp6InErrors"), OutDatagrams = reader.GetNextValueAsInt32("Udp6OutDatagrams"), RcvbufErrors = reader.GetNextValueAsInt32("Udp6RcvbufErrors"), SndbufErrors = reader.GetNextValueAsInt32("Udp6SndbufErrors"), InCsumErrors = reader.GetNextValueAsInt32("Udp6InCsumErrors"), }; } internal static IPInterfaceStatisticsTable ParseInterfaceStatisticsTableFromFile(string filePath, string name) { using (StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 0x1000, useAsync: false))) { sr.ReadLine(); sr.ReadLine(); int index = 0; while (!sr.EndOfStream) { string line = sr.ReadLine(); if (line.Contains(name)) { string[] pieces = line.Split(new char[] { ' ', ':' }, StringSplitOptions.RemoveEmptyEntries); return new IPInterfaceStatisticsTable() { BytesReceived = ParseUInt64AndClampToUInt32(pieces[1]), PacketsReceived = ParseUInt64AndClampToUInt32(pieces[2]), ErrorsReceived = ParseUInt64AndClampToUInt32(pieces[3]), IncomingPacketsDropped = ParseUInt64AndClampToUInt32(pieces[4]), FifoBufferErrorsReceived = ParseUInt64AndClampToUInt32(pieces[5]), PacketFramingErrorsReceived = ParseUInt64AndClampToUInt32(pieces[6]), CompressedPacketsReceived = ParseUInt64AndClampToUInt32(pieces[7]), MulticastFramesReceived = ParseUInt64AndClampToUInt32(pieces[8]), BytesTransmitted = ParseUInt64AndClampToUInt32(pieces[9]), PacketsTransmitted = ParseUInt64AndClampToUInt32(pieces[10]), ErrorsTransmitted = ParseUInt64AndClampToUInt32(pieces[11]), OutgoingPacketsDropped = ParseUInt64AndClampToUInt32(pieces[12]), FifoBufferErrorsTransmitted = ParseUInt64AndClampToUInt32(pieces[13]), CollisionsDetected = ParseUInt64AndClampToUInt32(pieces[14]), CarrierLosses = ParseUInt64AndClampToUInt32(pieces[15]), CompressedPacketsTransmitted = ParseUInt64AndClampToUInt32(pieces[16]), }; } index += 1; } throw ExceptionHelper.CreateForParseFailure(); } } private static uint ParseUInt64AndClampToUInt32(string value) { return (uint)Math.Min(uint.MaxValue, ulong.Parse(value)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; using QueryStatics = Apache.Geode.Client.Tests.QueryStatics; using QueryCategory = Apache.Geode.Client.Tests.QueryCategory; using QueryStrings = Apache.Geode.Client.Tests.QueryStrings; [TestFixture] [Category("group1")] [Category("unicast_only")] [Category("generics")] public class ThinClientRemoteQueryResultSetTests : ThinClientRegionSteps { #region Private members private UnitProcess m_client1; private UnitProcess m_client2; private static string[] QueryRegionNames = { "Portfolios", "Positions", "Portfolios2", "Portfolios3" }; #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); return new ClientBase[] { m_client1, m_client2 }; } [TestFixtureSetUp] public override void InitTests() { base.InitTests(); } [TearDown] public override void EndTest() { m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServers(); base.EndTest(); } [SetUp] public override void InitTest() { m_client1.Call(InitClient); m_client2.Call(InitClient); } #region Functions invoked by the tests public void InitClient() { CacheHelper.Init(); Serializable.RegisterTypeGeneric(Portfolio.CreateDeserializable, CacheHelper.DCache); Serializable.RegisterTypeGeneric(Position.CreateDeserializable, CacheHelper.DCache); Serializable.RegisterPdxType(Apache.Geode.Client.Tests.PortfolioPdx.CreateDeserializable); Serializable.RegisterPdxType(Apache.Geode.Client.Tests.PositionPdx.CreateDeserializable); } public void StepOne(string locators, bool isPdx) { m_isPdx = isPdx; CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[1], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[2], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[3], true, true, null, locators, "__TESTPOOL1_", true); IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); Apache.Geode.Client.RegionAttributes<object, object> regattrs = region.Attributes; region.CreateSubRegion(QueryRegionNames[1], regattrs); } public void StepTwo(bool isPdx) { m_isPdx = isPdx; IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); IRegion<object, object> subRegion0 = (IRegion<object, object>)region0.GetSubRegion(QueryRegionNames[1]); IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(QueryRegionNames[1]); IRegion<object, object> region2 = CacheHelper.GetRegion<object, object>(QueryRegionNames[2]); IRegion<object, object> region3 = CacheHelper.GetRegion<object, object>(QueryRegionNames[3]); QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); Util.Log("SetSize {0}, NumSets {1}.", qh.PortfolioSetSize, qh.PortfolioNumSets); if (!m_isPdx) { qh.PopulatePortfolioData(region0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionData(subRegion0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionData(region1, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioData(region2, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioData(region3, qh.PortfolioSetSize, qh.PortfolioNumSets); } else { qh.PopulatePortfolioPdxData(region0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionPdxData(subRegion0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionPdxData(region1, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region2, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region3, qh.PortfolioSetSize, qh.PortfolioNumSets); } } public void StepThreeRS() { bool ErrorOccurred = false; QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService(); int qryIdx = 0; foreach (QueryStrings qrystr in QueryStatics.ResultSetQueries) { if (qrystr.Category == QueryCategory.Unsupported) { Util.Log("Skipping query index {0} because it is unsupported.", qryIdx); qryIdx++; continue; } if (m_isPdx == true) { if (qryIdx == 2 || qryIdx == 3 || qryIdx == 4) { Util.Log("Skipping query index {0} for Pdx because it is function type.", qryIdx); qryIdx++; continue; } } Util.Log("Evaluating query index {0}. Query string {1}", qryIdx, qrystr.Query); Query<object> query = qs.NewQuery<object>(qrystr.Query); ISelectResults<object> results = query.Execute(); int expectedRowCount = qh.IsExpectedRowsConstantRS(qryIdx) ? QueryStatics.ResultSetRowCounts[qryIdx] : QueryStatics.ResultSetRowCounts[qryIdx] * qh.PortfolioNumSets; if (!qh.VerifyRS(results, expectedRowCount)) { ErrorOccurred = true; Util.Log("Query verify failed for query index {0}.", qryIdx); qryIdx++; continue; } ResultSet<object> rs = results as ResultSet<object>; foreach (object item in rs) { if (!m_isPdx) { Portfolio port = item as Portfolio; if (port == null) { Position pos = item as Position; if (pos == null) { string cs = item.ToString(); if (cs == null) { Util.Log("Query got other/unknown object."); } else { Util.Log("Query got string : {0}.", cs); } } else { Util.Log("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding); } } else { Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid); } } else { PortfolioPdx port = item as PortfolioPdx; if (port == null) { PositionPdx pos = item as PositionPdx; if (pos == null) { string cs = item.ToString(); if (cs == null) { Util.Log("Query got other/unknown object."); } else { Util.Log("Query got string : {0}.", cs); } } else { Util.Log("Query got Position object with secId {0}, shares {1}.", pos.secId, pos.getSharesOutstanding); } } else { Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid); } } } qryIdx++; } Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred."); } public void StepFourRS() { bool ErrorOccurred = false; QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService(); int qryIdx = 0; foreach (QueryStrings qrystr in QueryStatics.ResultSetQueries) { if (qrystr.Category != QueryCategory.Unsupported) { qryIdx++; continue; } Util.Log("Evaluating unsupported query index {0}.", qryIdx); Query<object> query = qs.NewQuery<object>(qrystr.Query); try { ISelectResults<object> results = query.Execute(); Util.Log("Query exception did not occur for index {0}.", qryIdx); ErrorOccurred = true; qryIdx++; } catch (GeodeException) { // ok, exception expected, do nothing. qryIdx++; } catch (Exception) { Util.Log("Query unexpected exception occurred for index {0}.", qryIdx); ErrorOccurred = true; qryIdx++; } } Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur."); } public void KillServer() { CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); } public delegate void KillServerDelegate(); #endregion void runRemoteQueryRS() { CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(StepOne, CacheHelper.Locators, m_isPdx); Util.Log("StepOne complete."); m_client1.Call(StepTwo, m_isPdx); Util.Log("StepTwo complete."); m_client1.Call(StepThreeRS); Util.Log("StepThree complete."); m_client1.Call(StepFourRS); Util.Log("StepFour complete."); m_client1.Call(Close); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); } static bool m_isPdx = false; [Test] public void RemoteQueryRSWithPdx() { m_isPdx = true; runRemoteQueryRS(); } [Test] public void RemoteQueryRSWithoutPdx() { m_isPdx = false; runRemoteQueryRS(); } } }
using System; using NUnit.Framework; using Shielded; using System.Threading.Tasks; using System.Linq; using System.Threading; namespace ShieldedTests { [TestFixture] public class PreCommitTests { [Test] public void NoOdds() { var x = new Shielded<int>(); int preCommitFails = 0; // we will not allow any odd number to be committed into x. Shield.PreCommit(() => (x.Value & 1) == 1, () => { Interlocked.Increment(ref preCommitFails); throw new InvalidOperationException(); }); int transactionCount = 0; Task.WaitAll( Enumerable.Range(1, 100).Select(i => Task.Factory.StartNew(() => { try { Shield.InTransaction(() => { Interlocked.Increment(ref transactionCount); int a = x; Thread.Sleep(5); x.Value = a + i; }); } catch (InvalidOperationException) { } }, TaskCreationOptions.LongRunning)).ToArray()); Assert.AreEqual(50, preCommitFails); Assert.AreEqual(2550, x); // just to confirm validity of test! not really a fail if this fails. Assert.Greater(transactionCount, 100); } public class ValidationException : Exception {} [Test] public void Validation() { var list1 = new ShieldedSeq<int>(Enumerable.Range(1, 100).ToArray()); var list2 = new ShieldedSeq<int>(); int validationFails = 0; Shield.PreCommit(() => list1.Count + list2.Count != 100, () => { Interlocked.Increment(ref validationFails); throw new ValidationException(); }); int transactionCount = 0; Task.WaitAll( Enumerable.Range(1, 100).Select(i => Task.Factory.StartNew(() => { try { Shield.InTransaction(() => { Interlocked.Increment(ref transactionCount); int x = list1.TakeHead(); if (i < 100) list2.Append(x); }); Assert.AreNotEqual(100, i); } catch (ValidationException) { Assert.AreEqual(100, i); } }, TaskCreationOptions.LongRunning)).ToArray()); Assert.AreEqual(1, validationFails); Assert.AreEqual(1, list1.Count); Assert.AreEqual(99, list2.Count); } [Test] public void Prioritization() { var x = new Shielded<int>(); var barrier = new Barrier(2); int slowThread1Repeats = 0; var slowThread1 = new Thread(() => { barrier.SignalAndWait(); Shield.InTransaction(() => { Interlocked.Increment(ref slowThread1Repeats); int a = x; Thread.Sleep(100); x.Value = a - 1; }); }); slowThread1.Start(); IDisposable conditional = null; conditional = Shield.Conditional(() => { int i = x; return true; }, () => { barrier.SignalAndWait(); Thread.Yield(); conditional.Dispose(); }); foreach (int i in Enumerable.Range(1, 1000)) { Shield.InTransaction(() => { x.Modify((ref int a) => a++); }); } slowThread1.Join(); Assert.Greater(slowThread1Repeats, 1); Assert.AreEqual(999, x); // now, we introduce prioritization. // this condition gets triggered before any attempt to write into x int ownerThreadId = -1; Shield.PreCommit(() => { int a = x; return true; }, () => { var threadId = ownerThreadId; if (threadId > -1 && threadId != Thread.CurrentThread.ManagedThreadId) // we'll cause lower prio threads to busy wait. we could also // add, e.g., an onRollback SideEffect which would wait for // a certain signal before continuing the next iteration.. // (NB that Shield.SideEffect would, of course, have to be called // before calling Rollback.) Shield.Rollback(); }); // this will pass due to ownerThreadId == -1 Shield.InTransaction(() => x.Value = 0); int slowThread2Repeats = 0; var slowThread2 = new Thread(() => { try { barrier.SignalAndWait(); Interlocked.Exchange(ref ownerThreadId, Thread.CurrentThread.ManagedThreadId); Shield.InTransaction(() => { Interlocked.Increment(ref slowThread2Repeats); int a = x; Thread.Sleep(100); x.Value = a - 1; }); } finally { Interlocked.Exchange(ref ownerThreadId, -1); } }); slowThread2.Start(); conditional = Shield.Conditional(() => { int i = x; return true; }, () => { barrier.SignalAndWait(); conditional.Dispose(); }); foreach (int i in Enumerable.Range(1, 1000)) { Shield.InTransaction(() => { x.Modify((ref int a) => a++); }); } slowThread2.Join(); Assert.AreEqual(1, slowThread2Repeats); Assert.AreEqual(999, x); } [Test] public void CommuteInvariantProblem() { // since pre-commits have no limitations on access, they cannot safely // execute within the commute sub-transaction. if they would, then this // test would fail on the last assertion. instead, pre-commits cause commutes // to degenerate. var testField = new Shielded<int>(); var effectField = new Shielded<int>(); var failCommitCount = new Shielded<int>(); var failVisibleCount = 0; // check if the effect field was written to, that the testField is even. Shield.PreCommit(() => effectField > 0, () => { if ((testField & 1) == 1) { Interlocked.Increment(ref failVisibleCount); // this will always fail to commit, confirming that the transaction // is already bound to fail. but, the failVisibleCount will be >0. failCommitCount.Modify((ref int n) => n++); } }); var thread = new Thread(() => { // if the testField is even, increment the effectField commutatively. foreach (int i in Enumerable.Range(1, 1000)) Shield.InTransaction(() => { if ((testField & 1) == 0) { effectField.Commute((ref int n) => n++); } }); }); thread.Start(); foreach (int i in Enumerable.Range(1, 1000)) Shield.InTransaction(() => { testField.Modify((ref int n) => n++); }); thread.Join(); Assert.AreEqual(0, failCommitCount); Assert.AreEqual(0, failVisibleCount); } } }
// jsvariablefield.cs // // Copyright 2010 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Reflection; namespace Microsoft.Ajax.Utilities { /// <summary> /// Field type enumeration /// </summary> public enum FieldType { Local, Predefined, Global, Arguments, Argument, WithField, CatchError, GhostCatch, GhostFunction, UndefinedGlobal, Super, } public class JSVariableField { private ActivationObject m_owningScope; private HashSet<INameReference> m_referenceTable; private HashSet<INameDeclaration> m_declarationTable; private bool m_canCrunch;// = false; private bool m_isDeclared; //= false; private bool m_isGenerated; private string m_crunchedName;// = null; public Context OriginalContext { get; set; } public string Name { get; private set; } public FieldType FieldType { get; set; } public FieldAttributes Attributes { get; set; } public Object FieldValue { get; set; } public bool IsFunction { get; internal set; } public bool IsAmbiguous { get; set; } public bool IsPlaceholder { get; set; } public bool HasNoReferences { get; set; } public bool InitializationOnly { get; set; } public int Position { get; set; } public bool WasRemoved { get; set; } public bool IsExported { get; set; } public JSVariableField OuterField { get; set; } public ActivationObject OwningScope { get { // but the get -- if we are an inner field, we always // want to get the owning scope of the outer field return OuterField == null ? m_owningScope : OuterField.OwningScope; } set { // simple set -- should always point to the scope in whose // name table this field has been added, which isn't necessarily // the owning scope, because this may be an inner field. But keep // this value in case we ever break the link to the outer field. m_owningScope = value; } } public JSVariableField GhostedField { get; set; } public int RefCount { get { return m_referenceTable.Count; } } public ICollection<INameReference> References { get { return m_referenceTable; } } /// <summary> /// returns the only reference IF there is only ONE reference /// in the collection; otherwise returns false. /// </summary> public INameReference OnlyReference { get { var array = new INameReference[1]; if (m_referenceTable.Count == 1) { m_referenceTable.CopyTo(array, 0); } return array[0]; } } public ICollection<INameDeclaration> Declarations { get { return m_declarationTable; } } /// <summary> /// returns the only declaration IF there is only ONE name declaration /// in the collection; otherwise returns null. /// </summary> public INameDeclaration OnlyDeclaration { get { var array = new INameDeclaration[1]; if (m_declarationTable.Count == 1) { m_declarationTable.CopyTo(array, 0); } return array[0]; } } public bool IsLiteral { get { return ((Attributes & FieldAttributes.Literal) != 0); } } public bool CanCrunch { get { return m_canCrunch; } set { m_canCrunch = value; // if there is an outer field, we only want to propagate // our crunch setting if we are setting it to false. We never // want to set an outer field to true because we might have already // determined that we can't crunch it. if (OuterField != null && !value) { OuterField.CanCrunch = false; } } } public bool IsDeclared { get { return m_isDeclared; } set { m_isDeclared = value; if (OuterField != null) { OuterField.IsDeclared = value; } } } public bool IsGenerated { get { // if we are pointing to an outer field, return ITS flag, not ours return OuterField != null ? OuterField.IsGenerated : m_isGenerated; } set { // always set our flag, just in case m_isGenerated = value; // if we are pointing to an outer field, set it's flag as well if (OuterField != null) { OuterField.IsGenerated = value; } } } public bool IsOuterReference { get { if (this.OuterField != null) { // there is an outer field reference. // go up the chain and make sure that there is a non-placeholder field // somewhere up there. If there is nothing but placeholders (ghosts), then // this is not an outer field. var outerField = this.OuterField; while (outerField != null) { if (!outerField.IsPlaceholder) { // we found an outer field that is not a placeholder, therefore // the original field IS an outer field. return true; } outerField = outerField.OuterField; } } // if we get here, then we didn't find any real (non-placeholder) // outer field, so we are not an outer reference. return false; } } // we'll set this after analyzing all the variables in the // script in order to shrink it down even further public string CrunchedName { get { // return the outer field's crunched name if there is one, // otherwise return ours return (OuterField != null ? OuterField.CrunchedName : m_crunchedName); } set { // only set this if we CAN if (m_canCrunch) { // if this is an outer reference, pass this on to the outer field if (OuterField != null) { OuterField.CrunchedName = value; } else { m_crunchedName = value; } } } } // we'll set this to true if the variable is referenced in a lookup public bool IsReferenced { get { // if the refcount is zero, we know we're not referenced. // if the count is greater than zero and we're a function definition, // then we need to do a little more work var funcObj = FieldValue as FunctionObject; if (funcObj != null) { // ask the function object if it's referenced. return funcObj.IsReferenced; } else if (FieldValue is ClassNode) { // classes are always referenced. For now. return true; } return RefCount > 0; } } /// <summary> /// Gets a value that indicates whether this field is ever referenced in a scope /// other than the one in which it is defined /// </summary> public bool IsReferencedInnerScope { get { // walk the list of references for this field. If any of them // have an outer-field reference, then the reference is an inner reference // and we can return true. foreach (var reference in this.References) { if (reference.VariableField.OuterField != null) { return true; } } // if we get here, all the references (if any) are from within // the same scope as it is defined. return false; } } public JSVariableField(FieldType fieldType, string name, FieldAttributes fieldAttributes, object value) { m_referenceTable = new HashSet<INameReference>(); m_declarationTable = new HashSet<INameDeclaration>(); Name = name; Attributes = fieldAttributes; FieldValue = value; SetFieldsBasedOnType(fieldType); } internal JSVariableField(FieldType fieldType, JSVariableField outerField) { if (outerField == null) { throw new ArgumentNullException("outerField"); } m_referenceTable = new HashSet<INameReference>(); m_declarationTable = new HashSet<INameDeclaration>(); // set values based on the outer field OuterField = outerField; Name = outerField.Name; Attributes = outerField.Attributes; FieldValue = outerField.FieldValue; IsGenerated = outerField.IsGenerated; // and set some other fields on our object based on the type we are SetFieldsBasedOnType(fieldType); } private void SetFieldsBasedOnType(FieldType fieldType) { FieldType = fieldType; switch (FieldType) { case FieldType.Argument: case FieldType.CatchError: IsDeclared = true; CanCrunch = true; break; case FieldType.Arguments: IsDeclared = false; CanCrunch = false; break; case FieldType.Global: case FieldType.Super: case FieldType.WithField: case FieldType.UndefinedGlobal: CanCrunch = false; break; case FieldType.Local: CanCrunch = true; break; case FieldType.Predefined: IsDeclared = false; CanCrunch = false; break; case FieldType.GhostCatch: CanCrunch = true; IsPlaceholder = true; break; case FieldType.GhostFunction: CanCrunch = OuterField == null ? true : OuterField.CanCrunch; IsFunction = true; IsPlaceholder = true; break; default: // shouldn't get here throw new ArgumentException("Invalid field type", "fieldType"); } } public void AddReference(INameReference reference) { if (reference != null) { m_referenceTable.Add(reference); if (this.OuterField != null) { this.OuterField.AddReference(reference); } } } public void AddReferences(IEnumerable<INameReference> references) { if (references != null) { foreach (var reference in references) { AddReference(reference); } } } public void Detach() { OuterField = null; } public override string ToString() { string crunch = CrunchedName; return string.IsNullOrEmpty(crunch) ? Name : crunch; } public override int GetHashCode() { return Name.GetHashCode(); } /// <summary> /// returns true if the fields point to the same ultimate reference object. /// Needs to walk up the outer-reference chain for each field in order to /// find the ultimate reference /// </summary> /// <param name="otherField"></param> /// <returns></returns> public bool IsSameField(JSVariableField otherField) { // shortcuts -- if they are already the same object, we're done; // and if the other field is null, then we are NOT the same object. if (this == otherField) { return true; } else if (otherField == null) { return false; } // get the ultimate field for this field var thisOuter = OuterField != null ? OuterField : this; while (thisOuter.OuterField != null) { thisOuter = thisOuter.OuterField; } // get the ultimate field for the other field var otherOuter = otherField.OuterField != null ? otherField.OuterField : otherField; while (otherOuter.OuterField != null) { otherOuter = otherOuter.OuterField; } // now that we have the same outer fields, check to see if they are the same return thisOuter == otherOuter; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using appveyortest.Areas.HelpPage.ModelDescriptions; using appveyortest.Areas.HelpPage.Models; namespace appveyortest.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // using System.Diagnostics; using System.IO; using System.Xml; using System.Xml.Serialization; namespace nanoFramework.Tools.VisualStudio.Extension { public class Pdbx { public class TokenMap { uint StringToUInt32(string s) { s.Trim(); if (s.StartsWith("0x")) s = s.Remove(0, 2); return uint.Parse(s, System.Globalization.NumberStyles.HexNumber); } string UInt32ToString(uint u) { return "0x" + u.ToString("X"); } [XmlIgnore]public uint CLR; [XmlIgnore]public uint nanoCLR; [XmlElement("CLR")] public string CLR_String { get {return UInt32ToString(CLR);} set {CLR = StringToUInt32(value);} } [XmlElement("nanoCLR")] public string nanoCLR_String { get {return UInt32ToString(nanoCLR);} set {nanoCLR = StringToUInt32(value);} } } public class Token : TokenMap { } public class IL : TokenMap { } public class ClassMember { public Token Token; [XmlIgnore]public Class Class; } public class Method : ClassMember { public bool HasByteCode = true; public IL[] ILMap; private bool m_fIsJMC; [XmlIgnore] public bool IsJMC { get { return m_fIsJMC; } set { if (CanSetJMC) m_fIsJMC = value; } } public bool CanSetJMC { get { return this.HasByteCode; } } } public class Field : ClassMember { } public class Class { public Token Token; public Field[] Fields; public Method[] Methods; [XmlIgnore]public Assembly Assembly; } public class Assembly /*Module*/ { public struct VersionStruct { public ushort Major; public ushort Minor; public ushort Build; public ushort Revision; } public string FileName; public VersionStruct Version; public Token Token; public Class[] Classes; [XmlIgnore]public CorDebugAssembly CorDebugAssembly; } public class PdbxFile { public class Resolver { private string[] _assemblyPaths; private string[] _assemblyDirectories; public string[] AssemblyPaths { get { return _assemblyPaths; } set { _assemblyPaths = value; } } public string[] AssemblyDirectories { get {return _assemblyDirectories;} set {_assemblyDirectories = value;} } public PdbxFile Resolve(string name, Tools.Debugger.WireProtocol.Commands.DebuggingResolveAssembly.Version version, bool fIsTargetBigEndian) { PdbxFile file = PdbxFile.Open(name, version, _assemblyPaths, _assemblyDirectories, fIsTargetBigEndian); return file; } } public Assembly Assembly; [XmlIgnore]public string PdbxPath; private static PdbxFile TryPdbxFile(string path, Tools.Debugger.WireProtocol.Commands.DebuggingResolveAssembly.Version version) { try { path += ".pdbx"; if (File.Exists(path)) { XmlSerializer xmls = new Serialization.PdbxFile.PdbxFileSerializer(); PdbxFile file = (PdbxFile)Utility.XmlDeserialize(path, xmls); //Check version Assembly.VersionStruct version2 = file.Assembly.Version; if (version2.Major == version.MajorVersion && version2.Minor == version.MinorVersion) { file.Initialize(path); return file; } } } catch { } return null; } private static PdbxFile OpenHelper(string name, Tools.Debugger.WireProtocol.Commands.DebuggingResolveAssembly.Version version, string[] assemblyDirectories, string directorySuffix) { PdbxFile file = null; for (int iDirectory = 0; iDirectory < assemblyDirectories.Length; iDirectory++) { string directory = assemblyDirectories[iDirectory]; if(!string.IsNullOrEmpty(directorySuffix)) { directory = Path.Combine(directory, directorySuffix); } string pathNoExt = Path.Combine(directory, name); if ((file = TryPdbxFile(pathNoExt, version)) != null) break; } return file; } private static PdbxFile Open(string name, Tools.Debugger.WireProtocol.Commands.DebuggingResolveAssembly.Version version, string[] assemblyPaths, string[] assemblyDirectories, bool fIsTargetBigEndian) { PdbxFile file = null; if (assemblyPaths != null) { for(int iPath = 0; iPath < assemblyPaths.Length; iPath++) { string path = assemblyPaths[iPath]; string pathNoExt = Path.ChangeExtension(path, null); if (0 == string.Compare(name, Path.GetFileName(pathNoExt), true)) { if ((file = TryPdbxFile(pathNoExt, version)) != null) break; } } } if (file == null && assemblyDirectories != null) { file = OpenHelper(name, version, assemblyDirectories, null); if (file == null) { if (fIsTargetBigEndian) { file = OpenHelper(name, version, assemblyDirectories, @"..\pe\be"); if (file == null) { file = OpenHelper(name, version, assemblyDirectories, @"be"); } } else { file = OpenHelper(name, version, assemblyDirectories, @"..\pe\le"); if (file == null) { file = OpenHelper(name, version, assemblyDirectories, @"le"); } } } } //Try other paths here... return file; } private void Initialize(string path) { this.PdbxPath = path; for(int iClass = 0; iClass < this.Assembly.Classes.Length; iClass++) { Class c = this.Assembly.Classes[iClass]; c.Assembly = this.Assembly; for(int iMethod = 0; iMethod < c.Methods.Length; iMethod++) { Method m = c.Methods[iMethod]; m.Class = c; #if DEBUG for (int iIL = 0; iIL < m.ILMap.Length - 1; iIL++) { Debug.Assert(m.ILMap[iIL].CLR < m.ILMap[iIL + 1].CLR); Debug.Assert(m.ILMap[iIL].nanoCLR < m.ILMap[iIL + 1].nanoCLR); } #endif } foreach (Field f in c.Fields) { f.Class = c; } } } /// Format of the Pdbx file /// ///<Pdbx> /// <dat> /// <filename>NAME</filename> /// </dat> /// <assemblies> /// <assembly> /// <name>NAME</name> /// <version> /// <Major>1</Major> /// <Minor>2</Minor> /// <Build>3</Build> /// <Revision>4</Revision> /// </version> /// <token> /// <CLR>TOKEN</CLR> /// <nanoCLR>TOKEN</nanoCLR> /// </token> /// <classes> /// <class> /// <name>NAME</name> /// <fields> /// <field> /// <token></token> /// </field> /// </fields> /// <methods> /// <method> /// <token></token> /// <ILMap> /// <IL> /// <CLR>IL</CLR> /// <nanoCLR>IL</nanoCLR> /// </IL> /// </ILMap> /// </method> /// </methods> /// </class> /// </classes> /// </assembly> /// </assemblies> ///</Pdbx> /// /// } } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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. #endregion // License using Bam.Core; using QtCommon.UicExtension; using System.Linq; namespace Qt5Test4 { sealed class Qt5Application : C.Cxx.GUIApplication { protected override void Init() { base.Init(); var source = this.CreateCxxSourceCollection("$(packagedir)/source/*.cpp"); var headers = this.CreateHeaderCollection(); var uiResources = this.CreateUicCollection("$(packagedir)/resources/*.ui"); foreach (var uiFile in uiResources.Children) { var uicGeneratedHeader = headers.Uic(uiFile); source.DependsOn(uicGeneratedHeader); // must be generated first source.PrivatePatch(settings => { var preprocessor = settings as C.ICommonPreprocessorSettings; preprocessor.IncludePaths.AddUnique( this.CreateTokenizedString( "@dir($(0))", new[] { uicGeneratedHeader.GeneratedPaths[C.HeaderFile.HeaderFileKey]} ) ); }); } source.PrivatePatch(settings => { if (settings is GccCommon.ICommonCompilerSettings gccCompiler) { // because Qt5.6.0/5.6/gcc_64/include/QtCore/qglobal.h:1090:4: error: #error "You must build your code with position independent code if Qt was built with -reduce-relocations. " "Compile your code with -fPIC (-fPIE is not enough)." gccCompiler.PositionIndependentCode = true; } if (settings is VisualCCommon.ICommonCompilerSettings vcCompiler) { if (source.Compiler.Version.AtLeast(VisualCCommon.ToolchainVersion.VC2015)) { var cxxCompiler = settings as C.ICxxOnlyCompilerSettings; cxxCompiler.ExceptionHandler = C.Cxx.EExceptionHandler.Synchronous; // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\iosfwd(343): warning C4577: 'noexcept' used with no exception handling mode specified; termination on exception is not guaranteed. Specify /EHsc } } }); this.PrivatePatch(settings => { if (settings is GccCommon.ICommonLinkerSettings gccLinker) { gccLinker.CanUseOrigin = true; gccLinker.RPath.AddUnique("$ORIGIN/../lib"); } if (settings is ClangCommon.ICommonLinkerSettings clangLinker) { clangLinker.RPath.AddUnique("@executable_path/../Frameworks"); } }); if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.OSX)) { this.CompileAndLinkAgainst<Qt.CoreFramework>(source); this.CompileAndLinkAgainst<Qt.WidgetsFramework>(source); this.CompileAndLinkAgainst<Qt.GuiFramework>(source); } else { this.CompileAndLinkAgainst<Qt.Core>(source); this.CompileAndLinkAgainst<Qt.Widgets>(source); this.CompileAndLinkAgainst<Qt.Gui>(source); } if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { this.CreateWinResourceCollection("$(packagedir)/resources/*.rc"); } } } sealed class Qt5Test4Runtime : Publisher.Collation { protected override void Init() { base.Init(); this.SetDefaultMacrosAndMappings(EPublishingType.WindowedApplication); var appAnchor = this.Include<Qt5Application>(C.Cxx.GUIApplication.ExecutableKey); var qtPlatformPlugin = this.Find<QtCommon.PlatformPlugin>().First(); (qtPlatformPlugin as Publisher.CollatedObject).SetPublishingDirectory("$(0)/platforms", this.PluginDir); if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.OSX)) { var collatedQtFrameworks = this.Find<QtCommon.CommonFramework>(); collatedQtFrameworks.ToList().ForEach(collatedFramework => // must be a public patch in order for the stripping mode to inherit the settings (collatedFramework as Publisher.CollatedObject).PublicPatch((settings, appliedTo) => { var rsyncSettings = settings as Publisher.IRsyncSettings; rsyncSettings.Exclusions = (collatedFramework.SourceModule as QtCommon.CommonFramework).PublishingExclusions; })); this.IncludeFiles( this.CreateTokenizedString("$(packagedir)/resources/osx/qt.conf"), this.Macros["macOSAppBundleResourcesDir"], appAnchor); } else if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Linux)) { this.IncludeFiles( this.CreateTokenizedString("$(packagedir)/resources/linux/qt.conf"), this.ExecutableDir, appAnchor); } else if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { this.IncludeFiles( this.CreateTokenizedString("$(packagedir)/resources/windows/qt.conf"), this.ExecutableDir, appAnchor); var app = appAnchor.SourceModule as Qt5Application; if (this.BuildEnvironment.Configuration != EConfiguration.Debug && app.Linker is VisualCCommon.LinkerBase) { var runtimeLibrary = Bam.Core.Graph.Instance.PackageMetaData<VisualCCommon.IRuntimeLibraryPathMeta>("VisualC"); this.IncludeFiles(runtimeLibrary.CRuntimePaths(app.BitDepth), this.ExecutableDir, appAnchor); this.IncludeFiles(runtimeLibrary.CxxRuntimePaths(app.BitDepth), this.ExecutableDir, appAnchor); } } else { throw new Bam.Core.Exception("Unknown platform"); } } } [Bam.Core.ConfigurationFilter(Bam.Core.EConfiguration.NotDebug)] sealed class Qt5Test4DebugSymbols : Publisher.DebugSymbolCollation { protected override void Init() { base.Init(); this.CreateSymbolsFrom<Qt5Test4Runtime>(); } } [Bam.Core.ConfigurationFilter(Bam.Core.EConfiguration.NotDebug)] sealed class Qt5Test4Stripped : Publisher.StrippedBinaryCollation { protected override void Init() { base.Init(); this.StripBinariesFrom<Qt5Test4Runtime, Qt5Test4DebugSymbols>(); } } [Bam.Core.ConfigurationFilter(Bam.Core.EConfiguration.NotDebug)] sealed class TarBallInstaller : Installer.TarBall { protected override void Init() { base.Init(); this.SourceFolder<Qt5Test4Stripped>(Publisher.StrippedBinaryCollation.StripBinaryDirectoryKey); } } }
/* ==================================================================== 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 TestCases.HSSF.UserModel { using System; using System.IO; using System.Collections; using TestCases.HSSF; using NPOI.HSSF.Model; using NPOI.HSSF.Record; using NPOI.SS.Formula; using NPOI.Util; using NPOI.HSSF.UserModel; using NUnit.Framework; using NPOI.DDF; using TestCases.SS.UserModel; using NPOI.SS.Formula.PTG; using NPOI.SS.UserModel; using NPOI.POIFS.FileSystem; using NPOI.SS.Util; using System.Collections.Generic; using System.Text; using NPOI.HSSF; using System.Threading; using System.Globalization; using NPOI.SS; /** * */ [TestFixture] public class TestHSSFWorkbook : BaseTestWorkbook { public TestHSSFWorkbook() : base(HSSFITestDataProvider.Instance) { } /** * gives test code access to the {@link InternalWorkbook} within {@link HSSFWorkbook} */ public static InternalWorkbook GetInternalWorkbook(HSSFWorkbook wb) { return wb.Workbook; } private static HSSFWorkbook OpenSample(String sampleFileName) { return HSSFTestDataSamples.OpenSampleWorkbook(sampleFileName); } /** * Tests for {@link HSSFWorkbook#isHidden()} etc * @throws IOException */ [Test] public void Hidden() { HSSFWorkbook wb = new HSSFWorkbook(); WindowOneRecord w1 = wb.Workbook.WindowOne; Assert.AreEqual(false, wb.IsHidden); Assert.AreEqual(false, w1.Hidden); wb.IsHidden = (true); Assert.AreEqual(true, wb.IsHidden); Assert.AreEqual(true, w1.Hidden); HSSFWorkbook wbBack = HSSFTestDataSamples.WriteOutAndReadBack(wb); w1 = wbBack.Workbook.WindowOne; wbBack.IsHidden = (true); Assert.AreEqual(true, wbBack.IsHidden); Assert.AreEqual(true, w1.Hidden); wbBack.IsHidden = (false); Assert.AreEqual(false, wbBack.IsHidden); Assert.AreEqual(false, w1.Hidden); wbBack.Close(); wb.Close(); } [Test] [Ignore("not found in poi")] public void CaseInsensitiveNames() { HSSFWorkbook b = new HSSFWorkbook(); ISheet originalSheet = b.CreateSheet("Sheet1"); ISheet fetchedSheet = b.GetSheet("sheet1"); if (fetchedSheet == null) { throw new AssertionException("Identified bug 44892"); } Assert.AreEqual(originalSheet, fetchedSheet); try { b.CreateSheet("sHeeT1"); Assert.Fail("should have thrown exceptiuon due to duplicate sheet name"); } catch (ArgumentException e) { // expected during successful Test Assert.AreEqual("The workbook already contains a sheet of this name", e.Message); } } [Test] [Ignore("not found in poi")] public void DuplicateNames() { HSSFWorkbook b = new HSSFWorkbook(); b.CreateSheet("Sheet1"); b.CreateSheet(); b.CreateSheet("name1"); try { b.CreateSheet("name1"); Assert.Fail(); } catch (ArgumentException)// pass { } b.CreateSheet(); try { b.SetSheetName(3, "name1"); Assert.Fail(); } catch (ArgumentException)// pass { } try { b.SetSheetName(3, "name1"); Assert.Fail(); } catch (ArgumentException)// pass { } b.SetSheetName(3, "name2"); b.SetSheetName(3, "name2"); b.SetSheetName(3, "name2"); HSSFWorkbook c = new HSSFWorkbook(); c.CreateSheet("Sheet1"); c.CreateSheet("Sheet2"); c.CreateSheet("Sheet3"); c.CreateSheet("Sheet4"); } [Test] [Ignore("not found in poi")] public new void TestSheetSelection() { HSSFWorkbook b = new HSSFWorkbook(); b.CreateSheet("Sheet One"); b.CreateSheet("Sheet Two"); b.SetActiveSheet(1); b.SetSelectedTab(1); b.FirstVisibleTab = (1); Assert.AreEqual(1, b.ActiveSheetIndex); Assert.AreEqual(1, b.FirstVisibleTab); } [Test] public void ReadWriteWithCharts() { ISheet s; // Single chart, two sheets HSSFWorkbook b1 = HSSFTestDataSamples.OpenSampleWorkbook("44010-SingleChart.xls"); Assert.AreEqual(2, b1.NumberOfSheets); Assert.AreEqual("Graph2", b1.GetSheetName(1)); s = b1.GetSheetAt(1); Assert.AreEqual(0, s.FirstRowNum); Assert.AreEqual(8, s.LastRowNum); // Has chart on 1st sheet?? // FIXME Assert.IsNotNull(b1.GetSheetAt(0).DrawingPatriarch); Assert.IsNull(b1.GetSheetAt(1).DrawingPatriarch); Assert.IsFalse((b1.GetSheetAt(0).DrawingPatriarch as HSSFPatriarch).ContainsChart()); b1.Close(); // We've now called getDrawingPatriarch() so // everything will be all screwy // So, start again HSSFWorkbook b2 = HSSFTestDataSamples.OpenSampleWorkbook("44010-SingleChart.xls"); HSSFWorkbook b3 = HSSFTestDataSamples.WriteOutAndReadBack(b2); b2.Close(); Assert.AreEqual(2, b3.NumberOfSheets); s = b3.GetSheetAt(1) as HSSFSheet; Assert.AreEqual(0, s.FirstRowNum); Assert.AreEqual(8, s.LastRowNum); b3.Close(); // Two charts, three sheets HSSFWorkbook b4 = HSSFTestDataSamples.OpenSampleWorkbook("44010-TwoCharts.xls"); Assert.AreEqual(3, b4.NumberOfSheets); s = b4.GetSheetAt(1) as HSSFSheet; Assert.AreEqual(0, s.FirstRowNum); Assert.AreEqual(8, s.LastRowNum); s = b4.GetSheetAt(2) as HSSFSheet; Assert.AreEqual(0, s.FirstRowNum); Assert.AreEqual(8, s.LastRowNum); // Has chart on 1st sheet?? // FIXME Assert.IsNotNull(b4.GetSheetAt(0).DrawingPatriarch); Assert.IsNull(b4.GetSheetAt(1).DrawingPatriarch); Assert.IsNull(b4.GetSheetAt(2).DrawingPatriarch); Assert.IsFalse((b4.GetSheetAt(0).DrawingPatriarch as HSSFPatriarch).ContainsChart()); b4.Close(); // We've now called getDrawingPatriarch() so // everything will be all screwy // So, start again HSSFWorkbook b5 = HSSFTestDataSamples.OpenSampleWorkbook("44010-TwoCharts.xls"); HSSFWorkbook b6 = HSSFTestDataSamples.WriteOutAndReadBack(b5); b5.Close(); Assert.AreEqual(3, b6.NumberOfSheets); s = b6.GetSheetAt(1) as HSSFSheet; Assert.AreEqual(0, s.FirstRowNum); Assert.AreEqual(8, s.LastRowNum); s = b6.GetSheetAt(2) as HSSFSheet; Assert.AreEqual(0, s.FirstRowNum); Assert.AreEqual(8, s.LastRowNum); b6.Close(); } private static HSSFWorkbook WriteRead(HSSFWorkbook b) { return HSSFTestDataSamples.WriteOutAndReadBack(b); } [Test] public void SelectedSheet_bug44523() { HSSFWorkbook wb = new HSSFWorkbook(); ISheet sheet1 = wb.CreateSheet("Sheet1"); ISheet sheet2 = wb.CreateSheet("Sheet2"); ISheet sheet3 = wb.CreateSheet("Sheet3"); ISheet sheet4 = wb.CreateSheet("Sheet4"); ConfirmActiveSelected(sheet1, true); ConfirmActiveSelected(sheet2, false); ConfirmActiveSelected(sheet3, false); ConfirmActiveSelected(sheet4, false); wb.SetSelectedTab(1); // Demonstrate bug 44525: // Well... not quite, since isActive + isSelected were also Added in the same bug fix if (sheet1.IsSelected) { throw new AssertionException("Identified bug 44523 a"); } wb.SetActiveSheet(1); if (sheet1.IsActive) { throw new AssertionException("Identified bug 44523 b"); } ConfirmActiveSelected(sheet1, false); ConfirmActiveSelected(sheet2, true); ConfirmActiveSelected(sheet3, false); ConfirmActiveSelected(sheet4, false); } private static List<int> arrayToList(int[] array) { List<int> list = new List<int>(array.Length); foreach (int element in array) { list.Add(element); } return list; } private static void assertCollectionsEquals(List<int> expected, List<int> actual) { Assert.AreEqual(expected.Count, actual.Count, "size"); foreach (int e in expected) { Assert.IsTrue(actual.Contains(e)); } foreach (int a in actual) { Assert.IsTrue(expected.Contains(a)); } } [Test] public void SelectMultiple() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet0 = wb.CreateSheet("Sheet0") as HSSFSheet; HSSFSheet sheet1 = wb.CreateSheet("Sheet1") as HSSFSheet; HSSFSheet sheet2 = wb.CreateSheet("Sheet2") as HSSFSheet; HSSFSheet sheet3 = wb.CreateSheet("Sheet3") as HSSFSheet; HSSFSheet sheet4 = wb.CreateSheet("Sheet4") as HSSFSheet; HSSFSheet sheet5 = wb.CreateSheet("Sheet5") as HSSFSheet; List<int> selected = arrayToList(new int[] { 0, 2, 3 }); wb.SetSelectedTabs(selected); CollectionAssert.AreEqual(selected, wb.GetSelectedTabs()); Assert.AreEqual(true, sheet0.IsSelected); Assert.AreEqual(false, sheet1.IsSelected); Assert.AreEqual(true, sheet2.IsSelected); Assert.AreEqual(true, sheet3.IsSelected); Assert.AreEqual(false, sheet4.IsSelected); Assert.AreEqual(false, sheet5.IsSelected); selected = arrayToList(new int[] { 1, 3, 5 }); wb.SetSelectedTabs(selected); // previous selection should be cleared CollectionAssert.AreEqual(selected, wb.GetSelectedTabs()); Assert.AreEqual(false, sheet0.IsSelected); Assert.AreEqual(true, sheet1.IsSelected); Assert.AreEqual(false, sheet2.IsSelected); Assert.AreEqual(true, sheet3.IsSelected); Assert.AreEqual(false, sheet4.IsSelected); Assert.AreEqual(true, sheet5.IsSelected); Assert.AreEqual(true, sheet0.IsActive); Assert.AreEqual(false, sheet2.IsActive); wb.SetActiveSheet(2); Assert.AreEqual(false, sheet0.IsActive); Assert.AreEqual(true, sheet2.IsActive); /*{ // helpful if viewing this workbook in excel: sheet0.createRow(0).createCell(0).setCellValue(new HSSFRichTextString("Sheet0")); sheet1.CreateRow(0).CreateCell(0).SetCellValue(new HSSFRichTextString("Sheet1")); sheet2.CreateRow(0).CreateCell(0).SetCellValue(new HSSFRichTextString("Sheet2")); sheet3.CreateRow(0).CreateCell(0).SetCellValue(new HSSFRichTextString("Sheet3")); try { File fOut = TempFile.CreateTempFile("sheetMultiSelect", ".xls"); FileOutputStream os = new FileOutputStream(fOut); wb.Write(os); os.Close(); } catch (IOException e) { throw new RuntimeException(e); } }*/ } [Test] public void ActiveSheetAfterDelete_bug40414() { HSSFWorkbook wb = new HSSFWorkbook(); ISheet sheet0 = wb.CreateSheet("Sheet0"); ISheet sheet1 = wb.CreateSheet("Sheet1"); ISheet sheet2 = wb.CreateSheet("Sheet2"); ISheet sheet3 = wb.CreateSheet("Sheet3"); ISheet sheet4 = wb.CreateSheet("Sheet4"); // Confirm default activation/selection ConfirmActiveSelected(sheet0, true); ConfirmActiveSelected(sheet1, false); ConfirmActiveSelected(sheet2, false); ConfirmActiveSelected(sheet3, false); ConfirmActiveSelected(sheet4, false); wb.SetActiveSheet(3); wb.SetSelectedTab(3); ConfirmActiveSelected(sheet0, false); ConfirmActiveSelected(sheet1, false); ConfirmActiveSelected(sheet2, false); ConfirmActiveSelected(sheet3, true); ConfirmActiveSelected(sheet4, false); wb.RemoveSheetAt(3); // after removing the only active/selected sheet, another should be active/selected in its place if (!sheet4.IsSelected) { throw new AssertionException("identified bug 40414 a"); } if (!sheet4.IsActive) { throw new AssertionException("identified bug 40414 b"); } ConfirmActiveSelected(sheet0, false); ConfirmActiveSelected(sheet1, false); ConfirmActiveSelected(sheet2, false); ConfirmActiveSelected(sheet4, true); sheet3 = sheet4; // re-align local vars in this Test case // Some more cases of removing sheets // Starting with a multiple selection, and different active sheet wb.SetSelectedTabs(new int[] { 1, 3, }); wb.SetActiveSheet(2); ConfirmActiveSelected(sheet0, false, false); ConfirmActiveSelected(sheet1, false, true); ConfirmActiveSelected(sheet2, true, false); ConfirmActiveSelected(sheet3, false, true); // removing a sheet that is not active, and not the only selected sheet wb.RemoveSheetAt(3); ConfirmActiveSelected(sheet0, false, false); ConfirmActiveSelected(sheet1, false, true); ConfirmActiveSelected(sheet2, true, false); // removing the only selected sheet wb.RemoveSheetAt(1); ConfirmActiveSelected(sheet0, false, false); ConfirmActiveSelected(sheet2, true, true); // The last remaining sheet should always be active+selected wb.RemoveSheetAt(1); ConfirmActiveSelected(sheet0, true, true); } private static void ConfirmActiveSelected(ISheet sheet, bool expected) { ConfirmActiveSelected(sheet, expected, expected); } private static void ConfirmActiveSelected(ISheet sheet, bool expectedActive, bool expectedSelected) { Assert.AreEqual(expectedActive, sheet.IsActive, "active"); Assert.AreEqual(expectedSelected, sheet.IsSelected, "selected"); } /** * If Sheet.GetSize() returns a different result to Sheet.serialize(), this will cause the BOF * records to be written with invalid offset indexes. Excel does not like this, and such * errors are particularly hard to track down. This Test ensures that HSSFWorkbook throws * a specific exception as soon as the situation is detected. See bugzilla 45066 */ [Test] public void SheetSerializeSizeMisMatch_bug45066() { HSSFWorkbook wb = new HSSFWorkbook(); InternalSheet sheet = ((HSSFSheet)wb.CreateSheet("Sheet1")).Sheet; IList sheetRecords = sheet.Records; // one way (of many) to cause the discrepancy is with a badly behaved record: sheetRecords.Add(new BadlyBehavedRecord()); // There is also much logic inside Sheet that (if buggy) might also cause the discrepancy try { wb.GetBytes(); throw new AssertionException("Identified bug 45066 a"); } catch (InvalidOperationException e) { // Expected badly behaved sheet record to cause exception Assert.IsTrue(e.Message.StartsWith("Actual serialized sheet size")); } } /** * Checks that us and IName play nicely with named ranges * that point to deleted sheets */ [Test] public void NamesToDeleteSheets() { HSSFWorkbook b = OpenSample("30978-deleted.xls"); Assert.AreEqual(3, b.NumberOfNames); // Sheet 2 is deleted Assert.AreEqual("Sheet1", b.GetSheetName(0)); Assert.AreEqual("Sheet3", b.GetSheetName(1)); Area3DPtg ptg; NameRecord nr; IName n; /* ======= Name pointing to deleted sheet ====== */ // First at low level nr = b.Workbook.GetNameRecord(0); Assert.AreEqual("On2", nr.NameText); Assert.AreEqual(0, nr.SheetNumber); Assert.AreEqual(1, nr.ExternSheetNumber); Assert.AreEqual(1, nr.NameDefinition.Length); ptg = (Area3DPtg)nr.NameDefinition[0]; Assert.AreEqual(1, ptg.ExternSheetIndex); Assert.AreEqual(0, ptg.FirstColumn); Assert.AreEqual(0, ptg.FirstRow); Assert.AreEqual(0, ptg.LastColumn); Assert.AreEqual(2, ptg.LastRow); // Now at high level n = b.GetNameAt(0); Assert.AreEqual("On2", n.NameName); Assert.AreEqual("", n.SheetName); Assert.AreEqual("#REF!$A$1:$A$3", n.RefersToFormula); /* ======= Name pointing to 1st sheet ====== */ // First at low level nr = b.Workbook.GetNameRecord(1); Assert.AreEqual("OnOne", nr.NameText); Assert.AreEqual(0, nr.SheetNumber); Assert.AreEqual(0, nr.ExternSheetNumber); Assert.AreEqual(1, nr.NameDefinition.Length); ptg = (Area3DPtg)nr.NameDefinition[0]; Assert.AreEqual(0, ptg.ExternSheetIndex); Assert.AreEqual(0, ptg.FirstColumn); Assert.AreEqual(2, ptg.FirstRow); Assert.AreEqual(0, ptg.LastColumn); Assert.AreEqual(3, ptg.LastRow); // Now at high level n = b.GetNameAt(1); Assert.AreEqual("OnOne", n.NameName); Assert.AreEqual("Sheet1", n.SheetName); Assert.AreEqual("Sheet1!$A$3:$A$4", n.RefersToFormula); /* ======= Name pointing to 3rd sheet ====== */ // First at low level nr = b.Workbook.GetNameRecord(2); Assert.AreEqual("OnSheet3", nr.NameText); Assert.AreEqual(0, nr.SheetNumber); Assert.AreEqual(2, nr.ExternSheetNumber); Assert.AreEqual(1, nr.NameDefinition.Length); ptg = (Area3DPtg)nr.NameDefinition[0]; Assert.AreEqual(2, ptg.ExternSheetIndex); Assert.AreEqual(0, ptg.FirstColumn); Assert.AreEqual(0, ptg.FirstRow); Assert.AreEqual(0, ptg.LastColumn); Assert.AreEqual(1, ptg.LastRow); // Now at high level n = b.GetNameAt(2); Assert.AreEqual("OnSheet3", n.NameName); Assert.AreEqual("Sheet3", n.SheetName); Assert.AreEqual("Sheet3!$A$1:$A$2", n.RefersToFormula); b.Close(); } /** * result returned by getRecordSize() differs from result returned by serialize() */ private class BadlyBehavedRecord : Record { public BadlyBehavedRecord() { // } public override short Sid { get { return unchecked((short)0x777); } } public override int Serialize(int offset, byte[] data) { return 4; } public override int RecordSize { get { return 8; } } } /** * The sample file provided with bug 45582 seems to have one extra byte after the EOFRecord */ [Test] public void ExtraDataAfterEOFRecord() { try { HSSFTestDataSamples.OpenSampleWorkbook("ex45582-22397.xls"); } catch (RecordFormatException e) { if (e.InnerException is NPOI.Util.BufferUnderrunException) { throw new AssertionException("Identified bug 45582"); } } } /** * Test to make sure that NameRecord.SheetNumber is interpreted as a * 1-based sheet tab index (not a 1-based extern sheet index) */ [Test] public void FindBuiltInNameRecord() { // TestRRaC has multiple (3) built-in name records // The second print titles name record has SheetNumber==4 HSSFWorkbook wb1 = HSSFTestDataSamples.OpenSampleWorkbook("TestRRaC.xls"); NameRecord nr; Assert.AreEqual(3, wb1.Workbook.NumNames); nr = wb1.Workbook.GetNameRecord(2); // TODO - render full row and full column refs properly Assert.AreEqual("Sheet2!$A$1:$IV$1", HSSFFormulaParser.ToFormulaString(wb1, nr.NameDefinition)); // 1:1 try { wb1.GetSheetAt(3).RepeatingRows = (CellRangeAddress.ValueOf("9:12")); wb1.GetSheetAt(3).RepeatingColumns = (CellRangeAddress.ValueOf("E:F")); } catch (Exception e) { if (e.Message.Equals("Builtin (7) already exists for sheet (4)")) { // there was a problem in the code which locates the existing print titles name record throw new Exception("Identified bug 45720b"); } throw e; } HSSFWorkbook wb2 = HSSFTestDataSamples.WriteOutAndReadBack(wb1); wb1.Close(); Assert.AreEqual(3, wb2.Workbook.NumNames); nr = wb2.Workbook.GetNameRecord(2); Assert.AreEqual("Sheet2!E:F,Sheet2!$A$9:$IV$12", HSSFFormulaParser.ToFormulaString(wb2, nr.NameDefinition)); // E:F,9:12 wb2.Close(); } /** * Test that the storage clsid property is preserved */ [Test] public void Bug47920() { POIFSFileSystem fs1 = new POIFSFileSystem(POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("47920.xls")); IWorkbook wb = new HSSFWorkbook(fs1); ClassID clsid1 = fs1.Root.StorageClsid; MemoryStream out1 = new MemoryStream(4096); wb.Write(out1); byte[] bytes = out1.ToArray(); POIFSFileSystem fs2 = new POIFSFileSystem(new MemoryStream(bytes)); ClassID clsid2 = fs2.Root.StorageClsid; Assert.IsTrue(clsid1.Equals(clsid2)); fs2.Close(); wb.Close(); fs1.Close(); } /** * If we try to open an old (pre-97) workbook, we Get a helpful * Exception give to explain what we've done wrong */ [Test] public void HelpfulExceptionOnOldFiles() { Stream excel4 = POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("testEXCEL_4.xls"); try { new HSSFWorkbook(excel4); Assert.Fail("Shouldn't be able to load an Excel 4 file"); } catch (OldExcelFormatException e) { POITestCase.AssertContains(e.Message, "BIFF4"); } excel4.Close(); Stream excel5 = POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("testEXCEL_5.xls"); try { new HSSFWorkbook(excel5); Assert.Fail("Shouldn't be able to load an Excel 5 file"); } catch (OldExcelFormatException e) { POITestCase.AssertContains(e.Message, "BIFF8"); } excel5.Close(); Stream excel95 = POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("testEXCEL_95.xls"); try { new HSSFWorkbook(excel95); Assert.Fail("Shouldn't be able to load an Excel 95 file"); } catch (OldExcelFormatException e) { POITestCase.AssertContains(e.Message, "BIFF5"); } excel95.Close(); } /** * Tests that we can work with both {@link POIFSFileSystem} * and {@link NPOIFSFileSystem} */ [Test] public void DifferentPOIFS() { //throw new NotImplementedException("class NPOIFSFileSystem is not implemented"); // Open the two filesystems DirectoryNode[] files = new DirectoryNode[2]; files[0] = (new POIFSFileSystem(HSSFTestDataSamples.OpenSampleFileStream("Simple.xls"))).Root; files[1] = (new NPOIFSFileSystem(HSSFTestDataSamples.OpenSampleFileStream("Simple.xls"))).Root; // Open without preserving nodes foreach (DirectoryNode dir in files) { IWorkbook workbook = new HSSFWorkbook(dir, false); ISheet sheet = workbook.GetSheetAt(0); ICell cell = sheet.GetRow(0).GetCell(0); Assert.AreEqual("replaceMe", cell.RichStringCellValue.String); } // Now re-check with preserving foreach (DirectoryNode dir in files) { IWorkbook workbook = new HSSFWorkbook(dir, true); ISheet sheet = workbook.GetSheetAt(0); ICell cell = sheet.GetRow(0).GetCell(0); Assert.AreEqual("replaceMe", cell.RichStringCellValue.String); } } [Test] public void WordDocEmbeddedInXls() { //throw new NotImplementedException("class NPOIFSFileSystem is not implemented"); // Open the two filesystems DirectoryNode[] files = new DirectoryNode[2]; files[0] = (new POIFSFileSystem(HSSFTestDataSamples.OpenSampleFileStream("WithEmbeddedObjects.xls"))).Root; files[1] = (new NPOIFSFileSystem(HSSFTestDataSamples.OpenSampleFileStream("WithEmbeddedObjects.xls"))).Root; // Check the embedded parts foreach (DirectoryNode root in files) { HSSFWorkbook hw = new HSSFWorkbook(root, true); IList<HSSFObjectData> objects = hw.GetAllEmbeddedObjects(); bool found = false; foreach (HSSFObjectData embeddedObject in objects) { if (embeddedObject.HasDirectoryEntry()) { DirectoryEntry dir = embeddedObject.GetDirectory(); if (dir is DirectoryNode) { DirectoryNode dNode = (DirectoryNode)dir; if (HasEntry(dNode, "WordDocument")) { found = true; } } } } Assert.IsTrue(found); } } /** * Checks that we can open a workbook with NPOIFS, and write it out * again (via POIFS) and have it be valid * @throws IOException */ [Test] public void WriteWorkbookFromNPOIFS() { Stream is1 = HSSFTestDataSamples.OpenSampleFileStream("WithEmbeddedObjects.xls"); try { NPOIFSFileSystem fs = new NPOIFSFileSystem(is1); try { // Start as NPOIFS HSSFWorkbook wb = new HSSFWorkbook(fs.Root, true); Assert.AreEqual(3, wb.NumberOfSheets); Assert.AreEqual("Root xls", wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue); // Will switch to POIFS wb = HSSFTestDataSamples.WriteOutAndReadBack(wb); Assert.AreEqual(3, wb.NumberOfSheets); Assert.AreEqual("Root xls", wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue); } finally { fs.Close(); } } finally { is1.Close(); } } [Test] public void CellStylesLimit() { IWorkbook wb = new HSSFWorkbook(); int numBuiltInStyles = wb.NumCellStyles; int MAX_STYLES = 4030; int limit = MAX_STYLES - numBuiltInStyles; for (int i = 0; i < limit; i++) { ICellStyle style = wb.CreateCellStyle(); } Assert.AreEqual(MAX_STYLES, wb.NumCellStyles); try { ICellStyle style = wb.CreateCellStyle(); Assert.Fail("expected exception"); } catch (InvalidOperationException e) { Assert.AreEqual("The maximum number of cell styles was exceeded. " + "You can define up to 4000 styles in a .xls workbook", e.Message); } Assert.AreEqual(MAX_STYLES, wb.NumCellStyles); } [Test] public void SetSheetOrderHSSF() { IWorkbook wb = new HSSFWorkbook(); ISheet s1 = wb.CreateSheet("first sheet"); ISheet s2 = wb.CreateSheet("other sheet"); IName name1 = wb.CreateName(); name1.NameName = (/*setter*/"name1"); name1.RefersToFormula = (/*setter*/"'first sheet'!D1"); IName name2 = wb.CreateName(); name2.NameName = (/*setter*/"name2"); name2.RefersToFormula = (/*setter*/"'other sheet'!C1"); IRow s1r1 = s1.CreateRow(2); ICell c1 = s1r1.CreateCell(3); c1.SetCellValue(30); ICell c2 = s1r1.CreateCell(2); c2.CellFormula = (/*setter*/"SUM('other sheet'!C1,'first sheet'!C1)"); IRow s2r1 = s2.CreateRow(0); ICell c3 = s2r1.CreateCell(1); c3.CellFormula = (/*setter*/"'first sheet'!D3"); ICell c4 = s2r1.CreateCell(2); c4.CellFormula = (/*setter*/"'other sheet'!D3"); // conditional formatting ISheetConditionalFormatting sheetCF = s1.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Between, "'first sheet'!D1", "'other sheet'!D1"); IConditionalFormattingRule[] cfRules = { rule1 }; CellRangeAddress[] regions = { new CellRangeAddress(2, 4, 0, 0), // A3:A5 }; sheetCF.AddConditionalFormatting(regions, cfRules); wb.SetSheetOrder("other sheet", 0); // names Assert.AreEqual("'first sheet'!D1", wb.GetName("name1").RefersToFormula); Assert.AreEqual("'other sheet'!C1", wb.GetName("name2").RefersToFormula); // cells Assert.AreEqual("SUM('other sheet'!C1,'first sheet'!C1)", c2.CellFormula); Assert.AreEqual("'first sheet'!D3", c3.CellFormula); Assert.AreEqual("'other sheet'!D3", c4.CellFormula); // conditional formatting IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual("'first sheet'!D1", cf.GetRule(0).Formula1); Assert.AreEqual("'other sheet'!D1", cf.GetRule(0).Formula2); } private bool HasEntry(DirectoryNode dirNode, String entryName) { try { dirNode.GetEntry(entryName); return true; } catch (FileNotFoundException) { return false; } } [Test] public void ClonePictures() { IWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("SimpleWithImages.xls"); InternalWorkbook iwb = ((HSSFWorkbook)wb).Workbook; iwb.FindDrawingGroup(); for (int pictureIndex = 1; pictureIndex <= 4; pictureIndex++) { EscherBSERecord bse = iwb.GetBSERecord(pictureIndex); Assert.AreEqual(1, bse.Ref); } wb.CloneSheet(0); for (int pictureIndex = 1; pictureIndex <= 4; pictureIndex++) { EscherBSERecord bse = iwb.GetBSERecord(pictureIndex); Assert.AreEqual(2, bse.Ref); } wb.CloneSheet(0); for (int pictureIndex = 1; pictureIndex <= 4; pictureIndex++) { EscherBSERecord bse = iwb.GetBSERecord(pictureIndex); Assert.AreEqual(3, bse.Ref); } wb.Close(); } [Test] public void ChangeSheetNameWithSharedFormulas() { ChangeSheetNameWithSharedFormulas("shared_formulas.xls"); } [Test] public void EmptyDirectoryNode() { POIFSFileSystem fs = new POIFSFileSystem(); try { new HSSFWorkbook(fs).Close(); } finally { fs.Close(); } } [Test] public void SelectedSheetshort() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet1 = (HSSFSheet)wb.CreateSheet("Sheet1"); HSSFSheet sheet2 = (HSSFSheet)wb.CreateSheet("Sheet2"); HSSFSheet sheet3 = (HSSFSheet)wb.CreateSheet("Sheet3"); HSSFSheet sheet4 = (HSSFSheet)wb.CreateSheet("Sheet4"); ConfirmActiveSelected(sheet1, true); ConfirmActiveSelected(sheet2, false); ConfirmActiveSelected(sheet3, false); ConfirmActiveSelected(sheet4, false); wb.SetSelectedTab((short)1); // Demonstrate bug 44525: // Well... not quite, since isActive + isSelected were also Added in the same bug fix if (sheet1.IsSelected) { //throw new AssertionFailedError("Identified bug 44523 a"); Assert.Fail("Identified bug 44523 a"); } wb.SetActiveSheet(1); if (sheet1.IsActive) { //throw new AssertionFailedError("Identified bug 44523 b"); Assert.Fail("Identified bug 44523 b"); } ConfirmActiveSelected(sheet1, false); ConfirmActiveSelected(sheet2, true); ConfirmActiveSelected(sheet3, false); ConfirmActiveSelected(sheet4, false); Assert.AreEqual(0, wb.FirstVisibleTab); wb.FirstVisibleTab = 2; Assert.AreEqual(2, wb.FirstVisibleTab); wb.Close(); } [Test] public void Names() { HSSFWorkbook wb = new HSSFWorkbook(); try { wb.GetNameAt(0); Assert.Fail("Fails without any defined names"); } catch (InvalidOperationException e) { Assert.IsTrue(e.Message.Contains("no defined names"), e.Message); } HSSFName name = (HSSFName)wb.CreateName(); Assert.IsNotNull(name); Assert.IsNull(wb.GetName("somename")); name.NameName = ("myname"); Assert.IsNotNull(wb.GetName("myname")); Assert.AreEqual(0, wb.GetNameIndex(name)); Assert.AreEqual(0, wb.GetNameIndex("myname")); try { wb.GetNameAt(5); Assert.Fail("Fails without any defined names"); } catch (ArgumentOutOfRangeException e) { Assert.IsTrue(e.Message.Contains("outside the allowable range"), e.Message); } try { wb.GetNameAt(-3); Assert.Fail("Fails without any defined names"); } catch (ArgumentOutOfRangeException e) { Assert.IsTrue(e.Message.Contains("outside the allowable range"), e.Message); } } [Test] public void TestMethods() { HSSFWorkbook wb = new HSSFWorkbook(); wb.InsertChartRecord(); //wb.dumpDrawingGroupRecords(true); //wb.dumpDrawingGroupRecords(false); } [Test] public void WriteProtection() { HSSFWorkbook wb = new HSSFWorkbook(); Assert.IsFalse(wb.IsWriteProtected); wb.WriteProtectWorkbook("mypassword", "myuser"); Assert.IsTrue(wb.IsWriteProtected); wb.UnwriteProtectWorkbook(); Assert.IsFalse(wb.IsWriteProtected); } [Test] public void Bug50298() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("50298.xls"); assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); ISheet sheet = wb.CloneSheet(0); assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "Invoice (2)"); wb.SetSheetName(wb.GetSheetIndex(sheet), "copy"); assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "copy"); wb.SetSheetOrder("copy", 0); assertSheetOrder(wb, "copy", "Invoice", "Invoice1", "Digest", "Deferred", "Received"); wb.RemoveSheetAt(0); assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); // check that the overall workbook serializes with its correct size int expected = wb.Workbook.Size; int written = wb.Workbook.Serialize(0, new byte[expected * 2]); Assert.AreEqual(expected, written, "Did not have the expected size when writing the workbook: written: " + written + ", but expected: " + expected); HSSFWorkbook read = HSSFTestDataSamples.WriteOutAndReadBack(wb); assertSheetOrder(read, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); read.Close(); wb.Close(); } [Test] public void Bug50298a() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("50298.xls"); assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); ISheet sheet = wb.CloneSheet(0); assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "Invoice (2)"); wb.SetSheetName(wb.GetSheetIndex(sheet), "copy"); assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "copy"); wb.SetSheetOrder("copy", 0); assertSheetOrder(wb, "copy", "Invoice", "Invoice1", "Digest", "Deferred", "Received"); wb.RemoveSheetAt(0); assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); wb.RemoveSheetAt(1); assertSheetOrder(wb, "Invoice", "Digest", "Deferred", "Received"); wb.SetSheetOrder("Digest", 3); assertSheetOrder(wb, "Invoice", "Deferred", "Received", "Digest"); // check that the overall workbook serializes with its correct size int expected = wb.Workbook.Size; int written = wb.Workbook.Serialize(0, new byte[expected * 2]); Assert.AreEqual(expected, written, "Did not have the expected size when writing the workbook: written: " + written + ", but expected: " + expected); HSSFWorkbook read = HSSFTestDataSamples.WriteOutAndReadBack(wb); assertSheetOrder(wb, "Invoice", "Deferred", "Received", "Digest"); read.Close(); wb.Close(); } [Test] public void Bug54500() { String nameName = "AName"; String sheetName = "ASheet"; IWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("54500.xls"); assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3"); wb.CreateSheet(sheetName); assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet"); IName n = wb.CreateName(); n.NameName = (/*setter*/nameName); n.SheetIndex = (/*setter*/3); n.RefersToFormula = (/*setter*/sheetName + "!A1"); assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet"); HSSFName name = wb.GetName(nameName) as HSSFName; Assert.IsNotNull(name); Assert.AreEqual("ASheet!A1", name.RefersToFormula); MemoryStream stream = new MemoryStream(); wb.Write(stream); assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet"); Assert.AreEqual("ASheet!A1", name.RefersToFormula); wb.RemoveSheetAt(1); assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet"); Assert.AreEqual("ASheet!A1", name.RefersToFormula); MemoryStream stream2 = new MemoryStream(); wb.Write(stream2); assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet"); Assert.AreEqual("ASheet!A1", name.RefersToFormula); HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(stream.ToArray())); ExpectName(wb2, nameName, "ASheet!A1"); HSSFWorkbook wb3 = new HSSFWorkbook(new ByteArrayInputStream(stream2.ToArray())); ExpectName(wb3, nameName, "ASheet!A1"); wb3.Close(); wb2.Close(); wb.Close(); } private void ExpectName(HSSFWorkbook wb, String name, String expect) { HSSFName hssfName = wb.GetName(name) as HSSFName; Assert.IsNotNull(hssfName); Assert.AreEqual(expect, hssfName.RefersToFormula); } [Test] public void Best49423() { HSSFWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook("49423.xls"); bool found = false; int numSheets = workbook.NumberOfSheets; for (int i = 0; i < numSheets; i++) { HSSFSheet sheet = workbook.GetSheetAt(i) as HSSFSheet; IList<HSSFShape> shapes = (sheet.DrawingPatriarch as HSSFPatriarch).Children; foreach (HSSFShape shape in shapes) { HSSFAnchor anchor = shape.Anchor; if (anchor is HSSFClientAnchor) { // absolute coordinates HSSFClientAnchor clientAnchor = (HSSFClientAnchor)anchor; Assert.IsNotNull(clientAnchor); //System.out.Println(clientAnchor.Row1 + "," + clientAnchor.Row2); found = true; } else if (anchor is HSSFChildAnchor) { // shape is grouped and the anchor is expressed in the coordinate system of the group HSSFChildAnchor childAnchor = (HSSFChildAnchor)anchor; Assert.IsNotNull(childAnchor); //System.out.Println(childAnchor.Dy1 + "," + childAnchor.Dy2); found = true; } } } Assert.IsTrue(found, "Should find some images via Client or Child anchors, but did not find any at all"); workbook.Close(); } [Test] [Ignore("not found in poi 3.14")] public void Bug47245() { Assert.DoesNotThrow(() => HSSFTestDataSamples.OpenSampleWorkbook("47245_test.xls")); } [Test] public void TestRewriteFileBug58480() { FileInfo file = TempFile.CreateTempFile("TestHSSFWorkbook", ".xls"); try { // create new workbook { IWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("foo"); IRow row = sheet.CreateRow(1); row.CreateCell(1).SetCellValue("bar"); WriteAndCloseWorkbook(workbook, file); } // edit the workbook { NPOIFSFileSystem fs = new NPOIFSFileSystem(file, false); try { DirectoryNode root = fs.Root; IWorkbook workbook = new HSSFWorkbook(root, true); ISheet sheet = workbook.GetSheet("foo"); sheet.GetRow(1).CreateCell(2).SetCellValue("baz"); WriteAndCloseWorkbook(workbook, file); } finally { fs.Close(); } } } finally { Assert.IsTrue(file.Exists); file.Delete(); Assert.IsTrue(!File.Exists(file.FullName)); } } private void WriteAndCloseWorkbook(IWorkbook workbook, FileInfo file) { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); workbook.Write(bytesOut); workbook.Close(); byte[] byteArray = bytesOut.ToByteArray(); bytesOut.Close(); FileStream fileOut = new FileStream(file.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite); fileOut.Write(byteArray, 0, byteArray.Length); fileOut.Close(); } [Test] public void CloseDoesNotModifyWorkbook() { String filename = "SampleSS.xls"; FileInfo file = POIDataSamples.GetSpreadSheetInstance().GetFileInfo(filename); IWorkbook wb; // File via POIFileStream (java.io) wb = new HSSFWorkbook(new POIFSFileSystem(file)); assertCloseDoesNotModifyFile(filename, wb); // File via NPOIFileStream (java.nio) wb = new HSSFWorkbook(new NPOIFSFileSystem(file)); assertCloseDoesNotModifyFile(filename, wb); // InputStream wb = new HSSFWorkbook(file.OpenRead()); assertCloseDoesNotModifyFile(filename, wb); } [Test] public void SetSheetOrderToEnd() { HSSFWorkbook workbook = new HSSFWorkbook(); workbook.CreateSheet("A"); try { for (int i = 0; i < 2 * workbook.InternalWorkbook.Records.Count; i++) { workbook.SetSheetOrder("A", 0); } } catch (Exception e) { throw new Exception("Moving a sheet to the end should not throw an exception, but threw ", e); } } [Test] public void InvalidInPlaceWrite() { HSSFWorkbook wb; // Can't work for new files wb = new HSSFWorkbook(); try { wb.Write(); Assert.Fail("Shouldn't work for new files"); } catch (InvalidOperationException e) { } // Can't work for InputStream opened files wb = new HSSFWorkbook( POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("SampleSS.xls")); try { wb.Write(); Assert.Fail("Shouldn't work for InputStream"); } catch (InvalidOperationException e) { } // Can't work for OPOIFS OPOIFSFileSystem ofs = new OPOIFSFileSystem( POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("SampleSS.xls")); wb = new HSSFWorkbook(ofs.Root, true); try { wb.Write(); Assert.Fail("Shouldn't work for OPOIFSFileSystem"); } catch (InvalidOperationException e) { } // Can't work for Read-Only files NPOIFSFileSystem fs = new NPOIFSFileSystem( POIDataSamples.GetSpreadSheetInstance().GetFile("SampleSS.xls"), true); wb = new HSSFWorkbook(fs); try { wb.Write(); Assert.Fail("Shouldn't work for Read Only"); } catch (InvalidOperationException e) { } } [Test] public void InPlaceWrite() { // Setup as a copy of a known-good file FileInfo file = TempFile.CreateTempFile("TestHSSFWorkbook", ".xls"); Stream outStream = file.Open(FileMode.Open, FileAccess.ReadWrite); Stream inStream = POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("SampleSS.xls"); IOUtils.Copy( inStream, outStream ); outStream.Close(); inStream.Close(); // Open from the temp file in read-write mode HSSFWorkbook wb = new HSSFWorkbook(new NPOIFSFileSystem(file, false)); Assert.AreEqual(3, wb.NumberOfSheets); // Change wb.RemoveSheetAt(2); wb.RemoveSheetAt(1); wb.GetSheetAt(0).GetRow(0).GetCell(0).SetCellValue("Changed!"); // Save in-place, close, re-open and check wb.Write(); wb.Close(); wb = new HSSFWorkbook(new NPOIFSFileSystem(file)); Assert.AreEqual(1, wb.NumberOfSheets); Assert.AreEqual("Changed!", wb.GetSheetAt(0).GetRow(0).GetCell(0).ToString()); } [Test] public void TestWriteToNewFile() { // Open from a Stream HSSFWorkbook wb = new HSSFWorkbook( POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("SampleSS.xls")); // Save to a new temp file FileInfo file = TempFile.CreateTempFile("TestHSSFWorkbook", ".xls"); wb.Write(file); wb.Close(); // Read and check wb = new HSSFWorkbook(new NPOIFSFileSystem(file)); Assert.AreEqual(3, wb.NumberOfSheets); wb.Close(); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using OpenTK; using OpenTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Play; using osu.Game.Screens.Select.Leaderboards; using osu.Game.Users; using osu.Framework.Graphics.Shapes; using osu.Framework.Extensions; namespace osu.Game.Screens.Ranking { public class ResultsPageScore : ResultsPage { private ScoreCounter scoreCounter; public ResultsPageScore(Score score, WorkingBeatmap beatmap) : base(score, beatmap) { } private FillFlowContainer<DrawableScoreStatistic> statisticsContainer; [BackgroundDependencyLoader] private void load(OsuColour colours) { const float user_header_height = 120; Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = user_header_height }, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.White, }, } }, new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Children = new Drawable[] { new UserHeader(Score.User) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X, Height = user_header_height, }, new DrawableRank(Score.Rank) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Size = new Vector2(150, 60), Margin = new MarginPadding(20), }, new Container { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X, Height = 60, Children = new Drawable[] { new SongProgressGraph { RelativeSizeAxes = Axes.Both, Alpha = 0.5f, Objects = Beatmap.Beatmap.HitObjects, }, scoreCounter = new SlowScoreCounter(6) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Colour = colours.PinkDarker, Y = 10, TextSize = 56, }, } }, new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Colour = colours.PinkDarker, Shadow = false, Font = @"Exo2.0-Bold", TextSize = 16, Text = "total score", Margin = new MarginPadding { Bottom = 15 }, }, new BeatmapDetails(Beatmap.BeatmapInfo) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Bottom = 10 }, }, new DateTimeDisplay(Score.Date.LocalDateTime) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, new Container { RelativeSizeAxes = Axes.X, Size = new Vector2(0.75f, 1), Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Top = 10, Bottom = 10 }, Children = new Drawable[] { new Box { Colour = ColourInfo.GradientHorizontal( colours.GrayC.Opacity(0), colours.GrayC.Opacity(0.9f)), RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f, 1), }, new Box { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Colour = ColourInfo.GradientHorizontal( colours.GrayC.Opacity(0.9f), colours.GrayC.Opacity(0)), RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f, 1), }, } }, statisticsContainer = new FillFlowContainer<DrawableScoreStatistic> { AutoSizeAxes = Axes.Both, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Direction = FillDirection.Horizontal, LayoutDuration = 200, LayoutEasing = Easing.OutQuint } } } }; statisticsContainer.ChildrenEnumerable = Score.Statistics.OrderByDescending(p => p.Key).Select(s => new DrawableScoreStatistic(s)); } protected override void LoadComplete() { base.LoadComplete(); Schedule(() => { scoreCounter.Increment(Score.TotalScore); int delay = 0; foreach (var s in statisticsContainer.Children) { s.FadeOut() .Then(delay += 200) .FadeIn(300 + delay, Easing.Out); } }); } private class DrawableScoreStatistic : Container { private readonly KeyValuePair<HitResult, object> statistic; public DrawableScoreStatistic(KeyValuePair<HitResult, object> statistic) { this.statistic = statistic; AutoSizeAxes = Axes.Both; Margin = new MarginPadding { Left = 5, Right = 5 }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new OsuSpriteText { Text = statistic.Value.ToString().PadLeft(4, '0'), Colour = colours.Gray7, TextSize = 30, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, new OsuSpriteText { Text = statistic.Key.GetDescription(), Colour = colours.Gray7, Font = @"Exo2.0-Bold", Y = 26, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, }; } } private class DateTimeDisplay : Container { private DateTime datetime; public DateTimeDisplay(DateTime datetime) { this.datetime = datetime; AutoSizeAxes = Axes.Y; Width = 140; Masking = true; CornerRadius = 5; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colours.Gray6, }, new OsuSpriteText { Origin = Anchor.CentreLeft, Anchor = Anchor.CentreLeft, Text = datetime.ToShortDateString(), Padding = new MarginPadding { Horizontal = 10, Vertical = 5 }, Colour = Color4.White, }, new OsuSpriteText { Origin = Anchor.CentreRight, Anchor = Anchor.CentreRight, Text = datetime.ToShortTimeString(), Padding = new MarginPadding { Horizontal = 10, Vertical = 5 }, Colour = Color4.White, } }; } } private class BeatmapDetails : Container { private readonly BeatmapInfo beatmap; private readonly OsuSpriteText title; private readonly OsuSpriteText artist; private readonly OsuSpriteText versionMapper; public BeatmapDetails(BeatmapInfo beatmap) { this.beatmap = beatmap; AutoSizeAxes = Axes.Both; Children = new Drawable[] { new FillFlowContainer { Direction = FillDirection.Vertical, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { title = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 24, Font = @"Exo2.0-BoldItalic", }, artist = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 20, Font = @"Exo2.0-BoldItalic", }, versionMapper = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 16, Font = @"Exo2.0-Bold", }, } } }; } [BackgroundDependencyLoader] private void load(OsuColour colours, LocalisationEngine localisation) { title.Colour = artist.Colour = colours.BlueDarker; versionMapper.Colour = colours.Gray8; var creator = beatmap.Metadata.Author?.Username; if (!string.IsNullOrEmpty(creator)) { versionMapper.Text = $"mapped by {creator}"; if (!string.IsNullOrEmpty(beatmap.Version)) versionMapper.Text = $"{beatmap.Version} - " + versionMapper.Text; } title.Current = localisation.GetUnicodePreference(beatmap.Metadata.TitleUnicode, beatmap.Metadata.Title); artist.Current = localisation.GetUnicodePreference(beatmap.Metadata.ArtistUnicode, beatmap.Metadata.Artist); } } private class UserHeader : Container { private readonly User user; private readonly Sprite cover; public UserHeader(User user) { this.user = user; Children = new Drawable[] { cover = new Sprite { RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fill, Anchor = Anchor.Centre, Origin = Anchor.Centre, }, new OsuSpriteText { Font = @"Exo2.0-RegularItalic", Text = user.Username, Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, TextSize = 30, Padding = new MarginPadding { Bottom = 10 }, } }; } [BackgroundDependencyLoader] private void load(TextureStore textures) { if (!string.IsNullOrEmpty(user.CoverUrl)) cover.Texture = textures.Get(user.CoverUrl); } } private class SlowScoreCounter : ScoreCounter { protected override double RollingDuration => 3000; protected override Easing RollingEasing => Easing.OutPow10; public SlowScoreCounter(uint leading = 0) : base(leading) { DisplayedCountSpriteText.Shadow = false; DisplayedCountSpriteText.Font = @"Venera-Light"; UseCommaSeparator = true; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Security; using System.Text; using System.Windows; using System.Windows.Markup; // for XmlLanguage using System.Windows.Media; using MS.Internal; using MS.Internal.PresentationCore; using MS.Utility; using MS.Internal.FontCache; // Since we disable PreSharp warnings in this file, we first need to disable warnings about unknown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 namespace MS.Internal.FontFace { /// <summary> /// Font technology. /// </summary> internal enum FontTechnology { // this enum need to be kept in order of preference that we want to use with duplicate font face, // highest value will win in case of duplicate PostscriptOpenType, TrueType, TrueTypeCollection } internal class TrueTypeFontDriver { #region Font constants, structures and enumerations private struct DirectoryEntry { internal TrueTypeTags tag; internal CheckedPointer pointer; } private enum TrueTypeTags : int { CharToIndexMap = 0x636d6170, /* 'cmap' */ ControlValue = 0x63767420, /* 'cvt ' */ BitmapData = 0x45424454, /* 'EBDT' */ BitmapLocation = 0x45424c43, /* 'EBLC' */ BitmapScale = 0x45425343, /* 'EBSC' */ Editor0 = 0x65647430, /* 'edt0' */ Editor1 = 0x65647431, /* 'edt1' */ Encryption = 0x63727970, /* 'cryp' */ FontHeader = 0x68656164, /* 'head' */ FontProgram = 0x6670676d, /* 'fpgm' */ GridfitAndScanProc = 0x67617370, /* 'gasp' */ GlyphDirectory = 0x67646972, /* 'gdir' */ GlyphData = 0x676c7966, /* 'glyf' */ HoriDeviceMetrics = 0x68646d78, /* 'hdmx' */ HoriHeader = 0x68686561, /* 'hhea' */ HorizontalMetrics = 0x686d7478, /* 'hmtx' */ IndexToLoc = 0x6c6f6361, /* 'loca' */ Kerning = 0x6b65726e, /* 'kern' */ LinearThreshold = 0x4c545348, /* 'LTSH' */ MaxProfile = 0x6d617870, /* 'maxp' */ NamingTable = 0x6e616d65, /* 'name' */ OS_2 = 0x4f532f32, /* 'OS/2' */ Postscript = 0x706f7374, /* 'post' */ PreProgram = 0x70726570, /* 'prep' */ VertDeviceMetrics = 0x56444d58, /* 'VDMX' */ VertHeader = 0x76686561, /* 'vhea' */ VerticalMetrics = 0x766d7478, /* 'vmtx' */ PCLT = 0x50434C54, /* 'PCLT' */ TTO_GSUB = 0x47535542, /* 'GSUB' */ TTO_GPOS = 0x47504F53, /* 'GPOS' */ TTO_GDEF = 0x47444546, /* 'GDEF' */ TTO_BASE = 0x42415345, /* 'BASE' */ TTO_JSTF = 0x4A535446, /* 'JSTF' */ OTTO = 0x4f54544f, // Adobe OpenType 'OTTO' TTC_TTCF = 0x74746366 // 'ttcf' } #endregion #region Byte, Short, Long etc. accesss to CheckedPointers /// <summary> /// The follwoing APIs extract OpenType variable types from OpenType font /// files. OpenType variables are stored big-endian, and the type are named /// as follows: /// Byte - signed 8 bit /// UShort - unsigned 16 bit /// Short - signed 16 bit /// ULong - unsigned 32 bit /// Long - signed 32 bit /// </summary> /// <SecurityNote> /// Critical: Calls into probe which is critical and also has unsafe code blocks /// TreatAsSafe: This code is Ok to expose /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private static ushort ReadOpenTypeUShort(CheckedPointer pointer) { unsafe { byte * readBuffer = (byte *)pointer.Probe(0, 2); ushort result = (ushort)((readBuffer[0] << 8) + readBuffer[1]); return result; } } /// <SecurityNote> /// Critical: Calls into probe which is critical and also has unsafe code blocks /// TreatAsSafe: This code IS Ok to expose /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private static int ReadOpenTypeLong(CheckedPointer pointer) { unsafe { byte * readBuffer = (byte *)pointer.Probe(0, 4); int result = (int)((((((readBuffer[0] << 8) + readBuffer[1]) << 8) + readBuffer[2]) << 8) + readBuffer[3]); return result; } } #endregion Byte, Short, Long etc. accesss to CheckedPointers #region Constructor and general helpers /// <SecurityNote> /// Critical: constructs data for a checked pointer. /// </SecurityNote> [SecurityCritical] internal TrueTypeFontDriver(UnmanagedMemoryStream unmanagedMemoryStream, Uri sourceUri) { _sourceUri = sourceUri; _unmanagedMemoryStream = unmanagedMemoryStream; _fileStream = new CheckedPointer(unmanagedMemoryStream); try { CheckedPointer seekPosition = _fileStream; TrueTypeTags typeTag = (TrueTypeTags)ReadOpenTypeLong(seekPosition); seekPosition += 4; if (typeTag == TrueTypeTags.TTC_TTCF) { // this is a TTC file, we need to decode the ttc header _technology = FontTechnology.TrueTypeCollection; seekPosition += 4; // skip version _numFaces = ReadOpenTypeLong(seekPosition); } else if (typeTag == TrueTypeTags.OTTO) { _technology = FontTechnology.PostscriptOpenType; _numFaces = 1; } else { _technology = FontTechnology.TrueType; _numFaces = 1; } } catch (ArgumentOutOfRangeException e) { // convert exceptions from CheckedPointer to FileFormatException throw new FileFormatException(SourceUri, e); } } internal void SetFace(int faceIndex) { if (_technology == FontTechnology.TrueTypeCollection) { if (faceIndex < 0 || faceIndex >= _numFaces) throw new ArgumentOutOfRangeException("faceIndex"); } else { if (faceIndex != 0) throw new ArgumentOutOfRangeException("faceIndex", SR.Get(SRID.FaceIndexValidOnlyForTTC)); } try { CheckedPointer seekPosition = _fileStream + 4; if (_technology == FontTechnology.TrueTypeCollection) { // this is a TTC file, we need to decode the ttc header // skip version, num faces, OffsetTable array seekPosition += (4 + 4 + 4 * faceIndex); _directoryOffset = ReadOpenTypeLong(seekPosition); seekPosition = _fileStream + (_directoryOffset + 4); // 4 means that we skip the version number } _faceIndex = faceIndex; int numTables = ReadOpenTypeUShort(seekPosition); seekPosition += 2; // quick check for malformed fonts, see if numTables is too large // file size should be >= sizeof(offset table) + numTables * (sizeof(directory entry) + minimum table size (4)) long minimumFileSize = (4 + 2 + 2 + 2 + 2) + numTables * (4 + 4 + 4 + 4 + 4); if (_fileStream.Size < minimumFileSize) { throw new FileFormatException(SourceUri); } _tableDirectory = new DirectoryEntry[numTables]; // skip searchRange, entrySelector and rangeShift seekPosition += 6; // I can't use foreach here because C# disallows modifying the current value for (int i = 0; i < _tableDirectory.Length; ++i) { _tableDirectory[i].tag = (TrueTypeTags)ReadOpenTypeLong(seekPosition); seekPosition += 8; // skip checksum int offset = ReadOpenTypeLong(seekPosition); seekPosition += 4; int length = ReadOpenTypeLong(seekPosition); seekPosition += 4; _tableDirectory[i].pointer = _fileStream.CheckedProbe(offset, length); } } catch (ArgumentOutOfRangeException e) { // convert exceptions from CheckedPointer to FileFormatException throw new FileFormatException(SourceUri, e); } } #endregion #region Public methods and properties internal int NumFaces { get { return _numFaces; } } private Uri SourceUri { get { return _sourceUri; } } /// <summary> /// Create font subset that includes glyphs in the input collection. /// </summary> ///<SecurityNote> /// TreatAsSafe: This API could be public in terms of security as it demands unmanaged code /// Critical: Does an elevation by calling TrueTypeSubsetter which we are treating as equivalent to /// unsafe native methods ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal byte[] ComputeFontSubset(ICollection<ushort> glyphs) { SecurityHelper.DemandUnmanagedCode(); int fileSize = _fileStream.Size; unsafe { void* fontData = _fileStream.Probe(0, fileSize); // Since we currently don't have a way to subset CFF fonts, just return a copy of the font. if (_technology == FontTechnology.PostscriptOpenType) { byte[] fontCopy = new byte[fileSize]; Marshal.Copy((IntPtr)fontData, fontCopy, 0, fileSize); return fontCopy; } ushort[] glyphArray; if (glyphs == null || glyphs.Count == 0) glyphArray = null; else { glyphArray = new ushort[glyphs.Count]; glyphs.CopyTo(glyphArray, 0); } return TrueTypeSubsetter.ComputeSubset(fontData, fileSize, SourceUri, _directoryOffset, glyphArray); } } #endregion Public methods and properties #region Fields // file-specific state private CheckedPointer _fileStream; private UnmanagedMemoryStream _unmanagedMemoryStream; private Uri _sourceUri; private int _numFaces; private FontTechnology _technology; // face-specific state private int _faceIndex; private int _directoryOffset; // table directory offset for TTC, 0 for TTF private DirectoryEntry[] _tableDirectory; #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Concurrent; using System.Diagnostics.Contracts; using System.Globalization; using System.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Threading.Tasks; namespace System.ServiceModel.Channels { public class ServiceChannelProxy : DispatchProxy, ICommunicationObject, IChannel, IClientChannel, IOutputChannel, IRequestChannel, IServiceChannel, IDuplexContextChannel { private const String activityIdSlotName = "E2ETrace.ActivityID"; private Type _proxiedType; private ServiceChannel _serviceChannel; private ImmutableClientRuntime _proxyRuntime; private MethodDataCache _methodDataCache; // ServiceChannelProxy serves 2 roles. It is the TChannel proxy called by the client, // and it is also the handler of those calls that dispatches them to the appropriate service channel. // In .Net Remoting terms, it is conceptually the same as a RealProxy and a TransparentProxy combined. internal static TChannel CreateProxy<TChannel>(MessageDirection direction, ServiceChannel serviceChannel) { TChannel proxy = DispatchProxy.Create<TChannel, ServiceChannelProxy>(); if (proxy == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.FailedToCreateTypedProxy, typeof(TChannel)))); } ServiceChannelProxy channelProxy = (ServiceChannelProxy)(object)proxy; channelProxy._proxiedType = typeof(TChannel); channelProxy._serviceChannel = serviceChannel; channelProxy._proxyRuntime = serviceChannel.ClientRuntime.GetRuntime(); channelProxy._methodDataCache = new MethodDataCache(); return proxy; } //Workaround is to set the activityid in remoting call's LogicalCallContext // Override ToString() to reveal only the expected proxy type, not the generated one public override string ToString() { return _proxiedType.ToString(); } private MethodData GetMethodData(MethodCall methodCall) { MethodData methodData; MethodBase method = methodCall.MethodBase; if (_methodDataCache.TryGetMethodData(method, out methodData)) { return methodData; } bool canCacheMessageData; Type declaringType = method.DeclaringType; if (declaringType == typeof(object) && method == typeof(object).GetMethod("GetType")) { canCacheMessageData = true; methodData = new MethodData(method, MethodType.GetType); } else if (declaringType.IsAssignableFrom(_serviceChannel.GetType())) { canCacheMessageData = true; methodData = new MethodData(method, MethodType.Channel); } else { ProxyOperationRuntime operation = _proxyRuntime.GetOperation(method, methodCall.Args, out canCacheMessageData); if (operation == null) { if (_serviceChannel.Factory != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SFxMethodNotSupported1, method.Name))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SFxMethodNotSupportedOnCallback1, method.Name))); } MethodType methodType; if (operation.IsTaskCall(methodCall)) { methodType = MethodType.TaskService; } else if (operation.IsSyncCall(methodCall)) { methodType = MethodType.Service; } else if (operation.IsBeginCall(methodCall)) { methodType = MethodType.BeginService; } else { methodType = MethodType.EndService; } methodData = new MethodData(method, methodType, operation); } if (canCacheMessageData) { _methodDataCache.SetMethodData(methodData); } return methodData; } internal ServiceChannel GetServiceChannel() { return _serviceChannel; } protected override object Invoke(MethodInfo targetMethod, object[] args) { if (args == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("args"); } if (targetMethod == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidTypedProxyMethodHandle, _proxiedType.Name))); } MethodCall methodCall = new MethodCall(targetMethod, args); MethodData methodData = GetMethodData(methodCall); switch (methodData.MethodType) { case MethodType.Service: return InvokeService(methodCall, methodData.Operation); case MethodType.BeginService: return InvokeBeginService(methodCall, methodData.Operation); case MethodType.EndService: return InvokeEndService(methodCall, methodData.Operation); case MethodType.TaskService: return InvokeTaskService(methodCall, methodData.Operation); case MethodType.Channel: return InvokeChannel(methodCall); case MethodType.GetType: return InvokeGetType(methodCall); default: Fx.Assert("Invalid proxy method type"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Invalid proxy method type"))); } } internal static class TaskCreator { public static Task CreateTask(ServiceChannel channel, MethodCall methodCall, ProxyOperationRuntime operation) { if (operation.TaskTResult == ServiceReflector.VoidType) { return TaskCreator.CreateTask(channel, operation, methodCall.Args); } return TaskCreator.CreateGenericTask(channel, operation, methodCall.Args); } private static Task CreateGenericTask(ServiceChannel channel, ProxyOperationRuntime operation, object[] inputParameters) { TaskCompletionSourceProxy tcsp = new TaskCompletionSourceProxy(operation.TaskTResult); bool completedCallback = false; Action<IAsyncResult> endCallDelegate = (asyncResult) => { Contract.Assert(asyncResult != null, "'asyncResult' MUST NOT be NULL."); completedCallback = true; OperationContext originalOperationContext = OperationContext.Current; OperationContext.Current = asyncResult.AsyncState as OperationContext; try { object result = channel.EndCall(operation.Action, Array.Empty<object>(), asyncResult); tcsp.TrySetResult(result); } catch (Exception e) { tcsp.TrySetException(e); } finally { OperationContext.Current = originalOperationContext; } }; try { IAsyncResult ar = ServiceChannel.BeginCall(channel, operation, inputParameters, new AsyncCallback(endCallDelegate), OperationContext.Current); if (ar.CompletedSynchronously && !completedCallback) { endCallDelegate(ar); } } catch (Exception e) { tcsp.TrySetException(e); } return tcsp.Task; } private static Task CreateTask(ServiceChannel channel, ProxyOperationRuntime operation, object[] inputParameters) { TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); bool completedCallback = false; Action<IAsyncResult> endCallDelegate = (asyncResult) => { Contract.Assert(asyncResult != null, "'asyncResult' MUST NOT be NULL."); completedCallback = true; OperationContext originalOperationContext = OperationContext.Current; OperationContext.Current = asyncResult.AsyncState as OperationContext; try { channel.EndCall(operation.Action, Array.Empty<object>(), asyncResult); tcs.TrySetResult(null); } catch (Exception e) { tcs.TrySetException(e); } finally { OperationContext.Current = originalOperationContext; } }; try { IAsyncResult ar = ServiceChannel.BeginCall(channel, operation, inputParameters, new AsyncCallback(endCallDelegate), OperationContext.Current); if (ar.CompletedSynchronously && !completedCallback) { endCallDelegate(ar); } } catch (Exception e) { tcs.TrySetException(e); } return tcs.Task; } } private class TaskCompletionSourceProxy { private TaskCompletionSourceInfo _tcsInfo; private object _tcsInstance; public TaskCompletionSourceProxy(Type resultType) { _tcsInfo = TaskCompletionSourceInfo.GetTaskCompletionSourceInfo(resultType); _tcsInstance = Activator.CreateInstance(_tcsInfo.GenericType); } public Task Task { get { return (Task)_tcsInfo.TaskProperty.GetValue(_tcsInstance); } } public bool TrySetResult(object result) { return (bool)_tcsInfo.TrySetResultMethod.Invoke(_tcsInstance, new object[] { result }); } public bool TrySetException(Exception exception) { return (bool)_tcsInfo.TrySetExceptionMethod.Invoke(_tcsInstance, new object[] { exception }); } public bool TrySetCanceled() { return (bool)_tcsInfo.TrySetCanceledMethod.Invoke(_tcsInstance, Array.Empty<object>()); } } private class TaskCompletionSourceInfo { private static ConcurrentDictionary<Type, TaskCompletionSourceInfo> s_cache = new ConcurrentDictionary<Type, TaskCompletionSourceInfo>(); public TaskCompletionSourceInfo(Type resultType) { ResultType = resultType; Type tcsType = typeof(TaskCompletionSource<>); GenericType = tcsType.MakeGenericType(new Type[] { resultType }); TaskProperty = GenericType.GetTypeInfo().GetDeclaredProperty("Task"); TrySetResultMethod = GenericType.GetTypeInfo().GetDeclaredMethod("TrySetResult"); TrySetExceptionMethod = GenericType.GetRuntimeMethod("TrySetException", new Type[] { typeof(Exception) }); TrySetCanceledMethod = GenericType.GetRuntimeMethod("TrySetCanceled", Array.Empty<Type>()); } public Type ResultType { get; private set; } public Type GenericType { get; private set; } public PropertyInfo TaskProperty { get; private set; } public MethodInfo TrySetResultMethod { get; private set; } public MethodInfo TrySetExceptionMethod { get; set; } public MethodInfo TrySetCanceledMethod { get; set; } public static TaskCompletionSourceInfo GetTaskCompletionSourceInfo(Type resultType) { return s_cache.GetOrAdd(resultType, t => new TaskCompletionSourceInfo(t)); } } private object InvokeTaskService(MethodCall methodCall, ProxyOperationRuntime operation) { Task task = TaskCreator.CreateTask(_serviceChannel, methodCall, operation); return task; } private object InvokeChannel(MethodCall methodCall) { string activityName = null; ActivityType activityType = ActivityType.Unknown; if (DiagnosticUtility.ShouldUseActivity) { if (ServiceModelActivity.Current == null || ServiceModelActivity.Current.ActivityType != ActivityType.Close) { MethodData methodData = this.GetMethodData(methodCall); if (methodData.MethodBase.DeclaringType == typeof(System.ServiceModel.ICommunicationObject) && methodData.MethodBase.Name.Equals("Close", StringComparison.Ordinal)) { activityName = SR.Format(SR.ActivityClose, _serviceChannel.GetType().FullName); activityType = ActivityType.Close; } } } using (ServiceModelActivity activity = string.IsNullOrEmpty(activityName) ? null : ServiceModelActivity.CreateBoundedActivity()) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, activityName, activityType); } return ExecuteMessage(_serviceChannel, methodCall); } } private object InvokeGetType(MethodCall methodCall) { return _proxiedType; } private object InvokeBeginService(MethodCall methodCall, ProxyOperationRuntime operation) { AsyncCallback callback; object asyncState; object[] ins = operation.MapAsyncBeginInputs(methodCall, out callback, out asyncState); object ret = _serviceChannel.BeginCall(operation.Action, operation.IsOneWay, operation, ins, callback, asyncState); return ret; } private object InvokeEndService(MethodCall methodCall, ProxyOperationRuntime operation) { IAsyncResult result; object[] outs; operation.MapAsyncEndInputs(methodCall, out result, out outs); object ret = _serviceChannel.EndCall(operation.Action, outs, result); operation.MapAsyncOutputs(methodCall, outs, ref ret); return ret; } private object InvokeService(MethodCall methodCall, ProxyOperationRuntime operation) { object[] outs; object[] ins = operation.MapSyncInputs(methodCall, out outs); object ret = _serviceChannel.Call(operation.Action, operation.IsOneWay, operation, ins, outs); operation.MapSyncOutputs(methodCall, outs, ref ret); return ret; } private object ExecuteMessage(object target, MethodCall methodCall) { MethodBase targetMethod = methodCall.MethodBase; object[] args = methodCall.Args; object returnValue = null; try { returnValue = targetMethod.Invoke(target, args); } catch (TargetInvocationException e) { throw e.InnerException; } return returnValue; } internal class MethodDataCache { private MethodData[] _methodDatas; public MethodDataCache() { _methodDatas = new MethodData[4]; } private object ThisLock { get { return this; } } public bool TryGetMethodData(MethodBase method, out MethodData methodData) { lock (ThisLock) { MethodData[] methodDatas = _methodDatas; int index = FindMethod(methodDatas, method); if (index >= 0) { methodData = methodDatas[index]; return true; } else { methodData = new MethodData(); return false; } } } private static int FindMethod(MethodData[] methodDatas, MethodBase methodToFind) { for (int i = 0; i < methodDatas.Length; i++) { MethodBase method = methodDatas[i].MethodBase; if (method == null) { break; } if (method == methodToFind) { return i; } } return -1; } public void SetMethodData(MethodData methodData) { lock (ThisLock) { int index = FindMethod(_methodDatas, methodData.MethodBase); if (index < 0) { for (int i = 0; i < _methodDatas.Length; i++) { if (_methodDatas[i].MethodBase == null) { _methodDatas[i] = methodData; return; } } MethodData[] newMethodDatas = new MethodData[_methodDatas.Length * 2]; Array.Copy(_methodDatas, newMethodDatas, _methodDatas.Length); newMethodDatas[_methodDatas.Length] = methodData; _methodDatas = newMethodDatas; } } } } internal enum MethodType { Service, BeginService, EndService, Channel, Object, GetType, TaskService } internal struct MethodData { private MethodBase _methodBase; private MethodType _methodType; private ProxyOperationRuntime _operation; public MethodData(MethodBase methodBase, MethodType methodType) : this(methodBase, methodType, null) { } public MethodData(MethodBase methodBase, MethodType methodType, ProxyOperationRuntime operation) { _methodBase = methodBase; _methodType = methodType; _operation = operation; } public MethodBase MethodBase { get { return _methodBase; } } public MethodType MethodType { get { return _methodType; } } public ProxyOperationRuntime Operation { get { return _operation; } } } #region Channel interfaces // These channel methods exist only to implement additional channel interfaces for ServiceChannelProxy. // This is required because clients can down-cast typed proxies to the these channel interfaces. // On the desktop, the .Net Remoting layer allowed that type cast, and subsequent calls against the // interface went back through the RealProxy and invoked the underlying ServiceChannel. // Net Native and CoreClr do not have .Net Remoting and therefore cannot use that mechanism. // But because typed proxies derive from ServiceChannelProxy, implementing these interfaces // on ServiceChannelProxy permits casting the typed proxy to these interfaces. // All interface implementations delegate directly to the underlying ServiceChannel. T IChannel.GetProperty<T>() { return _serviceChannel.GetProperty<T>(); } CommunicationState ICommunicationObject.State { get { return _serviceChannel.State; } } event EventHandler ICommunicationObject.Closed { add { _serviceChannel.Closed += value; } remove { _serviceChannel.Closed -= value; } } event EventHandler ICommunicationObject.Closing { add { _serviceChannel.Closing += value; } remove { _serviceChannel.Closing -= value; } } event EventHandler ICommunicationObject.Faulted { add { _serviceChannel.Faulted += value; } remove { _serviceChannel.Faulted -= value; } } event EventHandler ICommunicationObject.Opened { add { _serviceChannel.Opened += value; } remove { _serviceChannel.Opened -= value; } } event EventHandler ICommunicationObject.Opening { add { _serviceChannel.Opening += value; } remove { _serviceChannel.Opening -= value; } } void ICommunicationObject.Abort() { _serviceChannel.Abort(); } void ICommunicationObject.Close() { _serviceChannel.Close(); } void ICommunicationObject.Close(TimeSpan timeout) { _serviceChannel.Close(timeout); } IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state) { return _serviceChannel.BeginClose(callback, state); } IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return _serviceChannel.BeginClose(timeout, callback, state); } void ICommunicationObject.EndClose(IAsyncResult result) { _serviceChannel.EndClose(result); } void ICommunicationObject.Open() { _serviceChannel.Open(); } void ICommunicationObject.Open(TimeSpan timeout) { _serviceChannel.Open(timeout); } IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state) { return _serviceChannel.BeginOpen(callback, state); } IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return _serviceChannel.BeginOpen(timeout, callback, state); } void ICommunicationObject.EndOpen(IAsyncResult result) { _serviceChannel.EndOpen(result); } bool IClientChannel.AllowInitializationUI { get { return ((IClientChannel)_serviceChannel).AllowInitializationUI; } set { ((IClientChannel)_serviceChannel).AllowInitializationUI = value; } } bool IClientChannel.DidInteractiveInitialization { get { return ((IClientChannel)_serviceChannel).DidInteractiveInitialization; } } Uri IClientChannel.Via { get { return _serviceChannel.Via; } } event EventHandler<UnknownMessageReceivedEventArgs> IClientChannel.UnknownMessageReceived { add { ((IClientChannel)_serviceChannel).UnknownMessageReceived += value; } remove { ((IClientChannel)_serviceChannel).UnknownMessageReceived -= value; } } IAsyncResult IClientChannel.BeginDisplayInitializationUI(AsyncCallback callback, object state) { return _serviceChannel.BeginDisplayInitializationUI(callback, state); } void IClientChannel.DisplayInitializationUI() { _serviceChannel.DisplayInitializationUI(); } void IClientChannel.EndDisplayInitializationUI(IAsyncResult result) { _serviceChannel.EndDisplayInitializationUI(result); } void IDisposable.Dispose() { ((IClientChannel)_serviceChannel).Dispose(); } bool IContextChannel.AllowOutputBatching { get { return ((IContextChannel)_serviceChannel).AllowOutputBatching; } set { ((IContextChannel)_serviceChannel).AllowOutputBatching = value; } } IInputSession IContextChannel.InputSession { get { return ((IContextChannel)_serviceChannel).InputSession; } } EndpointAddress IContextChannel.LocalAddress { get { return ((IContextChannel)_serviceChannel).LocalAddress; } } TimeSpan IContextChannel.OperationTimeout { get { return ((IContextChannel)_serviceChannel).OperationTimeout; } set { ((IContextChannel)_serviceChannel).OperationTimeout = value; } } IOutputSession IContextChannel.OutputSession { get { return ((IContextChannel)_serviceChannel).OutputSession; } } EndpointAddress IOutputChannel.RemoteAddress { get { return ((IContextChannel)_serviceChannel).RemoteAddress; } } Uri IOutputChannel.Via { get { return _serviceChannel.Via; } } EndpointAddress IContextChannel.RemoteAddress { get { return ((IContextChannel)_serviceChannel).RemoteAddress; } } string IContextChannel.SessionId { get { return ((IContextChannel)_serviceChannel).SessionId; } } IExtensionCollection<IContextChannel> IExtensibleObject<IContextChannel>.Extensions { get { return ((IContextChannel)_serviceChannel).Extensions; } } IAsyncResult IOutputChannel.BeginSend(Message message, AsyncCallback callback, object state) { return _serviceChannel.BeginSend(message, callback, state); } IAsyncResult IOutputChannel.BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return _serviceChannel.BeginSend(message, timeout, callback, state); } void IOutputChannel.EndSend(IAsyncResult result) { _serviceChannel.EndSend(result); } void IOutputChannel.Send(Message message) { _serviceChannel.Send(message); } void IOutputChannel.Send(Message message, TimeSpan timeout) { _serviceChannel.Send(message, timeout); } Message IRequestChannel.Request(Message message) { return _serviceChannel.Request(message); } Message IRequestChannel.Request(Message message, TimeSpan timeout) { return _serviceChannel.Request(message, timeout); } IAsyncResult IRequestChannel.BeginRequest(Message message, AsyncCallback callback, object state) { return _serviceChannel.BeginRequest(message, callback, state); } IAsyncResult IRequestChannel.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return _serviceChannel.BeginRequest(message, timeout, callback, state); } Message IRequestChannel.EndRequest(IAsyncResult result) { return _serviceChannel.EndRequest(result); } public IAsyncResult BeginCloseOutputSession(TimeSpan timeout, AsyncCallback callback, object state) { return ((IDuplexContextChannel)_serviceChannel).BeginCloseOutputSession(timeout, callback, state); } public void EndCloseOutputSession(IAsyncResult result) { ((IDuplexContextChannel)_serviceChannel).EndCloseOutputSession(result); } public void CloseOutputSession(TimeSpan timeout) { ((IDuplexContextChannel)_serviceChannel).CloseOutputSession(timeout); } EndpointAddress IRequestChannel.RemoteAddress { get { return ((IContextChannel)_serviceChannel).RemoteAddress; } } Uri IRequestChannel.Via { get { return _serviceChannel.Via; } } Uri IServiceChannel.ListenUri { get { return _serviceChannel.ListenUri; } } public bool AutomaticInputSessionShutdown { get { return ((IDuplexContextChannel)_serviceChannel).AutomaticInputSessionShutdown; } set { ((IDuplexContextChannel)_serviceChannel).AutomaticInputSessionShutdown = value; } } public InstanceContext CallbackInstance { get { return ((IDuplexContextChannel)_serviceChannel).CallbackInstance; } set { ((IDuplexContextChannel)_serviceChannel).CallbackInstance = value; } } #endregion // Channel interfaces } }
using System; using System.Diagnostics; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using Orleans.TestingHost.Utils; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace DefaultCluster.Tests.General { /// <summary> /// Summary description for ObserverTests /// </summary> public class ObserverTests : HostedTestClusterEnsureDefaultStarted { private readonly TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(10); private int callbackCounter; private readonly bool[] callbacksRecieved = new bool[2]; // we keep the observer objects as instance variables to prevent them from // being garbage collected permaturely (the runtime stores them as weak references). private SimpleGrainObserver observer1; private SimpleGrainObserver observer2; public ObserverTests(DefaultClusterFixture fixture) : base(fixture) { } public void TestInitialize() { callbackCounter = 0; callbacksRecieved[0] = false; callbacksRecieved[1] = false; observer1 = null; observer2 = null; } private ISimpleObserverableGrain GetGrain() { return this.GrainFactory.GetGrain<ISimpleObserverableGrain>(GetRandomGrainId()); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_SimpleNotification() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result); ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(this.observer1); await grain.Subscribe(reference); await grain.SetA(3); await grain.SetB(2); Assert.True(await result.WaitForFinished(timeout)); await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_SimpleNotification_GeneratedFactory() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result); ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); await grain.Subscribe(reference); await grain.SetA(3); await grain.SetB(2); Assert.True(await result.WaitForFinished(timeout)); await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); } void ObserverTest_SimpleNotification_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_SimpleNotification_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b); if (a == 3 && b == 0) callbacksRecieved[0] = true; else if (a == 3 && b == 2) callbacksRecieved[1] = true; else throw new ArgumentOutOfRangeException("Unexpected callback with values: a=" + a + ",b=" + b); if (callbackCounter == 1) { // Allow for callbacks occurring in any order Assert.True(callbacksRecieved[0] || callbacksRecieved[1]); } else if (callbackCounter == 2) { Assert.True(callbacksRecieved[0] && callbacksRecieved[1]); result.Done = true; } else { Assert.True(false); } } [Fact, TestCategory("SlowBVT"), TestCategory("Functional")] public async Task ObserverTest_DoubleSubscriptionSameReference() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionSameReference_Callback, result); ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); await grain.Subscribe(reference); await grain.SetA(1); // Use grain try { await grain.Subscribe(reference); } catch (TimeoutException) { throw; } catch (Exception exc) { Exception baseException = exc.GetBaseException(); logger.Info("Received exception: {0}", baseException); Assert.IsAssignableFrom<OrleansException>(baseException); if (!baseException.Message.StartsWith("Cannot subscribe already subscribed observer")) { Assert.True(false, "Unexpected exception message: " + baseException); } } await grain.SetA(2); // Use grain Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetA(2)", timeout)); await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); } void ObserverTest_DoubleSubscriptionSameReference_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_DoubleSubscriptionSameReference_Callback for {0} time with a={1} and b={2}", callbackCounter, a, b); Assert.True(callbackCounter <= 2, "Callback has been called more times than was expected " + callbackCounter); if (callbackCounter == 2) { result.Continue = true; } } [Fact, TestCategory("SlowBVT"), TestCategory("Functional")] public async Task ObserverTest_SubscribeUnsubscribe() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_SubscribeUnsubscribe_Callback, result); ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); await grain.Subscribe(reference); await grain.SetA(5); Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout)); await grain.Unsubscribe(reference); await grain.SetB(3); Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout)); await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); } void ObserverTest_SubscribeUnsubscribe_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_SubscribeUnsubscribe_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b); Assert.True(callbackCounter < 2, "Callback has been called more times than was expected."); Assert.Equal(5, a); Assert.Equal(0, b); result.Continue = true; } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_Unsubscribe() { TestInitialize(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(null, null); ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); try { await grain.Unsubscribe(reference); await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); } catch (TimeoutException) { throw; } catch (Exception exc) { Exception baseException = exc.GetBaseException(); if (!(baseException is OrleansException)) Assert.True(false); } } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_DoubleSubscriptionDifferentReferences() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result); ISimpleGrainObserver reference1 = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); observer2 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result); ISimpleGrainObserver reference2 = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer2); await grain.Subscribe(reference1); await grain.Subscribe(reference2); grain.SetA(6).Ignore(); Assert.True(await result.WaitForFinished(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout)); await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference1); await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference2); } void ObserverTest_DoubleSubscriptionDifferentReferences_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_DoubleSubscriptionDifferentReferences_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b); Assert.True(callbackCounter < 3, "Callback has been called more times than was expected."); Assert.Equal(6, a); Assert.Equal(0, b); if (callbackCounter == 2) result.Done = true; } [Fact, TestCategory("SlowBVT"), TestCategory("Functional")] public async Task ObserverTest_DeleteObject() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_DeleteObject_Callback, result); ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); await grain.Subscribe(reference); await grain.SetA(5); Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout)); await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); await grain.SetB(3); Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout)); } void ObserverTest_DeleteObject_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_DeleteObject_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b); Assert.True(callbackCounter < 2, "Callback has been called more times than was expected."); Assert.Equal(5, a); Assert.Equal(0, b); result.Continue = true; } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_SubscriberMustBeGrainReference() { TestInitialize(); await Xunit.Assert.ThrowsAsync(typeof(NotSupportedException), async () => { var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result); ISimpleGrainObserver reference = observer1; // Should be: this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(obj); await grain.Subscribe(reference); // Not reached }); } internal class SimpleGrainObserver : ISimpleGrainObserver { readonly Action<int, int, AsyncResultHandle> action; readonly AsyncResultHandle result; public SimpleGrainObserver(Action<int, int, AsyncResultHandle> action, AsyncResultHandle result) { this.action = action; this.result = result; } #region ISimpleGrainObserver Members public void StateChanged(int a, int b) { GrainClient.Logger.Verbose("SimpleGrainObserver.StateChanged a={0} b={1}", a, b); action?.Invoke(a, b, result); } #endregion } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Billing { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for InvoicesOperations. /// </summary> public static partial class InvoicesOperationsExtensions { /// <summary> /// Lists the available invoices for a subscription in reverse chronological /// order beginning with the most recent invoice. In preview, invoices are /// available via this API only for invoice periods which end December 1, 2016 /// or later. /// <see href="https://go.microsoft.com/fwlink/?linkid=842057" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='expand'> /// May be used to expand the downloadUrl property within a list of invoices. /// This enables download links to be generated for multiple invoices at once. /// By default, downloadURLs are not included when listing invoices. /// </param> /// <param name='filter'> /// May be used to filter invoices by invoicePeriodEndDate. The filter supports /// 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support /// 'ne', 'or', or 'not'. /// </param> /// <param name='skiptoken'> /// Skiptoken is only used if a previous operation returned a partial result. /// If a previous response contains a nextLink element, the value of the /// nextLink element will include a skiptoken parameter that specifies a /// starting point to use for subsequent calls. /// </param> /// <param name='top'> /// May be used to limit the number of results to the most recent N invoices. /// </param> public static IPage<Invoice> List(this IInvoicesOperations operations, string expand = default(string), string filter = default(string), string skiptoken = default(string), int? top = default(int?)) { return operations.ListAsync(expand, filter, skiptoken, top).GetAwaiter().GetResult(); } /// <summary> /// Lists the available invoices for a subscription in reverse chronological /// order beginning with the most recent invoice. In preview, invoices are /// available via this API only for invoice periods which end December 1, 2016 /// or later. /// <see href="https://go.microsoft.com/fwlink/?linkid=842057" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='expand'> /// May be used to expand the downloadUrl property within a list of invoices. /// This enables download links to be generated for multiple invoices at once. /// By default, downloadURLs are not included when listing invoices. /// </param> /// <param name='filter'> /// May be used to filter invoices by invoicePeriodEndDate. The filter supports /// 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support /// 'ne', 'or', or 'not'. /// </param> /// <param name='skiptoken'> /// Skiptoken is only used if a previous operation returned a partial result. /// If a previous response contains a nextLink element, the value of the /// nextLink element will include a skiptoken parameter that specifies a /// starting point to use for subsequent calls. /// </param> /// <param name='top'> /// May be used to limit the number of results to the most recent N invoices. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Invoice>> ListAsync(this IInvoicesOperations operations, string expand = default(string), string filter = default(string), string skiptoken = default(string), int? top = default(int?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(expand, filter, skiptoken, top, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a named invoice resource. When getting a single invoice, the /// downloadUrl property is expanded automatically. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='invoiceName'> /// The name of an invoice resource. /// </param> public static Invoice Get(this IInvoicesOperations operations, string invoiceName) { return operations.GetAsync(invoiceName).GetAwaiter().GetResult(); } /// <summary> /// Gets a named invoice resource. When getting a single invoice, the /// downloadUrl property is expanded automatically. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='invoiceName'> /// The name of an invoice resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Invoice> GetAsync(this IInvoicesOperations operations, string invoiceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(invoiceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the most recent invoice. When getting a single invoice, the /// downloadUrl property is expanded automatically. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Invoice GetLatest(this IInvoicesOperations operations) { return operations.GetLatestAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets the most recent invoice. When getting a single invoice, the /// downloadUrl property is expanded automatically. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Invoice> GetLatestAsync(this IInvoicesOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLatestWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the available invoices for a subscription in reverse chronological /// order beginning with the most recent invoice. In preview, invoices are /// available via this API only for invoice periods which end December 1, 2016 /// or later. /// <see href="https://go.microsoft.com/fwlink/?linkid=842057" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Invoice> ListNext(this IInvoicesOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists the available invoices for a subscription in reverse chronological /// order beginning with the most recent invoice. In preview, invoices are /// available via this API only for invoice periods which end December 1, 2016 /// or later. /// <see href="https://go.microsoft.com/fwlink/?linkid=842057" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Invoice>> ListNextAsync(this IInvoicesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Lucene version compatibility level 4.8.1 using J2N.Collections.Generic.Extensions; using Lucene.Net.Analysis.Core; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Analysis.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Abstract parent class for analysis factories <see cref="TokenizerFactory"/>, /// <see cref="TokenFilterFactory"/> and <see cref="CharFilterFactory"/>. /// <para> /// The typical lifecycle for a factory consumer is: /// <list type="bullet"> /// <item><description>Create factory via its constructor (or via XXXFactory.ForName)</description></item> /// <item><description>(Optional) If the factory uses resources such as files, /// <see cref="IResourceLoaderAware.Inform(IResourceLoader)"/> is called to initialize those resources.</description></item> /// <item><description>Consumer calls create() to obtain instances.</description></item> /// </list> /// </para> /// </summary> public abstract class AbstractAnalysisFactory { public const string LUCENE_MATCH_VERSION_PARAM = "luceneMatchVersion"; /// <summary> /// The original args, before any processing </summary> private readonly IDictionary<string, string> originalArgs; /// <summary> /// the luceneVersion arg </summary> protected readonly LuceneVersion m_luceneMatchVersion; /// <summary> /// Initialize this factory via a set of key-value pairs. /// </summary> protected AbstractAnalysisFactory(IDictionary<string, string> args) { IsExplicitLuceneMatchVersion = false; originalArgs = args.AsReadOnly(); string version = Get(args, LUCENE_MATCH_VERSION_PARAM); // LUCENENET TODO: What should we do if the version is null? //luceneMatchVersion = version == null ? (LuceneVersion?)null : LuceneVersionHelpers.ParseLeniently(version); m_luceneMatchVersion = version == null ? #pragma warning disable 612, 618 LuceneVersion.LUCENE_CURRENT : #pragma warning restore 612, 618 LuceneVersionExtensions.ParseLeniently(version); args.Remove(CLASS_NAME); // consume the class arg } public IDictionary<string, string> OriginalArgs => originalArgs; /// <summary> /// this method can be called in the <see cref="TokenizerFactory.Create(TextReader)"/> /// or <see cref="TokenFilterFactory.Create(TokenStream)"/> methods, /// to inform user, that for this factory a <see cref="m_luceneMatchVersion"/> is required /// </summary> protected void AssureMatchVersion() // LUCENENET TODO: Remove this method (not used anyway in .NET) { // LUCENENET NOTE: since luceneMatchVersion can never be null in .NET, // this method effectively does nothing. However, leaving it in place because // it is used throughout Lucene. //if (luceneMatchVersion == null) //{ // throw new ArgumentException("Configuration Error: Factory '" + this.GetType().FullName + "' needs a 'luceneMatchVersion' parameter"); //} } public LuceneVersion LuceneMatchVersion => this.m_luceneMatchVersion; public virtual string Require(IDictionary<string, string> args, string name) { if (!args.TryGetValue(name, out string s)) throw new ArgumentException($"Configuration Error: missing parameter '{name}'"); args.Remove(name); return s; } public virtual string Require(IDictionary<string, string> args, string name, ICollection<string> allowedValues) { return Require(args, name, allowedValues, true); } public virtual string Require(IDictionary<string, string> args, string name, ICollection<string> allowedValues, bool caseSensitive) { if (!args.TryGetValue(name, out string s)) throw new ArgumentException($"Configuration Error: missing parameter '{name}'"); args.Remove(name); foreach (var allowedValue in allowedValues) { if (caseSensitive) { if (s.Equals(allowedValue, StringComparison.Ordinal)) return s; } else { if (s.Equals(allowedValue, StringComparison.OrdinalIgnoreCase)) return s; } } throw new ArgumentException($"Configuration Error: '{name}' value must be one of {Collections.ToString(allowedValues)}"); } public virtual string Get(IDictionary<string, string> args, string name, string defaultVal = null) { if (args.TryGetValue(name, out string s)) args.Remove(name); return s ?? defaultVal; } public virtual string Get(IDictionary<string, string> args, string name, ICollection<string> allowedValues) { return Get(args, name, allowedValues, defaultVal: null); } public virtual string Get(IDictionary<string, string> args, string name, ICollection<string> allowedValues, string defaultVal) { return Get(args, name, allowedValues, defaultVal, caseSensitive: true); } public virtual string Get(IDictionary<string, string> args, string name, ICollection<string> allowedValues, string defaultVal, bool caseSensitive) { if (!args.TryGetValue(name, out string s) || s is null) { return defaultVal; } else { args.Remove(name); foreach (string allowedValue in allowedValues) { if (caseSensitive) { if (s.Equals(allowedValue, StringComparison.Ordinal)) { return s; } } else { if (s.Equals(allowedValue, StringComparison.OrdinalIgnoreCase)) { return s; } } } throw new ArgumentException($"Configuration Error: '{name}' value must be one of {Collections.ToString(allowedValues)}"); } } /// <summary> /// NOTE: This was requireInt() in Lucene /// </summary> protected int RequireInt32(IDictionary<string, string> args, string name) { return int.Parse(Require(args, name), CultureInfo.InvariantCulture); } /// <summary> /// NOTE: This was getInt() in Lucene /// </summary> protected int GetInt32(IDictionary<string, string> args, string name, int defaultVal) { if (args.TryGetValue(name, out string s)) { args.Remove(name); return int.Parse(s, CultureInfo.InvariantCulture); } return defaultVal; } protected bool RequireBoolean(IDictionary<string, string> args, string name) { return bool.Parse(Require(args, name)); } protected bool GetBoolean(IDictionary<string, string> args, string name, bool defaultVal) { if (args.TryGetValue(name, out string s)) { args.Remove(name); return bool.Parse(s); } return defaultVal; } /// <summary> /// NOTE: This was requireFloat() in Lucene /// </summary> protected float RequireSingle(IDictionary<string, string> args, string name) { return float.Parse(Require(args, name), CultureInfo.InvariantCulture); } /// <summary> /// NOTE: This was getFloat() in Lucene /// </summary> protected float GetSingle(IDictionary<string, string> args, string name, float defaultVal) { if (args.TryGetValue(name, out string s)) { args.Remove(name); return float.Parse(s, CultureInfo.InvariantCulture); } return defaultVal; } public virtual char RequireChar(IDictionary<string, string> args, string name) { return Require(args, name)[0]; } public virtual char GetChar(IDictionary<string, string> args, string name, char defaultVal) { if (args.TryGetValue(name, out string s)) { args.Remove(name); if (s.Length != 1) { throw new ArgumentException($"{name} should be a char. \"{s}\" is invalid"); } else { return s[0]; } } return defaultVal; } private static readonly Regex ITEM_PATTERN = new Regex("[^,\\s]+", RegexOptions.Compiled); /// <summary> /// Returns whitespace- and/or comma-separated set of values, or null if none are found </summary> public virtual ISet<string> GetSet(IDictionary<string, string> args, string name) { if (args.TryGetValue(name, out string s)) { args.Remove(name); ISet<string> set = null; Match matcher = ITEM_PATTERN.Match(s); if (matcher.Success) { set = new JCG.HashSet<string> { matcher.Groups[0].Value }; matcher = matcher.NextMatch(); while (matcher.Success) { set.Add(matcher.Groups[0].Value); matcher = matcher.NextMatch(); } } return set; } return null; } /// <summary> /// Compiles a pattern for the value of the specified argument key <paramref name="name"/> /// </summary> protected Regex GetPattern(IDictionary<string, string> args, string name) { try { return new Regex(Require(args, name), RegexOptions.Compiled); } catch (Exception e) { throw new ArgumentException("Configuration Error: '" + name + "' can not be parsed in " + this.GetType().Name, e); } } /// <summary> /// Gets a <see cref="CultureInfo"/> value of the specified argument key <paramref name="name"/>. /// <para/> /// To specify the invariant culture, pass the string <c>"invariant"</c>. /// <para/> /// LUCENENET specific /// </summary> protected CultureInfo GetCulture(IDictionary<string, string> args, string name, CultureInfo defaultVal) { if (args.TryGetValue(name, out string culture)) { args.Remove(name); try { if (culture.Equals("invariant", StringComparison.Ordinal)) { return CultureInfo.InvariantCulture; } return new CultureInfo(culture); } catch (Exception e) { throw new ArgumentException("Configuration Error: '" + name + "' can not be parsed in " + this.GetType().Name, e); } } return defaultVal; } /// <summary> /// Returns as <see cref="CharArraySet"/> from wordFiles, which /// can be a comma-separated list of filenames /// </summary> protected CharArraySet GetWordSet(IResourceLoader loader, string wordFiles, bool ignoreCase) { AssureMatchVersion(); IList<string> files = SplitFileNames(wordFiles); CharArraySet words = null; if (files.Count > 0) { // default stopwords list has 35 or so words, but maybe don't make it that // big to start words = new CharArraySet(m_luceneMatchVersion, files.Count * 10, ignoreCase); foreach (string file in files) { var wlist = GetLines(loader, file.Trim()); words.UnionWith(StopFilter.MakeStopSet(m_luceneMatchVersion, wlist, ignoreCase)); } } return words; } /// <summary> /// Returns the resource's lines (with content treated as UTF-8) /// </summary> protected IList<string> GetLines(IResourceLoader loader, string resource) { return WordlistLoader.GetLines(loader.OpenResource(resource), Encoding.UTF8); } /// <summary> /// Same as <see cref="GetWordSet(IResourceLoader, string, bool)"/>, /// except the input is in snowball format. /// </summary> protected CharArraySet GetSnowballWordSet(IResourceLoader loader, string wordFiles, bool ignoreCase) { AssureMatchVersion(); IList<string> files = SplitFileNames(wordFiles); CharArraySet words = null; if (files.Count > 0) { // default stopwords list has 35 or so words, but maybe don't make it that // big to start words = new CharArraySet(m_luceneMatchVersion, files.Count * 10, ignoreCase); foreach (string file in files) { using (Stream stream = loader.OpenResource(file.Trim())) using (TextReader reader = new StreamReader(stream, Encoding.UTF8)) { WordlistLoader.GetSnowballWordSet(reader, words); } } } return words; } /// <summary> /// Splits file names separated by comma character. /// File names can contain comma characters escaped by backslash '\' /// </summary> /// <param name="fileNames"> the string containing file names </param> /// <returns> a list of file names with the escaping backslashed removed </returns> protected IList<string> SplitFileNames(string fileNames) { if (fileNames == null) { return Collections.EmptyList<string>(); } IList<string> result = new List<string>(); foreach (string file in SplitFileNameHolder.FILE_SPLIT_PATTERN.Split(fileNames)) { result.Add(SplitFileNameHolder.FILE_REPLACE_PATTERN.Replace(file, string.Empty)); } return result; } // LUCENENET specific - optimize compilation and lazy-load the regular expressions private static class SplitFileNameHolder { public static readonly Regex FILE_SPLIT_PATTERN = new Regex("(?<!\\\\),", RegexOptions.Compiled | RegexOptions.CultureInvariant); public static readonly Regex FILE_REPLACE_PATTERN = new Regex("\\\\(?=,)", RegexOptions.Compiled | RegexOptions.CultureInvariant); } private const string CLASS_NAME = "class"; /// <returns> the string used to specify the concrete class name in a serialized representation: the class arg. /// If the concrete class name was not specified via a class arg, returns <c>GetType().Name</c>. </returns> public virtual string GetClassArg() { if (null != originalArgs) { string className = originalArgs[CLASS_NAME]; if (null != className) { return className; } } return this.GetType().Name; } public virtual bool IsExplicitLuceneMatchVersion { get; set; } } }
using System; using System.Reflection; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.IO; using System.Runtime.Remoting; using System.Threading; using System.Globalization; namespace Alchemi.Updater { /// <summary> /// Summary description for AppKeys. /// </summary> //************************************************************** // AppKeys Class // Used to validate downloaded assemblies. On initialization, // a list of valid keys is built up by using the main entry // point assemblies keys and any keys in the remote AppUpdaterKeys.dll. // Validation is done in a seperate appdomain to prevent collision // with assemblies already loaded in the current app domain. //************************************************************** public class AppKeys { private const string KEYFILENAME = "AppUpdaterKeys.dll"; private AppDomain AD; private byte[][] KeyList; private string[] ExceptionList; private KeyValidator Validator; private string AppUrl; public AppKeys(string appUrl) { AppUrl = appUrl; } //************************************************************** // InitializeKeyCheck() //************************************************************** public void InitializeKeyCheck() { //Clear any previous app domain UnInitializeKeyCheck(); AD = AppDomain.CreateDomain("KeyValidatorDomain"); BindingFlags flags = (BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance); ObjectHandle objh = AD.CreateInstance( "AppUpdater", "Microsoft.Samples.AppUpdater.KeyValidator", false, flags, null, null, null, null, null); // Unwrap the object Object obj = objh.Unwrap(); // Cast to the actual type Validator = (KeyValidator)obj; KeyList = GetKeyList(AppUrl.TrimEnd(new char[] {'/'}) + "/" + KEYFILENAME); } //************************************************************** // UnInitializeKeyCheck() //************************************************************** public void UnInitializeKeyCheck() { if (AD != null) { AppDomain.Unload(AD); //Gives the async Unload call some time to complete, //only effects whether older versions are cleaned up or not. Thread.Sleep(TimeSpan.FromSeconds(2)); AD = null; } } //************************************************************** // ValidateAssembly() //************************************************************** public bool ValidateAssembly(string assemblyLocation) { //Check the assembly using the Validator object running in //the other appdomain return (Validator.Validate(assemblyLocation,KeyList,ExceptionList)); } //************************************************************** // GetKeyList() //************************************************************** public byte[][] GetKeyList(string keyFileUrl) { byte[][] RemoteKeys = null; try { //Load the remote key assembly AssemblyName AN = new AssemblyName(); AN.CodeBase = keyFileUrl; Assembly KeyAssembly = AD.Load(AN); //Validate the Assembly was signed w/ the same public key as the main assembly if (KeyValidator.CompareKeys(KeyAssembly.GetName().GetPublicKey(), new Byte[][] {Assembly.GetEntryAssembly().GetName().GetPublicKey()})) { //Get the keys out of the assembly Type T = KeyAssembly.GetType("Microsoft.Samples.AppUpdater.KeyList"); RemoteKeys = (byte[][]) T.GetField("Keys").GetValue(null); //Get the list of file exceptions ExceptionList = (string[]) T.GetField("ExceptionList").GetValue(null); } } catch (Exception) { Debug.WriteLine("APPMANAGER: No remote keys found."); } byte[][] Keys = null; if (RemoteKeys != null) { Keys = new byte[RemoteKeys.Length+1][]; Keys[0] = Assembly.GetEntryAssembly().GetName().GetPublicKey(); RemoteKeys.CopyTo(Keys,1); } else { Keys = new byte[1][]; Keys[0] = Assembly.GetEntryAssembly().GetName().GetPublicKey(); } return Keys; } } //************************************************************** // KeyValidator Class //************************************************************** public class KeyValidator : MarshalByRefObject { //************************************************************** // KeyValidator //************************************************************** public KeyValidator() { } //************************************************************** // Validate() // Meant to be called in it's own app domain //************************************************************** public bool Validate(string assemblyLocation, byte[][] keyList, string[] ExceptionList) { try { //If the file is in the exception list, return true; if (IsException(assemblyLocation,ExceptionList)) return true; Assembly A = Assembly.LoadFrom(assemblyLocation); return (CompareKeys(A.GetName().GetPublicKey(),keyList)); } catch (Exception e) { Debug.WriteLine("APPMANAGER: Key check failed for : " + assemblyLocation); Debug.WriteLine("APPMANAGER: " + e.ToString()); //The file isn't an assembly & not in the exception list return false; } } //************************************************************** // IsException() - static helper function //************************************************************** public static bool IsException(string FilePath, string[] ExceptionList) { //Empty ExceptionList case if (ExceptionList == null) return false; foreach (string exceptionFile in ExceptionList) { if (Path.GetFileName(FilePath).ToLower(new CultureInfo("en-US")) == exceptionFile.ToLower(new CultureInfo("en-US"))) { return true; } } return false; } //************************************************************** // CompareKeys() - static helper function //************************************************************** public static bool CompareKeys(byte[] assemblyKey, byte[][]validKeys) { try { ASCIIEncoding AE = new ASCIIEncoding(); foreach (byte[] Key in validKeys) { if (AE.GetString(Key) == AE.GetString(assemblyKey)) return true; } return false; } catch (Exception e) { Debug.WriteLine("APPMANAGER: :" + e.ToString()); return false; } } } }
using System; namespace Umbraco.Cms.Core { public static partial class Constants { public static class DataTypes { //NOTE: unfortunately due to backwards compat we can't move/rename these, with the addition of the GUID //constants, it would make more sense to have these suffixed with "ID" or in a Subclass called "INT", for //now all we can do is make a subclass called Guids to put the GUID IDs. public const int LabelString = System.DefaultLabelDataTypeId; public const int LabelInt = -91; public const int LabelBigint = -93; public const int LabelDateTime = -94; public const int LabelTime = -98; public const int LabelDecimal = -99; public const int Textarea = -89; public const int Textbox = -88; public const int RichtextEditor = -87; public const int Boolean = -49; public const int DateTime = -36; public const int DropDownSingle = -39; public const int DropDownMultiple = -42; public const int Upload = -90; public const int UploadVideo = -100; public const int UploadAudio = -101; public const int UploadArticle = -102; public const int UploadVectorGraphics = -103; public const int DefaultContentListView = -95; public const int DefaultMediaListView = -96; public const int DefaultMembersListView = -97; public const int ImageCropper = 1043; public const int Tags = 1041; public static class ReservedPreValueKeys { public const string IgnoreUserStartNodes = "ignoreUserStartNodes"; } /// <summary> /// Defines the identifiers for Umbraco data types as constants for easy centralized access/management. /// </summary> public static class Guids { /// <summary> /// Guid for Content Picker as string /// </summary> public const string ContentPicker = "FD1E0DA5-5606-4862-B679-5D0CF3A52A59"; /// <summary> /// Guid for Content Picker /// </summary> public static readonly Guid ContentPickerGuid = new Guid(ContentPicker); /// <summary> /// Guid for Member Picker as string /// </summary> public const string MemberPicker = "1EA2E01F-EBD8-4CE1-8D71-6B1149E63548"; /// <summary> /// Guid for Member Picker /// </summary> public static readonly Guid MemberPickerGuid = new Guid(MemberPicker); /// <summary> /// Guid for Media Picker as string /// </summary> public const string MediaPicker = "135D60E0-64D9-49ED-AB08-893C9BA44AE5"; /// <summary> /// Guid for Media Picker /// </summary> public static readonly Guid MediaPickerGuid = new Guid(MediaPicker); /// <summary> /// Guid for Multiple Media Picker as string /// </summary> public const string MultipleMediaPicker = "9DBBCBBB-2327-434A-B355-AF1B84E5010A"; /// <summary> /// Guid for Multiple Media Picker /// </summary> public static readonly Guid MultipleMediaPickerGuid = new Guid(MultipleMediaPicker); /// <summary> /// Guid for Media Picker v3 as string /// </summary> public const string MediaPicker3 = "4309A3EA-0D78-4329-A06C-C80B036AF19A"; /// <summary> /// Guid for Media Picker v3 /// </summary> public static readonly Guid MediaPicker3Guid = new Guid(MediaPicker3); /// <summary> /// Guid for Media Picker v3 multiple as string /// </summary> public const string MediaPicker3Multiple = "1B661F40-2242-4B44-B9CB-3990EE2B13C0"; /// <summary> /// Guid for Media Picker v3 multiple /// </summary> public static readonly Guid MediaPicker3MultipleGuid = new Guid(MediaPicker3Multiple); /// <summary> /// Guid for Media Picker v3 single-image as string /// </summary> public const string MediaPicker3SingleImage = "AD9F0CF2-BDA2-45D5-9EA1-A63CFC873FD3"; /// <summary> /// Guid for Media Picker v3 single-image /// </summary> public static readonly Guid MediaPicker3SingleImageGuid = new Guid(MediaPicker3SingleImage); /// <summary> /// Guid for Media Picker v3 multi-image as string /// </summary> public const string MediaPicker3MultipleImages = "0E63D883-B62B-4799-88C3-157F82E83ECC"; /// <summary> /// Guid for Media Picker v3 multi-image /// </summary> public static readonly Guid MediaPicker3MultipleImagesGuid = new Guid(MediaPicker3MultipleImages); /// <summary> /// Guid for Related Links as string /// </summary> public const string RelatedLinks = "B4E3535A-1753-47E2-8568-602CF8CFEE6F"; /// <summary> /// Guid for Related Links /// </summary> public static readonly Guid RelatedLinksGuid = new Guid(RelatedLinks); /// <summary> /// Guid for Member as string /// </summary> public const string Member = "d59be02f-1df9-4228-aa1e-01917d806cda"; /// <summary> /// Guid for Member /// </summary> public static readonly Guid MemberGuid = new Guid(Member); /// <summary> /// Guid for Image Cropper as string /// </summary> public const string ImageCropper = "1df9f033-e6d4-451f-b8d2-e0cbc50a836f"; /// <summary> /// Guid for Image Cropper /// </summary> public static readonly Guid ImageCropperGuid = new Guid(ImageCropper); /// <summary> /// Guid for Tags as string /// </summary> public const string Tags = "b6b73142-b9c1-4bf8-a16d-e1c23320b549"; /// <summary> /// Guid for Tags /// </summary> public static readonly Guid TagsGuid = new Guid(Tags); /// <summary> /// Guid for List View - Content as string /// </summary> public const string ListViewContent = "C0808DD3-8133-4E4B-8CE8-E2BEA84A96A4"; /// <summary> /// Guid for List View - Content /// </summary> public static readonly Guid ListViewContentGuid = new Guid(ListViewContent); /// <summary> /// Guid for List View - Media as string /// </summary> public const string ListViewMedia = "3A0156C4-3B8C-4803-BDC1-6871FAA83FFF"; /// <summary> /// Guid for List View - Media /// </summary> public static readonly Guid ListViewMediaGuid = new Guid(ListViewMedia); /// <summary> /// Guid for List View - Members as string /// </summary> public const string ListViewMembers = "AA2C52A0-CE87-4E65-A47C-7DF09358585D"; /// <summary> /// Guid for List View - Members /// </summary> public static readonly Guid ListViewMembersGuid = new Guid(ListViewMembers); /// <summary> /// Guid for Date Picker with time as string /// </summary> public const string DatePickerWithTime = "e4d66c0f-b935-4200-81f0-025f7256b89a"; /// <summary> /// Guid for Date Picker with time /// </summary> public static readonly Guid DatePickerWithTimeGuid = new Guid(DatePickerWithTime); /// <summary> /// Guid for Approved Color as string /// </summary> public const string ApprovedColor = "0225af17-b302-49cb-9176-b9f35cab9c17"; /// <summary> /// Guid for Approved Color /// </summary> public static readonly Guid ApprovedColorGuid = new Guid(ApprovedColor); /// <summary> /// Guid for Dropdown multiple as string /// </summary> public const string DropdownMultiple = "f38f0ac7-1d27-439c-9f3f-089cd8825a53"; /// <summary> /// Guid for Dropdown multiple /// </summary> public static readonly Guid DropdownMultipleGuid = new Guid(DropdownMultiple); /// <summary> /// Guid for Radiobox as string /// </summary> public const string Radiobox = "bb5f57c9-ce2b-4bb9-b697-4caca783a805"; /// <summary> /// Guid for Radiobox /// </summary> public static readonly Guid RadioboxGuid = new Guid(Radiobox); /// <summary> /// Guid for Date Picker as string /// </summary> public const string DatePicker = "5046194e-4237-453c-a547-15db3a07c4e1"; /// <summary> /// Guid for Date Picker /// </summary> public static readonly Guid DatePickerGuid = new Guid(DatePicker); /// <summary> /// Guid for Dropdown as string /// </summary> public const string Dropdown = "0b6a45e7-44ba-430d-9da5-4e46060b9e03"; /// <summary> /// Guid for Dropdown /// </summary> public static readonly Guid DropdownGuid = new Guid(Dropdown); /// <summary> /// Guid for Checkbox list as string /// </summary> public const string CheckboxList = "fbaf13a8-4036-41f2-93a3-974f678c312a"; /// <summary> /// Guid for Checkbox list /// </summary> public static readonly Guid CheckboxListGuid = new Guid(CheckboxList); /// <summary> /// Guid for Checkbox as string /// </summary> public const string Checkbox = "92897bc6-a5f3-4ffe-ae27-f2e7e33dda49"; /// <summary> /// Guid for Checkbox /// </summary> public static readonly Guid CheckboxGuid = new Guid(Checkbox); /// <summary> /// Guid for Numeric as string /// </summary> public const string Numeric = "2e6d3631-066e-44b8-aec4-96f09099b2b5"; /// <summary> /// Guid for Dropdown /// </summary> public static readonly Guid NumericGuid = new Guid(Numeric); /// <summary> /// Guid for Richtext editor as string /// </summary> public const string RichtextEditor = "ca90c950-0aff-4e72-b976-a30b1ac57dad"; /// <summary> /// Guid for Richtext editor /// </summary> public static readonly Guid RichtextEditorGuid = new Guid(RichtextEditor); /// <summary> /// Guid for Textstring as string /// </summary> public const string Textstring = "0cc0eba1-9960-42c9-bf9b-60e150b429ae"; /// <summary> /// Guid for Textstring /// </summary> public static readonly Guid TextstringGuid = new Guid(Textstring); /// <summary> /// Guid for Textarea as string /// </summary> public const string Textarea = "c6bac0dd-4ab9-45b1-8e30-e4b619ee5da3"; /// <summary> /// Guid for Dropdown /// </summary> public static readonly Guid TextareaGuid = new Guid(Textarea); /// <summary> /// Guid for Upload as string /// </summary> public const string Upload = "84c6b441-31df-4ffe-b67e-67d5bc3ae65a"; /// <summary> /// Guid for Upload /// </summary> public static readonly Guid UploadGuid = new Guid(Upload); /// <summary> /// Guid for UploadVideo as string /// </summary> public const string UploadVideo = "70575fe7-9812-4396-bbe1-c81a76db71b5"; /// <summary> /// Guid for UploadVideo /// </summary> public static readonly Guid UploadVideoGuid = new Guid(UploadVideo); /// <summary> /// Guid for UploadAudio as string /// </summary> public const string UploadAudio = "8f430dd6-4e96-447e-9dc0-cb552c8cd1f3"; /// <summary> /// Guid for UploadAudio /// </summary> public static readonly Guid UploadAudioGuid = new Guid(UploadAudio); /// <summary> /// Guid for UploadArticle as string /// </summary> public const string UploadArticle = "bc1e266c-dac4-4164-bf08-8a1ec6a7143d"; /// <summary> /// Guid for UploadArticle /// </summary> public static readonly Guid UploadArticleGuid = new Guid(UploadArticle); /// <summary> /// Guid for UploadVectorGraphics as string /// </summary> public const string UploadVectorGraphics = "215cb418-2153-4429-9aef-8c0f0041191b"; /// <summary> /// Guid for UploadVectorGraphics /// </summary> public static readonly Guid UploadVectorGraphicsGuid = new Guid(UploadVectorGraphics); /// <summary> /// Guid for Label as string /// </summary> public const string LabelString = "f0bc4bfb-b499-40d6-ba86-058885a5178c"; /// <summary> /// Guid for Label string /// </summary> public static readonly Guid LabelStringGuid = new Guid(LabelString); /// <summary> /// Guid for Label as int /// </summary> public const string LabelInt = "8e7f995c-bd81-4627-9932-c40e568ec788"; /// <summary> /// Guid for Label int /// </summary> public static readonly Guid LabelIntGuid = new Guid(LabelInt); /// <summary> /// Guid for Label as big int /// </summary> public const string LabelBigInt = "930861bf-e262-4ead-a704-f99453565708"; /// <summary> /// Guid for Label big int /// </summary> public static readonly Guid LabelBigIntGuid = new Guid(LabelBigInt); /// <summary> /// Guid for Label as date time /// </summary> public const string LabelDateTime = "0e9794eb-f9b5-4f20-a788-93acd233a7e4"; /// <summary> /// Guid for Label date time /// </summary> public static readonly Guid LabelDateTimeGuid = new Guid(LabelDateTime); /// <summary> /// Guid for Label as time /// </summary> public const string LabelTime = "a97cec69-9b71-4c30-8b12-ec398860d7e8"; /// <summary> /// Guid for Label time /// </summary> public static readonly Guid LabelTimeGuid = new Guid(LabelTime); /// <summary> /// Guid for Label as decimal /// </summary> public const string LabelDecimal = "8f1ef1e1-9de4-40d3-a072-6673f631ca64"; /// <summary> /// Guid for Label decimal /// </summary> public static readonly Guid LabelDecimalGuid = new Guid(LabelDecimal); } } } }
/* Copyright (c) 2009, hkrn 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 hkrn 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 REGENTS 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. */ // // $Id: Channel.cs 138 2009-08-22 13:31:42Z hikarin $ // using System; using SlMML.Modulators; namespace SlMML { public enum ChannelOutputMode { Default = 0, Overwrite = 1, Add = 2 } public class Channel { #region constants public const int PITCH_RESOLUTION = 100; public const int VELOCITY_MAX = 128; public const int VELOCITY_MAX2 = VELOCITY_MAX - 1; #endregion #region public class methods public static void Initialize(int nbSamples) { if (!s_initialized) { int i = 0; s_sampleLength = nbSamples; s_samples = new double[nbSamples]; s_frequencyLength = s_frequencyMap.Length; for (i = 0; i < s_frequencyLength; i++) s_frequencyMap[i] = Sample.FREQUENCY_BASE * Math.Pow(2.0, (i - 69.0 * PITCH_RESOLUTION) / (12.0 * PITCH_RESOLUTION)); s_volumeLength = VELOCITY_MAX; s_volumeMap[0] = 0.0; for (i = 1; i < s_volumeLength; i++) s_volumeMap[i] = Math.Pow(10.0, (i - VELOCITY_MAX2) * (48.0 / (VELOCITY_MAX2 * 20.0))); s_pipeArray = null; s_initialized = true; } } public static void Release() { s_pipeArray = null; s_samples = null; } public static void CreatePipes(int number) { s_pipeArray = new double[number][]; s_pipeArrayNum = number; for (int i = 0; i < number; i++) { s_pipeArray[i] = new double[s_sampleLength]; for (int j = 0; j < s_sampleLength; j++) s_pipeArray[i][j] = 0; } } public static void CreateSyncSources(int number) { s_syncSource = new bool[number][]; s_syncSourceLength = number; for (int i = 0; i < number; i++) { s_syncSource[i] = new bool[s_sampleLength]; for (int j = 0; j < s_sampleLength; j++) s_syncSource[i][j] = false; } } public static double FrequencyFromIndex(int index) { index = Math.Min(Math.Max(index, 0), Math.Max(s_frequencyLength, 1) - 1); return s_frequencyMap[index]; } #endregion #region constructors and destructor public Channel() { m_vco = new Envelope(0.0, 60.0 / VELOCITY_MAX2, 30.0 / VELOCITY_MAX2, 1.0 / VELOCITY_MAX2); m_vcf = new Envelope(0.0, 30.0 / VELOCITY_MAX2, 0.0, 1.0); m_osc1 = new Oscillator(); m_mod1 = m_osc1.CurrentModulator; m_osc2 = new Oscillator() { Form = OscillatorForm.Sine }; m_osc2.MakeAsLFO(); m_mod2 = m_osc2.CurrentModulator; m_filter = new Filter(); m_osc2connect = m_enableFilter = false; m_formant = new Formant(); m_volumeMode = 0; m_expression = 0; m_onCounter = 0; m_lfoDelay = 0; m_lfoDepth = 0; m_lfoEnd = 0; m_lpfAmount = 0; m_lpfFrequency = 0; m_lpfResonance = 0; NoteIndex = 0; Detune = 0; m_frequencyIndex = 0; Pan = 64; Expression = 127; Velocity = 100; Input = new Events.Input() { Sens = 0, Pipe = 0 }; Output = new Events.Output() { Mode = ChannelOutputMode.Default, Pipe = 0 }; Ring = new Events.Ring() { Sens = 0, Pipe = 0 }; Sync = new Events.Sync() { Mode = ChannelOutputMode.Default, Pipe = 0 }; } #endregion #region public methods public void EnableNote(Events.NoteOn noteOn) { int index = noteOn.Index, velocity = noteOn.Velocity; NoteIndex = index; m_vco.Trigger(false); m_vcf.Trigger(true); m_mod1.ResetPhase(); m_mod2.ResetPhase(); m_filter.Reset(); m_onCounter = 0; Velocity = velocity; FCNoise fcNoise = (FCNoise)m_osc1.ModulatorFromForm(OscillatorForm.FCNoise); fcNoise.NoiseFrequencyIndex = index; GBLongNoise longNoise = (GBLongNoise)m_osc1.ModulatorFromForm(OscillatorForm.GBLongNoise); longNoise.NoiseFrequencyIndex = index; GBShortNoise shortNoise = (GBShortNoise)m_osc1.ModulatorFromForm(OscillatorForm.GBShortNoise); shortNoise.NoiseFrequencyIndex = index; FCDPCM fcDPCM = (FCDPCM)m_osc1.ModulatorFromForm(OscillatorForm.FCDPCM); fcDPCM.DPCMFrequency = index; } public void DisableNote() { m_vco.Release(); m_vcf.Release(); } public void Close() { DisableNote(); m_filter.Switch = FilterType.None; } public void SetLFO(Events.LFO lfo, double frequency) { OscillatorForm mainForm = lfo.Main - 1; m_osc2.Form = mainForm; m_mod2 = m_osc2.ModulatorFromForm(mainForm); m_osc2sign = lfo.Reverse ? -1.0 : 1.0; if (mainForm >= OscillatorForm.Max) m_osc2connect = false; if (mainForm == OscillatorForm.GBWave) { GBWave gbWave = (GBWave)m_osc2.ModulatorFromForm(OscillatorForm.GBWave); gbWave.WaveIndex = (int)lfo.Sub; } m_lfoDepth = lfo.Depth; m_osc2connect = m_lfoDepth == 0 ? false : true; m_mod2.Frequency = frequency; m_mod2.ResetPhase(); Noise noise = (Noise)m_osc2.ModulatorFromForm(OscillatorForm.Noise); noise.NoiseFrequency = frequency / Sample.RATE; m_lfoDelay = lfo.Delay; int time = lfo.Time; m_lfoEnd = time > 0 ? m_lfoDelay + time : 0; } public void GetSamples(ref double[] samples, int start, int delta, int max) { int end = Math.Min(start + delta, max); int frequencyIndex = 0; if (!m_vco.Playing) { for (int i = start; i < end; i++) s_samples[i] = 0; } else if (m_inSens < 0.000001) { if (!m_osc2connect) { switch (m_syncMode) { case ChannelOutputMode.Overwrite: m_mod1.GetSamplesSyncOut(ref s_samples, ref s_syncSource[m_syncPipe], start, end); break; case ChannelOutputMode.Add: m_mod1.GetSamplesSyncIn(ref s_samples, s_syncSource[m_syncPipe], start, end); break; default: m_mod1.GetSamples(ref s_samples, start, end); break; } if (VolumeMode == 0) m_vco.GetAmplitudeSamplesLinear(ref s_samples, start, end, m_ampLevel); else m_vco.GetAmplitudeSamplesNonLinear(ref s_samples, start, end, m_ampLevel); } else { int s = start, e = 0; do { e = Math.Min(s + s_lfoDelta, end); frequencyIndex = m_frequencyIndex; if (m_onCounter >= m_lfoDelay && (m_lfoEnd == 0 || m_onCounter < m_lfoEnd)) { frequencyIndex += (int)(m_mod2.NextSample * m_osc2sign * m_lfoDepth); m_mod2.AddPhase(e - s - 1); } m_mod1.Frequency = Channel.FrequencyFromIndex(frequencyIndex); switch (m_syncMode) { case ChannelOutputMode.Overwrite: m_mod1.GetSamplesSyncOut(ref s_samples, ref s_syncSource[m_syncPipe], s, e); break; case ChannelOutputMode.Add: m_mod1.GetSamplesSyncIn(ref s_samples, s_syncSource[m_syncPipe], s, e); break; default: m_mod1.GetSamples(ref s_samples, s, e); break; } if (VolumeMode == 0) m_vco.GetAmplitudeSamplesLinear(ref s_samples, s, e, m_ampLevel); else m_vco.GetAmplitudeSamplesNonLinear(ref s_samples, s, e, m_ampLevel); m_onCounter += e - s; s = e; } while (s < end); } } else { if (!m_osc2connect) { m_mod1.Frequency = Channel.FrequencyFromIndex(m_frequencyIndex); for (int i = start; i < end; i++) s_samples[i] = m_mod1.NextSampleFrom((int)(s_pipeArray[m_inPipe][i] * m_inSens)); if (m_volumeMode == 0) m_vco.GetAmplitudeSamplesLinear(ref s_samples, start, end, m_ampLevel); else m_vco.GetAmplitudeSamplesNonLinear(ref s_samples, start, end, m_ampLevel); } else { for (int i = start; i < end; i++) { frequencyIndex = m_frequencyIndex; if (m_onCounter >= m_lfoDelay && (m_lfoEnd == 0 || m_onCounter < m_lfoEnd)) frequencyIndex += (int)(m_mod2.NextSample * m_osc2sign * m_lfoDepth); m_mod1.Frequency = Channel.FrequencyFromIndex(frequencyIndex); s_samples[i] = m_mod1.NextSampleFrom((int)(s_pipeArray[m_inPipe][i] * m_inSens)); m_onCounter++; } if (m_volumeMode == 0) m_vco.GetAmplitudeSamplesLinear(ref s_samples, start, end, m_ampLevel); else m_vco.GetAmplitudeSamplesNonLinear(ref s_samples, start, end, m_ampLevel); } } if (m_ringSens >= 0.000001) { for (int i = start; i < end; i++) s_samples[i] *= s_pipeArray[m_ringPipe][i] * m_ringSens; } double key = m_mod1.Frequency; m_formant.GetSamples(ref s_samples, start, end); m_filter.Envelope = m_vcf; m_filter.Frequency = m_lpfFrequency; m_filter.Amount = m_lpfAmount; m_filter.Resonance = m_lpfResonance; m_filter.Key = key; m_filter.GetSample(ref s_samples, start, end); switch (m_outMode) { case ChannelOutputMode.Default: for (int i = start; i < end; i++) { int n = i << 1; double amplitude = s_samples[i]; samples[n] += amplitude * m_panLeft; samples[n + 1] += amplitude * m_panRight; } break; case ChannelOutputMode.Overwrite: for (int i = start; i < end; i++) s_pipeArray[m_outPipe][i] = s_samples[i]; break; case ChannelOutputMode.Add: for (int i = start; i < end; i++) s_pipeArray[m_outPipe][i] += s_samples[i]; break; } } #endregion #region nonpublic methods private void SetModulatorFrequency() { m_frequencyIndex = m_noteIndex * PITCH_RESOLUTION + m_detune; m_mod1.Frequency = FrequencyFromIndex(m_frequencyIndex); } #endregion #region public properties public Events.VCO ADSRForVCO { set { double multiply = (1.0 / VELOCITY_MAX2); m_vco.SetASDR(value.Attack * multiply, value.Decay * multiply, value.Sustain * multiply, value.Release * multiply); } } public Events.VCF ADSRForVCF { set { double multiply = (1.0 / VELOCITY_MAX2); m_vcf.SetASDR(value.Attack * multiply, value.Decay * multiply, value.Sustain * multiply, value.Release * multiply); } } public Events.Form Form { set { OscillatorForm main = value.Main; m_osc1.Form = main; m_mod1 = m_osc1.ModulatorFromForm(main); if (main == OscillatorForm.GBWave) { GBWave gbWave = (GBWave)m_osc1.ModulatorFromForm(OscillatorForm.GBWave); gbWave.WaveIndex = (int)value.Sub; } if (main == OscillatorForm.FCDPCM) { FCDPCM fcDCPM = (FCDPCM)m_osc1.ModulatorFromForm(OscillatorForm.FCDPCM); fcDCPM.WaveIndex = (int)value.Sub; } } } public Events.LPF LPF { set { FilterType sw = value.Switch; if (sw >= FilterType.HPFQuality && sw <= FilterType.LPFQuality && !m_enableFilter) { m_enableFilter = true; m_filter.Switch = sw; } m_lpfAmount = Math.Min(Math.Max(value.Amount, -VELOCITY_MAX2), VELOCITY_MAX2); m_lpfAmount *= PITCH_RESOLUTION; int frequencyIndex = value.Frequency; frequencyIndex = Math.Min(Math.Max(frequencyIndex, 0), VELOCITY_MAX2); m_lpfFrequency = frequencyIndex * PITCH_RESOLUTION; m_lpfResonance = value.Resonance * (1.0 / VELOCITY_MAX2); m_lpfResonance = Math.Min(Math.Max(m_lpfResonance, 0.0), 1.0); } } public Events.Input Input { set { m_inSens = (1 << (value.Sens - 1)) * (1.0 / 8.0) * Modulator.PHASE_LENGTH; m_inPipe = Math.Min(Math.Max(value.Pipe, 0), s_pipeArrayNum); } } public Events.Output Output { set { m_outMode = value.Mode; m_outPipe = Math.Min(Math.Max(value.Pipe, 0), s_pipeArrayNum); } } public int NoteIndex { set { m_noteIndex = value; SetModulatorFrequency(); } } public int Detune { set { m_detune = value; SetModulatorFrequency(); } } public double NoiseFrequency { set { Noise noise = (Noise)m_osc1.ModulatorFromForm(OscillatorForm.Noise); noise.NoiseFrequency = 1.0 - value * (1.0 / VELOCITY_MAX); } } public int PWM { set { Pulse pulse; if (m_osc1.Form != OscillatorForm.FCPulse) { pulse = (Pulse)m_osc1.ModulatorFromForm(OscillatorForm.Pulse); pulse.PWM = value * (1.0 / 100.0); } else { pulse = (Pulse)m_osc1.ModulatorFromForm(OscillatorForm.FCPulse); pulse.PWM = 0.125 * value; } } } public int Pan { set { m_panRight = Math.Max((value - 1) * (0.25 / 63.0), 0.0); m_panLeft = (2.0 * 0.25) - m_panRight; } } public FormantVowel FormantVowel { set { m_formant.Vowel = value; } } public int VolumeMode { private get; set; } public int Velocity { set { int velocity = Math.Min(Math.Max(value, 0), VELOCITY_MAX2); m_velocity = VolumeMode > 0 ? s_volumeMap[velocity] : (double)velocity / VELOCITY_MAX2; m_ampLevel = m_velocity * m_expression; } } public int Expression { set { int expression = Math.Min(Math.Max(value, 0), VELOCITY_MAX2); m_expression = VolumeMode > 0 ? s_volumeMap[expression] : (double)expression / VELOCITY_MAX2; m_ampLevel = m_velocity * m_expression; } } public Events.Ring Ring { set { m_ringSens = (1 << (value.Sens - 1)) / 8.0; m_ringPipe = Math.Min(Math.Max(value.Pipe, 0), s_pipeArrayNum); } } public Events.Sync Sync { set { m_syncMode = value.Mode; m_syncPipe = Math.Min(Math.Max(value.Pipe, 0), s_pipeArrayNum); } } #endregion #region member variables private static bool s_initialized = false; private static double[] s_frequencyMap = new double[VELOCITY_MAX * PITCH_RESOLUTION]; private static int s_frequencyLength = 0; private static double[] s_volumeMap = new double[VELOCITY_MAX]; private static int s_volumeLength = 0; private static double[] s_samples = null; private static int s_sampleLength = 0; private static double[][] s_pipeArray = null; private static int s_syncSourceLength = 0; private static bool[][] s_syncSource; private static int s_pipeArrayNum = 0; private static int s_lfoDelta = VELOCITY_MAX; private Envelope m_vco; private Envelope m_vcf; private IModulator m_mod1; private Oscillator m_osc1; private IModulator m_mod2; private Oscillator m_osc2; private int m_noteIndex; private int m_detune; private int m_frequencyIndex; private bool m_osc2connect; private double m_osc2sign; private Filter m_filter; private bool m_enableFilter; private Formant m_formant; private double m_expression; private double m_velocity; private double m_ampLevel; private double m_panLeft; private double m_panRight; private int m_onCounter; private int m_lfoDelay; private double m_lfoDepth; private int m_lfoEnd; private double m_lpfAmount; private double m_lpfFrequency; private double m_lpfResonance; private int m_volumeMode; private double m_inSens; private int m_inPipe; private ChannelOutputMode m_outMode; private int m_outPipe; private double m_ringSens; private int m_ringPipe; private ChannelOutputMode m_syncMode; private int m_syncPipe; #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.Connectors.Inventory { public class HGInventoryServiceConnector : ISessionAuthInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<string, InventoryServicesConnector> m_connectors = new Dictionary<string, InventoryServicesConnector>(); public HGInventoryServiceConnector(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { IConfig inventoryConfig = source.Configs["InventoryService"]; if (inventoryConfig == null) { m_log.Error("[HG INVENTORY SERVICE]: InventoryService missing from OpenSim.ini"); return; } m_log.Info("[HG INVENTORY SERVICE]: HG inventory service enabled"); } } private bool StringToUrlAndUserID(string id, out string url, out string userID) { url = String.Empty; userID = String.Empty; Uri assetUri; if (Uri.TryCreate(id, UriKind.Absolute, out assetUri) && assetUri.Scheme == Uri.UriSchemeHttp) { url = "http://" + assetUri.Authority; userID = assetUri.LocalPath.Trim(new char[] { '/' }); return true; } return false; } private ISessionAuthInventoryService GetConnector(string url) { InventoryServicesConnector connector = null; lock (m_connectors) { if (m_connectors.ContainsKey(url)) { connector = m_connectors[url]; } else { // We're instantiating this class explicitly, but this won't // work in general, because the remote grid may be running // an inventory server that has a different protocol. // Eventually we will want a piece of protocol asking // the remote server about its kind. Definitely cool thing to do! connector = new InventoryServicesConnector(url); m_connectors.Add(url, connector); } } return connector; } public string Host { get { return string.Empty; } } public void GetUserInventory(string id, UUID sessionID, InventoryReceiptCallback callback) { m_log.Debug("[HGInventory]: GetUserInventory " + id); string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); connector.GetUserInventory(userID, sessionID, callback); } } /// <summary> /// Gets the user folder for the given folder-type /// </summary> /// <param name="userID"></param> /// <param name="type"></param> /// <returns></returns> public Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(string id, UUID sessionID) { m_log.Debug("[HGInventory]: GetSystemFolders " + id); string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.GetSystemFolders(userID, sessionID); } return new Dictionary<AssetType, InventoryFolderBase>(); } /// <summary> /// Gets everything (folders and items) inside a folder /// </summary> /// <param name="userId"></param> /// <param name="folderID"></param> /// <returns></returns> public InventoryCollection GetFolderContent(string id, UUID folderID, UUID sessionID) { m_log.Debug("[HGInventory]: GetFolderContent " + id); string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.GetFolderContent(userID, folderID, sessionID); } return null; } public bool AddFolder(string id, InventoryFolderBase folder, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.AddFolder(userID, folder, sessionID); } return false; } public bool UpdateFolder(string id, InventoryFolderBase folder, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.UpdateFolder(userID, folder, sessionID); } return false; } public bool MoveFolder(string id, InventoryFolderBase folder, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.MoveFolder(userID, folder, sessionID); } return false; } public bool DeleteFolders(string id, List<UUID> folders, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.DeleteFolders(userID, folders, sessionID); } return false; } public bool PurgeFolder(string id, InventoryFolderBase folder, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.PurgeFolder(userID, folder, sessionID); } return false; } public List<InventoryItemBase> GetFolderItems(string id, UUID folderID, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.GetFolderItems(userID, folderID, sessionID); } return new List<InventoryItemBase>(); } public bool AddItem(string id, InventoryItemBase item, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.AddItem(userID, item, sessionID); } return false; } public bool UpdateItem(string id, InventoryItemBase item, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.UpdateItem(userID, item, sessionID); } return false; } public bool MoveItems(string id, List<InventoryItemBase> items, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.MoveItems(userID, items, sessionID); } return false; } public bool DeleteItems(string id, List<UUID> itemIDs, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.DeleteItems(userID, itemIDs, sessionID); } return false; } public InventoryItemBase QueryItem(string id, InventoryItemBase item, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.QueryItem(userID, item, sessionID); } return null; } public InventoryFolderBase QueryFolder(string id, InventoryFolderBase folder, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.QueryFolder(userID, folder, sessionID); } return null; } public int GetAssetPermissions(string id, UUID assetID, UUID sessionID) { string url = string.Empty; string userID = string.Empty; if (StringToUrlAndUserID(id, out url, out userID)) { ISessionAuthInventoryService connector = GetConnector(url); return connector.GetAssetPermissions(userID, assetID, sessionID); } return 0; } } }
using System; using System.Collections.Generic; using System.Data; using System.Configuration; using System.Data.Common; using System.Data.SqlClient; using System.Text; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; /// <summary> /// Summary description for Examples /// </summary> public class Examples { private const string CodeFormat = "{0}:{1}"; private String connectionString; public string ConnectionString { get { return connectionString; } set { connectionString = value; } } private String networkCode; private String vocabularyCode; public string NetworkCode { get { return networkCode; } set { networkCode = value; } } public string VocabularyCode { get { return vocabularyCode; } set { vocabularyCode = value; } } public Examples() { } public Examples(String connection) { this.connectionString = connection; } public List<String> GetSites() { using (DbConnection connection= new SqlConnection( connectionString )) { List<String> sitesSamples = new List<String>(); connection.Open(); string sitesQ = " Select TOP 3 SiteCode from Sites "; DbCommand command = connection.CreateCommand(); command.CommandText = sitesQ; using (DbDataReader reader = command.ExecuteReader() ) { if (reader.HasRows) { if (reader.Read()) { sitesSamples.Add(String.Format(CodeFormat, NetworkCode, reader.GetString(0))); } string siteList = "In SOAP send ARRAY OF String[] ("; while (reader.Read()) { siteList += String.Format(" '{0}' ", string.Format(CodeFormat, NetworkCode, reader.GetString(0)) ) ; } siteList += ") "; sitesSamples.Add(siteList); } } //BOX((W S, E N)) string sitesBoundQ = @" SELECT CONVERT(varchar,MIN(Longitude)) + ' '+ CONVERT(varchar,MIN(Latitude))+ ', '+ CONVERT(varchar,Max(Longitude))+ ' '+ CONVERT(varchar,Max(Latitude)) AS Box FROM Sites"; command = connection.CreateCommand(); command.CommandText = sitesBoundQ; String sitesBounds= (string) command.ExecuteScalar(); sitesSamples.Add("GEOM:BOX(" + sitesBounds +")"); connection.Close(); return sitesSamples; } } public List<String> GetSiteInfo() { using (DbConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sitesQ = " Select DISTINCT TOP 3 SiteCode from SeriesCatalog "; DbCommand command = connection.CreateCommand(); command.CommandText = sitesQ; DbDataReader reader = command.ExecuteReader(); List<String> sitesSamples = new List<String>(); if (reader.HasRows) { while(reader.Read()) { sitesSamples.Add(String.Format(CodeFormat, NetworkCode, reader.GetString(0))); } } connection.Close(); return sitesSamples; } } public List<String> GetVariableSimple() { using (DbConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sitesQ = " Select TOP 3 VariableCode from Variables "; DbCommand command = connection.CreateCommand(); command.CommandText = sitesQ; DbDataReader reader = command.ExecuteReader(); List<String> samples = new List<String>(); if (reader.HasRows) { while (reader.Read()) { samples.Add(String.Format(CodeFormat, VocabularyCode, reader.GetString(0))); } } connection.Close(); return samples; } } public List<String> GetVariableDetailed() { using (DbConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sitesQ = " Select TOP 3 * from Variables "; DbCommand command = connection.CreateCommand(); command.CommandText = sitesQ; DbDataReader reader = command.ExecuteReader(); List<String> samples = new List<String>(); if (reader.HasRows) { while (reader.Read()) { ; DetailedVariable variable = new DetailedVariable(); variable.VariableVocabulary = VocabularyCode; variable.VariableCode = ValueFromReader(reader, "VariableCode"); variable.SampleMedium = ValueFromReader(reader, "SampleMedium"); variable.DataType = ValueFromReader(reader, "DataType"); variable.ValueType = ValueFromReader(reader, "ValueType"); samples.Add(variable.ToString()); } } connection.Close(); return samples; } } private string ValueFromReader(DbDataReader reader, String field) { string val = null; int col = reader.GetOrdinal(field); if (col >=0) { if (!reader.IsDBNull(col)) val = reader.GetString(col); } return val; } private class DetailedVariable { private string variableVocabulary; private string variableCode; private string sampleMedium; private string dataType; private string valueType; private string methodId; private string sourceId; private string qualityControlLevelId; public string VariableVocabulary { get { return variableVocabulary; } set { variableVocabulary = value; } } public string VariableCode { get { return variableCode; } set { variableCode = value; } } public string SampleMedium { get { return sampleMedium; } set { sampleMedium = value; } } public string DataType { get { return dataType; } set { dataType = value; } } public string ValueType { get { return valueType; } set { valueType = value; } } public string MethodId { get { return methodId; } set { methodId = value; } } public string SourceId { get { return sourceId; } set { sourceId = value; } } public string QualityControlLevelId { get { return qualityControlLevelId; } set { qualityControlLevelId = value; } } public string ToString() { StringBuilder variable = new StringBuilder(); if (!String.IsNullOrEmpty(variableCode) && ! String.IsNullOrEmpty(VariableVocabulary)) { variable.AppendFormat("{0}:{1}", VariableVocabulary, VariableCode); } else { // no variableCode or vocabulary return "INTERNAL ERROR missing variable vocabulary or variable code."; } const string keypair = "/{0}={1}"; if (!string.IsNullOrEmpty(sampleMedium)) variable.AppendFormat(keypair, "SampleMedium", sampleMedium); if (!string.IsNullOrEmpty(valueType)) variable.AppendFormat(keypair, "valueType", valueType); if (!string.IsNullOrEmpty(dataType)) variable.AppendFormat(keypair, "dataType", dataType); if (!string.IsNullOrEmpty(QualityControlLevelId)) variable.AppendFormat(keypair, "QualityControlLevelId", QualityControlLevelId); if (!string.IsNullOrEmpty(sourceId)) variable.AppendFormat(keypair, "sourceId", sourceId); if (!string.IsNullOrEmpty(MethodId)) variable.AppendFormat(keypair, "MethodId", MethodId); return variable.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Collections.Specialized; using System.Net.Mail; namespace System.Net.Mime { internal abstract class BaseWriter { // This is the maximum default line length that can actually be written. When encoding // headers, the line length is more conservative to account for things like folding. // In MailWriter, all encoding has already been done so this will only fold lines // that are NOT encoded already, which means being less conservative is ok. private const int DefaultLineLength = 76; private static readonly AsyncCallback s_onWrite = OnWrite; protected static readonly byte[] s_crlf = new byte[] { (byte)'\r', (byte)'\n' }; protected readonly BufferBuilder _bufferBuilder; protected readonly Stream _stream; private readonly EventHandler _onCloseHandler; private readonly bool _shouldEncodeLeadingDots; private int _lineLength; protected Stream _contentStream; protected bool _isInContent; protected BaseWriter(Stream stream, bool shouldEncodeLeadingDots) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } _stream = stream; _shouldEncodeLeadingDots = shouldEncodeLeadingDots; _onCloseHandler = new EventHandler(OnClose); _bufferBuilder = new BufferBuilder(); _lineLength = DefaultLineLength; } #region Headers internal abstract void WriteHeaders(NameValueCollection headers, bool allowUnicode); internal void WriteHeader(string name, string value, bool allowUnicode) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (_isInContent) { throw new InvalidOperationException(SR.MailWriterIsInContent); } CheckBoundary(); _bufferBuilder.Append(name); _bufferBuilder.Append(": "); WriteAndFold(value, name.Length + 2, allowUnicode); _bufferBuilder.Append(s_crlf); } private void WriteAndFold(string value, int charsAlreadyOnLine, bool allowUnicode) { int lastSpace = 0, startOfLine = 0; for (int index = 0; index < value.Length; index++) { // When we find a FWS (CRLF) copy it as is. if (MailBnfHelper.IsFWSAt(value, index)) // At the first char of "\r\n " or "\r\n\t" { index += 2; // Skip the FWS _bufferBuilder.Append(value, startOfLine, index - startOfLine, allowUnicode); // Reset for the next line startOfLine = index; lastSpace = index; charsAlreadyOnLine = 0; } // When we pass the line length limit, and know where there was a space to fold at, fold there else if (((index - startOfLine) > (_lineLength - charsAlreadyOnLine)) && lastSpace != startOfLine) { _bufferBuilder.Append(value, startOfLine, lastSpace - startOfLine, allowUnicode); _bufferBuilder.Append(s_crlf); startOfLine = lastSpace; charsAlreadyOnLine = 0; } // Mark a foldable space. If we go over the line length limit, fold here. else if (value[index] == MailBnfHelper.Space || value[index] == MailBnfHelper.Tab) { lastSpace = index; } } // Write any remaining data to the buffer. if (value.Length - startOfLine > 0) { _bufferBuilder.Append(value, startOfLine, value.Length - startOfLine, allowUnicode); } } #endregion Headers #region Content internal Stream GetContentStream() => GetContentStream(null); private Stream GetContentStream(MultiAsyncResult multiResult) { if (_isInContent) { throw new InvalidOperationException(SR.MailWriterIsInContent); } _isInContent = true; CheckBoundary(); _bufferBuilder.Append(s_crlf); Flush(multiResult); ClosableStream cs = new ClosableStream(new EightBitStream(_stream, _shouldEncodeLeadingDots), _onCloseHandler); _contentStream = cs; return cs; } internal IAsyncResult BeginGetContentStream(AsyncCallback callback, object state) { MultiAsyncResult multiResult = new MultiAsyncResult(this, callback, state); Stream s = GetContentStream(multiResult); if (!(multiResult.Result is Exception)) { multiResult.Result = s; } multiResult.CompleteSequence(); return multiResult; } internal Stream EndGetContentStream(IAsyncResult result) { object o = MultiAsyncResult.End(result); if (o is Exception) { throw (Exception)o; } return (Stream)o; } #endregion Content #region Cleanup protected void Flush(MultiAsyncResult multiResult) { if (_bufferBuilder.Length > 0) { if (multiResult != null) { multiResult.Enter(); IAsyncResult result = _stream.BeginWrite(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length, s_onWrite, multiResult); if (result.CompletedSynchronously) { _stream.EndWrite(result); multiResult.Leave(); } } else { _stream.Write(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length); } _bufferBuilder.Reset(); } } protected static void OnWrite(IAsyncResult result) { if (!result.CompletedSynchronously) { MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState; BaseWriter thisPtr = (BaseWriter)multiResult.Context; try { thisPtr._stream.EndWrite(result); multiResult.Leave(); } catch (Exception e) { multiResult.Leave(e); } } } internal abstract void Close(); protected abstract void OnClose(object sender, EventArgs args); #endregion Cleanup protected virtual void CheckBoundary() { } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; // ReSharper disable AssignNullToNotNullAttribute namespace Thinktecture.Net.Sockets.Adapters { /// <summary> /// Provides client connections for TCP network services. /// </summary> public class TcpClientAdapter : AbstractionAdapter<TcpClient>, ITcpClient { /// <inheritdoc /> public int Available => Implementation.Available; /// <inheritdoc /> public ISocket Client { get => Implementation.Client.ToInterface(); set => Implementation.Client = value.ToImplementation(); } /// <inheritdoc /> public bool Connected => Implementation.Connected; /// <inheritdoc /> public bool ExclusiveAddressUse { get => Implementation.ExclusiveAddressUse; set => Implementation.ExclusiveAddressUse = value; } /// <inheritdoc /> [DisallowNull] public ILingerOption? LingerState { get => Implementation.LingerState.ToInterface(); set => Implementation.LingerState = value.ToImplementation(); } /// <inheritdoc /> public bool NoDelay { get => Implementation.NoDelay; set => Implementation.NoDelay = value; } /// <inheritdoc /> public int ReceiveBufferSize { get => Implementation.ReceiveBufferSize; set => Implementation.ReceiveBufferSize = value; } /// <inheritdoc /> public int ReceiveTimeout { get => Implementation.ReceiveTimeout; set => Implementation.ReceiveTimeout = value; } /// <inheritdoc /> public int SendBufferSize { get => Implementation.SendBufferSize; set => Implementation.SendBufferSize = value; } /// <inheritdoc /> public int SendTimeout { get => Implementation.SendTimeout; set => Implementation.SendTimeout = value; } /// <summary> /// Initializes a new instance of the TcpClient class. /// </summary> public TcpClientAdapter() : this(new TcpClient()) { } /// <summary>Initializes a new instance of the <see cref="TcpClientAdapter"></see> class and binds it to the specified local endpoint.</summary> /// <param name="localEp">The <see cref="T:System.Net.IPEndPoint"></see> to which you bind the TCP <see cref="T:System.Net.Sockets.Socket"></see>.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="localEp">localEP</paramref> parameter is null.</exception> public TcpClientAdapter(IPEndPoint localEp) : this(new TcpClient(localEp)) { } /// <summary>Initializes a new instance of the <see cref="TcpClientAdapter"></see> class and connects to the specified port on the specified host.</summary> /// <param name="hostname">The DNS name of the remote host to which you intend to connect.</param> /// <param name="port">The port number of the remote host to which you intend to connect.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="hostname">hostname</paramref> parameter is null.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="port">port</paramref> parameter is not between <see cref="System.Net.IPEndPoint.MinPort"></see> and <see cref="System.Net.IPEndPoint.MaxPort"></see>.</exception> /// <exception cref="T:System.Net.Sockets.SocketException">An error occurred when accessing the socket.</exception> public TcpClientAdapter(string hostname, int port) : this(new TcpClient(hostname, port)) { } /// <summary> /// Initializes a new instance of the TcpClient class with the specified family. /// </summary> /// <param name="family">The AddressFamily of the IP protocol.</param> public TcpClientAdapter(AddressFamily family) : this(new TcpClient(family)) { } /// <summary> /// Initializes new instance of <see cref="TcpClientAdapter"/>. /// </summary> /// <param name="client">Client to be used by the adapter.</param> public TcpClientAdapter(TcpClient client) : base(client) { } /// <inheritdoc /> public Task ConnectAsync(IPAddress address, int port) { return Implementation.ConnectAsync(address, port); } /// <inheritdoc /> public Task ConnectAsync(IIPAddress address, int port) { return Implementation.ConnectAsync(address.ToImplementation(), port); } #if NET5_0 /// <inheritdoc /> public ValueTask ConnectAsync(IPAddress address, int port, CancellationToken cancellationToken) { return Implementation.ConnectAsync(address, port, cancellationToken); } /// <inheritdoc /> public ValueTask ConnectAsync(IIPAddress address, int port, CancellationToken cancellationToken) { return Implementation.ConnectAsync(address.ToImplementation(), port, cancellationToken); } #endif /// <inheritdoc /> public Task ConnectAsync(IPAddress[] addresses, int port) { return Implementation.ConnectAsync(addresses, port); } /// <inheritdoc /> public Task ConnectAsync(IIPAddress[] addresses, int port) { return Implementation.ConnectAsync(addresses.ToNotNullImplementation<IIPAddress, IPAddress>(), port); } #if NET5_0 /// <inheritdoc /> public ValueTask ConnectAsync(IPAddress[] addresses, int port, CancellationToken cancellationToken) { return Implementation.ConnectAsync(addresses, port, cancellationToken); } /// <inheritdoc /> public ValueTask ConnectAsync(IIPAddress[] addresses, int port, CancellationToken cancellationToken) { return Implementation.ConnectAsync(addresses.ToNotNullImplementation<IIPAddress, IPAddress>(), port, cancellationToken); } #endif /// <inheritdoc /> public Task ConnectAsync(string host, int port) { return Implementation.ConnectAsync(host, port); } #if NET5_0 /// <inheritdoc /> public ValueTask ConnectAsync(string host, int port, CancellationToken cancellationToken) { return Implementation.ConnectAsync(host, port, cancellationToken); } #endif /// <inheritdoc /> public INetworkStream GetStream() { return Implementation.GetStream().ToInterface(); } /// <inheritdoc /> public void Connect(string hostname, int port) { Implementation.Connect(hostname, port); } /// <inheritdoc /> public void Connect(IPAddress address, int port) { Implementation.Connect(address, port); } /// <inheritdoc /> public void Connect(IIPAddress address, int port) { Implementation.Connect(address.ToImplementation(), port); } /// <inheritdoc /> public void Connect(IPEndPoint remoteEp) { Implementation.Connect(remoteEp); } /// <inheritdoc /> public void Connect(IIPEndPoint remoteEp) { Implementation.Connect(remoteEp.ToImplementation()); } /// <inheritdoc /> public void Connect(IPAddress[] ipAddresses, int port) { Implementation.Connect(ipAddresses, port); } /// <inheritdoc /> public void Connect(IIPAddress[] ipAddresses, int port) { Implementation.Connect(ipAddresses.ToNotNullImplementation<IIPAddress, IPAddress>(), port); } /// <inheritdoc /> public void Close() { Implementation.Close(); } /// <inheritdoc /> public void Dispose() { ((IDisposable)Implementation).Dispose(); } } }
/* * @(#)ConstantValue.cs 4.1.0 2017-04-18 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2016 MARIUSZ GROMADA. 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 <MARIUSZ GROMADA> ``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 <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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * mariuszgromada.org@gmail.com * http://mathparser.org * http://mathspace.pl * http://janetsudoku.mariuszgromada.org * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser * http://mxparser.sourceforge.net * http://bitbucket.org/mariuszgromada/mxparser * http://mxparser.codeplex.com * http://github.com/mariuszgromada/Janet-Sudoku * http://janetsudoku.codeplex.com * http://sourceforge.net/projects/janetsudoku * http://bitbucket.org/mariuszgromada/janet-sudoku * http://github.com/mariuszgromada/MathParser.org-mXparser * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ using System; namespace org.mariuszgromada.math.mxparser.parsertokens { /** * Constant Values - mXparser tokens definition. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br> * <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br> * <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br> * <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br> * <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br> * <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br> * * @version 4.1.0 */ [CLSCompliant(true)] public sealed class ConstantValue { /* * ConstantValue - token type id. */ public const int TYPE_ID = 9; public const String TYPE_DESC = "Constant Value"; /* * ConstantValue - tokens id. */ /* Math Constants */ public const int PI_ID = 1; public const int EULER_ID = 2; public const int EULER_MASCHERONI_ID = 3; public const int GOLDEN_RATIO_ID = 4; public const int PLASTIC_ID = 5; public const int EMBREE_TREFETHEN_ID = 6; public const int FEIGENBAUM_DELTA_ID = 7; public const int FEIGENBAUM_ALFA_ID = 8; public const int TWIN_PRIME_ID = 9; public const int MEISSEL_MERTEENS_ID = 10; public const int BRAUN_TWIN_PRIME_ID = 11; public const int BRAUN_PRIME_QUADR_ID = 12; public const int BRUIJN_NEWMAN_ID = 13; public const int CATALAN_ID = 14; public const int LANDAU_RAMANUJAN_ID = 15; public const int VISWANATH_ID = 16; public const int LEGENDRE_ID = 17; public const int RAMANUJAN_SOLDNER_ID = 18; public const int ERDOS_BORWEIN_ID = 19; public const int BERNSTEIN_ID = 20; public const int GAUSS_KUZMIN_WIRSING_ID = 21; public const int HAFNER_SARNAK_MCCURLEY_ID = 22; public const int GOLOMB_DICKMAN_ID = 23; public const int CAHEN_ID = 24; public const int LAPLACE_LIMIT_ID = 25; public const int ALLADI_GRINSTEAD_ID = 26; public const int LENGYEL_ID = 27; public const int LEVY_ID = 28; public const int APERY_ID = 29; public const int MILLS_ID = 30; public const int BACKHOUSE_ID = 31; public const int PORTER_ID = 32; public const int LIEB_QUARE_ICE_ID = 33; public const int NIVEN_ID = 34; public const int SIERPINSKI_ID = 35; public const int KHINCHIN_ID = 36; public const int FRANSEN_ROBINSON_ID = 37; public const int LANDAU_ID = 38; public const int PARABOLIC_ID = 39; public const int OMEGA_ID = 40; public const int MRB_ID = 41; public const int LI2_ID = 42; public const int GOMPERTZ_ID = 43; /* Physical Constants */ public const int LIGHT_SPEED_ID = 101; public const int GRAVITATIONAL_CONSTANT_ID = 102; public const int GRAVIT_ACC_EARTH_ID = 103; public const int PLANCK_CONSTANT_ID = 104; public const int PLANCK_CONSTANT_REDUCED_ID = 105; public const int PLANCK_LENGTH_ID = 106; public const int PLANCK_MASS_ID = 107; public const int PLANCK_TIME_ID = 108; /* Astronomical Constants */ public const int LIGHT_YEAR_ID = 201; public const int ASTRONOMICAL_UNIT_ID = 202; public const int PARSEC_ID = 203; public const int KILOPARSEC_ID = 204; public const int EARTH_RADIUS_EQUATORIAL_ID = 205; public const int EARTH_RADIUS_POLAR_ID = 206; public const int EARTH_RADIUS_MEAN_ID = 207; public const int EARTH_MASS_ID = 208; public const int EARTH_SEMI_MAJOR_AXIS_ID = 209; public const int MOON_RADIUS_MEAN_ID = 210; public const int MOON_MASS_ID = 211; public const int MONN_SEMI_MAJOR_AXIS_ID = 212; public const int SOLAR_RADIUS_ID = 213; public const int SOLAR_MASS_ID = 214; public const int MERCURY_RADIUS_MEAN_ID = 215; public const int MERCURY_MASS_ID = 216; public const int MERCURY_SEMI_MAJOR_AXIS_ID = 217; public const int VENUS_RADIUS_MEAN_ID = 218; public const int VENUS_MASS_ID = 219; public const int VENUS_SEMI_MAJOR_AXIS_ID = 220; public const int MARS_RADIUS_MEAN_ID = 221; public const int MARS_MASS_ID = 222; public const int MARS_SEMI_MAJOR_AXIS_ID = 223; public const int JUPITER_RADIUS_MEAN_ID = 224; public const int JUPITER_MASS_ID = 225; public const int JUPITER_SEMI_MAJOR_AXIS_ID = 226; public const int SATURN_RADIUS_MEAN_ID = 227; public const int SATURN_MASS_ID = 228; public const int SATURN_SEMI_MAJOR_AXIS_ID = 229; public const int URANUS_RADIUS_MEAN_ID = 230; public const int URANUS_MASS_ID = 231; public const int URANUS_SEMI_MAJOR_AXIS_ID = 232; public const int NEPTUNE_RADIUS_MEAN_ID = 233; public const int NEPTUNE_MASS_ID = 234; public const int NEPTUNE_SEMI_MAJOR_AXIS_ID = 235; /* boolean values */ public const int TRUE_ID = 301; public const int FALSE_ID = 302; /* other values */ public const int NAN_ID = 999; public const int NaN = -1; /* * ConstantValue - tokens key words. */ public const String PI_STR = "pi"; public const String EULER_STR = "e"; public const String EULER_MASCHERONI_STR = "[gam]"; public const String GOLDEN_RATIO_STR = "[phi]"; public const String PLASTIC_STR = "[PN]"; public const String EMBREE_TREFETHEN_STR = "[B*]"; public const String FEIGENBAUM_DELTA_STR = "[F'd]"; public const String FEIGENBAUM_ALFA_STR = "[F'a]"; public const String TWIN_PRIME_STR = "[C2]"; public const String MEISSEL_MERTEENS_STR = "[M1]"; public const String BRAUN_TWIN_PRIME_STR = "[B2]"; public const String BRAUN_PRIME_QUADR_STR = "[B4]"; public const String BRUIJN_NEWMAN_STR = "[BN'L]"; public const String CATALAN_STR = "[Kat]"; public const String LANDAU_RAMANUJAN_STR = "[K*]"; public const String VISWANATH_STR = "[K.]"; public const String LEGENDRE_STR = "[B'L]"; public const String RAMANUJAN_SOLDNER_STR = "[RS'm]"; public const String ERDOS_BORWEIN_STR = "[EB'e]"; public const String BERNSTEIN_STR = "[Bern]"; public const String GAUSS_KUZMIN_WIRSING_STR = "[GKW'l]"; public const String HAFNER_SARNAK_MCCURLEY_STR = "[HSM's]"; public const String GOLOMB_DICKMAN_STR = "[lm]"; public const String CAHEN_STR = "[Cah]"; public const String LAPLACE_LIMIT_STR = "[Ll]"; public const String ALLADI_GRINSTEAD_STR = "[AG]"; public const String LENGYEL_STR = "[L*]"; public const String LEVY_STR = "[L.]"; public const String APERY_STR = "[Dz3]"; public const String MILLS_STR = "[A3n]"; public const String BACKHOUSE_STR = "[Bh]"; public const String PORTER_STR = "[Pt]"; public const String LIEB_QUARE_ICE_STR = "[L2]"; public const String NIVEN_STR = "[Nv]"; public const String SIERPINSKI_STR = "[Ks]"; public const String KHINCHIN_STR = "[Kh]"; public const String FRANSEN_ROBINSON_STR = "[FR]"; public const String LANDAU_STR = "[La]"; public const String PARABOLIC_STR = "[P2]"; public const String OMEGA_STR = "[Om]"; public const String MRB_STR = "[MRB]"; public const String LI2_STR = "[li2]"; public const String GOMPERTZ_STR = "[EG]"; /* Physical Constants */ public const String LIGHT_SPEED_STR = "[c]"; public const String GRAVITATIONAL_CONSTANT_STR = "[G.]"; public const String GRAVIT_ACC_EARTH_STR = "[g]"; public const String PLANCK_CONSTANT_STR = "[hP]"; public const String PLANCK_CONSTANT_REDUCED_STR = "[h-]"; public const String PLANCK_LENGTH_STR = "[lP]"; public const String PLANCK_MASS_STR = "[mP]"; public const String PLANCK_TIME_STR = "[tP]"; /* AstronomicalConstants */ public const String LIGHT_YEAR_STR = "[ly]"; public const String ASTRONOMICAL_UNIT_STR = "[au]"; public const String PARSEC_STR = "[pc]"; public const String KILOPARSEC_STR = "[kpc]"; public const String EARTH_RADIUS_EQUATORIAL_STR = "[Earth-R-eq]"; public const String EARTH_RADIUS_POLAR_STR = "[Earth-R-po]"; public const String EARTH_RADIUS_MEAN_STR = "[Earth-R]"; public const String EARTH_MASS_STR = "[Earth-M]"; public const String EARTH_SEMI_MAJOR_AXIS_STR = "[Earth-D]"; public const String MOON_RADIUS_MEAN_STR = "[Moon-R]"; public const String MOON_MASS_STR = "[Moon-M]"; public const String MONN_SEMI_MAJOR_AXIS_STR = "[Moon-D]"; public const String SOLAR_RADIUS_STR = "[Solar-R]"; public const String SOLAR_MASS_STR = "[Solar-M]"; public const String MERCURY_RADIUS_MEAN_STR = "[Mercury-R]"; public const String MERCURY_MASS_STR = "[Mercury-M]"; public const String MERCURY_SEMI_MAJOR_AXIS_STR = "[Mercury-D]"; public const String VENUS_RADIUS_MEAN_STR = "[Venus-R]"; public const String VENUS_MASS_STR = "[Venus-M]"; public const String VENUS_SEMI_MAJOR_AXIS_STR = "[Venus-D]"; public const String MARS_RADIUS_MEAN_STR = "[Mars-R]"; public const String MARS_MASS_STR = "[Mars-M]"; public const String MARS_SEMI_MAJOR_AXIS_STR = "[Mars-D]"; public const String JUPITER_RADIUS_MEAN_STR = "[Jupiter-R]"; public const String JUPITER_MASS_STR = "[Jupiter-M]"; public const String JUPITER_SEMI_MAJOR_AXIS_STR = "[Jupiter-D]"; public const String SATURN_RADIUS_MEAN_STR = "[Saturn-R]"; public const String SATURN_MASS_STR = "[Saturn-M]"; public const String SATURN_SEMI_MAJOR_AXIS_STR = "[Saturn-D]"; public const String URANUS_RADIUS_MEAN_STR = "[Uranus-R]"; public const String URANUS_MASS_STR = "[Uranus-M]"; public const String URANUS_SEMI_MAJOR_AXIS_STR = "[Uranus-D]"; public const String NEPTUNE_RADIUS_MEAN_STR = "[Neptune-R]"; public const String NEPTUNE_MASS_STR = "[Neptune-M]"; public const String NEPTUNE_SEMI_MAJOR_AXIS_STR = "[Neptune-D]"; /* boolean values */ public const String TRUE_STR = "[true]"; public const String FALSE_STR = "[false]"; /* other values */ public const String NAN_STR = "[NaN]"; /* * ConstantValue - tokens description. */ public const String PI_DESC = "Pi, Archimedes' constant or Ludolph's number"; public const String EULER_DESC = "Napier's constant, or Euler's number, base of Natural logarithm"; public const String EULER_MASCHERONI_DESC = "Euler-Mascheroni constant"; public const String GOLDEN_RATIO_DESC = "Golden ratio"; public const String PLASTIC_DESC = "Plastic constant"; public const String EMBREE_TREFETHEN_DESC = "Embree-Trefethen constant"; public const String FEIGENBAUM_DELTA_DESC = "Feigenbaum constant alfa"; public const String FEIGENBAUM_ALFA_DESC = "Feigenbaum constant delta"; public const String TWIN_PRIME_DESC = "Twin prime constant"; public const String MEISSEL_MERTEENS_DESC = "Meissel-Mertens constant"; public const String BRAUN_TWIN_PRIME_DESC = "Brun's constant for twin primes"; public const String BRAUN_PRIME_QUADR_DESC = "Brun's constant for prime quadruplets"; public const String BRUIJN_NEWMAN_DESC = "de Bruijn-Newman constant"; public const String CATALAN_DESC = "Catalan's constant"; public const String LANDAU_RAMANUJAN_DESC = "Landau-Ramanujan constant"; public const String VISWANATH_DESC = "Viswanath's constant"; public const String LEGENDRE_DESC = "Legendre's constant"; public const String RAMANUJAN_SOLDNER_DESC = "Ramanujan-Soldner constant"; public const String ERDOS_BORWEIN_DESC = "Erdos-Borwein constant"; public const String BERNSTEIN_DESC = "Bernstein's constant"; public const String GAUSS_KUZMIN_WIRSING_DESC = "Gauss-Kuzmin-Wirsing constant"; public const String HAFNER_SARNAK_MCCURLEY_DESC = "Hafner-Sarnak-McCurley constant"; public const String GOLOMB_DICKMAN_DESC = "Golomb-Dickman constant"; public const String CAHEN_DESC = "Cahen's constant"; public const String LAPLACE_LIMIT_DESC = "Laplace limit"; public const String ALLADI_GRINSTEAD_DESC = "Alladi-Grinstead constant"; public const String LENGYEL_DESC = "Lengyel's constant"; public const String LEVY_DESC = "Levy's constant"; public const String APERY_DESC = "Apery's constant"; public const String MILLS_DESC = "Mills' constant"; public const String BACKHOUSE_DESC = "Backhouse's constant"; public const String PORTER_DESC = "Porter's constant"; public const String LIEB_QUARE_ICE_DESC = "Lieb's square ice constant"; public const String NIVEN_DESC = "Niven's constant"; public const String SIERPINSKI_DESC = "Sierpinski's constant"; public const String KHINCHIN_DESC = "Khinchin's constant"; public const String FRANSEN_ROBINSON_DESC = "Fransen-Robinson constant"; public const String LANDAU_DESC = "Landau's constant"; public const String PARABOLIC_DESC = "Parabolic constant"; public const String OMEGA_DESC = "Omega constant"; public const String MRB_DESC = "MRB constant"; public const String LI2_DESC = "(2.3) li(2) - logarithmic integral function at x=2"; public const String GOMPERTZ_DESC = "(2.3) Gompertz constant"; /* Physical Constants */ public const String LIGHT_SPEED_DESC = "(4.0) <Physical Constant> Light speed in vacuum [m/s] (m=1, s=1)"; public const String GRAVITATIONAL_CONSTANT_DESC = "(4.0) <Physical Constant> Gravitational constant (m=1, kg=1, s=1)]"; public const String GRAVIT_ACC_EARTH_DESC = "(4.0) <Physical Constant> Gravitational acceleration on Earth [m/s^2] (m=1, s=1)"; public const String PLANCK_CONSTANT_DESC = "(4.0) <Physical Constant> Planck constant (m=1, kg=1, s=1)"; public const String PLANCK_CONSTANT_REDUCED_DESC = "(4.0) <Physical Constant> Reduced Planck constant / Dirac constant (m=1, kg=1, s=1)]"; public const String PLANCK_LENGTH_DESC = "(4.0) <Physical Constant> Planck length [m] (m=1)"; public const String PLANCK_MASS_DESC = "(4.0) <Physical Constant> Planck mass [kg] (kg=1)"; public const String PLANCK_TIME_DESC = "(4.0) <Physical Constant> Planck time [s] (s=1)"; /* Astronomical Constants */ public const String LIGHT_YEAR_DESC = "(4.0) <Astronomical Constant> Light year [m] (m=1)"; public const String ASTRONOMICAL_UNIT_DESC = "(4.0) <Astronomical Constant> Astronomical unit [m] (m=1)"; public const String PARSEC_DESC = "(4.0) <Astronomical Constant> Parsec [m] (m=1)"; public const String KILOPARSEC_DESC = "(4.0) <Astronomical Constant> Kiloparsec [m] (m=1)"; public const String EARTH_RADIUS_EQUATORIAL_DESC = "(4.0) <Astronomical Constant> Earth equatorial radius [m] (m=1)"; public const String EARTH_RADIUS_POLAR_DESC = "(4.0) <Astronomical Constant> Earth polar radius [m] (m=1)"; public const String EARTH_RADIUS_MEAN_DESC = "(4.0) <Astronomical Constant> Earth mean radius (m=1)"; public const String EARTH_MASS_DESC = "(4.0) <Astronomical Constant> Earth mass [kg] (kg=1)"; public const String EARTH_SEMI_MAJOR_AXIS_DESC = "(4.0) <Astronomical Constant> Earth-Sun distance - semi major axis [m] (m=1)"; public const String MOON_RADIUS_MEAN_DESC = "(4.0) <Astronomical Constant> Moon mean radius [m] (m=1)"; public const String MOON_MASS_DESC = "(4.0) <Astronomical Constant> Moon mass [kg] (kg=1)"; public const String MONN_SEMI_MAJOR_AXIS_DESC = "(4.0) <Astronomical Constant> Moon-Earth distance - semi major axis [m] (m=1)"; public const String SOLAR_RADIUS_DESC = "(4.0) <Astronomical Constant> Solar mean radius [m] (m=1)"; public const String SOLAR_MASS_DESC = "(4.0) <Astronomical Constant> Solar mass [kg] (kg=1)"; public const String MERCURY_RADIUS_MEAN_DESC = "(4.0) <Astronomical Constant> Mercury mean radius [m] (m=1)"; public const String MERCURY_MASS_DESC = "(4.0) <Astronomical Constant> Mercury mass [kg] (kg=1)"; public const String MERCURY_SEMI_MAJOR_AXIS_DESC = "(4.0) <Astronomical Constant> Mercury-Sun distance - semi major axis [m] (m=1)"; public const String VENUS_RADIUS_MEAN_DESC = "(4.0) <Astronomical Constant> Venus mean radius [m] (m=1)"; public const String VENUS_MASS_DESC = "(4.0) <Astronomical Constant> Venus mass [kg] (kg=1)"; public const String VENUS_SEMI_MAJOR_AXIS_DESC = "(4.0) <Astronomical Constant> Venus-Sun distance - semi major axis [m] (m=1)"; public const String MARS_RADIUS_MEAN_DESC = "(4.0) <Astronomical Constant> Mars mean radius [m] (m=1)"; public const String MARS_MASS_DESC = "(4.0) <Astronomical Constant> Mars mass [kg] (kg=1)"; public const String MARS_SEMI_MAJOR_AXIS_DESC = "(4.0) <Astronomical Constant> Mars-Sun distance - semi major axis [m] (m=1)"; public const String JUPITER_RADIUS_MEAN_DESC = "(4.0) <Astronomical Constant> Jupiter mean radius [m] (m=1)"; public const String JUPITER_MASS_DESC = "(4.0) <Astronomical Constant> Jupiter mass [kg] (kg=1)"; public const String JUPITER_SEMI_MAJOR_AXIS_DESC = "(4.0) <Astronomical Constant> Jupiter-Sun distance - semi major axis [m] (m=1)"; public const String SATURN_RADIUS_MEAN_DESC = "(4.0) <Astronomical Constant> Saturn mean radius [m] (m=1)"; public const String SATURN_MASS_DESC = "(4.0) <Astronomical Constant> Saturn mass [kg] (kg=1)"; public const String SATURN_SEMI_MAJOR_AXIS_DESC = "(4.0) <Astronomical Constant> Saturn-Sun distance - semi major axis [m] (m=1)"; public const String URANUS_RADIUS_MEAN_DESC = "(4.0) <Astronomical Constant> Uranus mean radius [m] (m=1)"; public const String URANUS_MASS_DESC = "(4.0) <Astronomical Constant> Uranus mass [kg] (kg=1)"; public const String URANUS_SEMI_MAJOR_AXIS_DESC = "(4.0) <Astronomical Constant> Uranus-Sun distance - semi major axis [m] (m=1)"; public const String NEPTUNE_RADIUS_MEAN_DESC = "(4.0) <Astronomical Constant> Neptune mean radius [m] (m=1)"; public const String NEPTUNE_MASS_DESC = "(4.0) <Astronomical Constant> Neptune mass [kg] (kg=1)"; public const String NEPTUNE_SEMI_MAJOR_AXIS_DESC = "(4.0) <Astronomical Constant> Neptune-Sun distance - semi major axis [m] (m=1)"; /* boolean values */ public const String TRUE_DESC = "(4.1) Boolean True represented as double, [true] = 1"; public const String FALSE_DESC = "(4.1) Boolean False represented as double, [false] = 0"; /* other values */ public const String NAN_DESC = "(4.1) Not-a-Number"; } }
// String.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; namespace System { /// <summary> /// Equivalent to the String type in Javascript. /// </summary> [IgnoreNamespace] [Imported(ObeysTypeSystem = true)] public sealed class String : IComparable<String>, IEquatable<String> { [ScriptName("")] public String() {} [ScriptName("")] public String(String other) {} [InlineCode("{$System.Script}.stringFromChar({$System.String}.fromCharCode({ch}), {count})")] public String(char ch, int count) {} [InlineCode("{$System.String}.fromCharCode.apply(null, {value})")] public String(char[] value) {} [InlineCode("{$System.String}.fromCharCode.apply(null, {value}.slice({startIndex}, {startIndex} + {length}))")] public String(char[] value, int startIndex, int length) {} [IndexerName("Chars")] public char this[int index] { [InlineCode("{this}.charCodeAt({index})")] get { return '\0'; } } [NonScriptable] public IEnumerator<char> GetEnumerator() { return null; } /// <summary> /// An empty zero-length string. /// </summary> [InlineConstant] public const String Empty = ""; /// <summary> /// The number of characters in the string. /// </summary> [IntrinsicProperty] public int Length { get { return 0; } } /// <summary> /// Retrieves the character at the specified position. /// </summary> /// <param name="index">The specified 0-based position.</param> /// <returns>The character within the string.</returns> public string CharAt(int index) { return null; } /// <summary> /// Retrieves the character code of the character at the specified position. /// </summary> /// <param name="index">The specified 0-based position.</param> /// <returns>The character code of the character within the string.</returns> public char CharCodeAt(int index) { return '\0'; } [InlineCode("{$System.Script}.compareStrings({s1}, {s2})")] public static int Compare(string s1, string s2) { return 0; } [InlineCode("{$System.Script}.compareStrings({s1}, {s2}, {ignoreCase})")] public static int Compare(string s1, string s2, bool ignoreCase) { return 0; } [InlineCode("{$System.Script}.compareStrings({this}, {s}, {ignoreCase})")] public int CompareTo(string s, bool ignoreCase) { return 0; } [InlineCode("[{s1}, {s2}].join('')")] public static string Concat(string s1, string s2) { return null; } [InlineCode("[{s1}, {s2}, {s3}].join('')")] public static string Concat(string s1, string s2, string s3) { return null; } [InlineCode("[{s1}, {s2}, {s3}, {s4}].join('')")] public static string Concat(string s1, string s2, string s3, string s4) { return null; } /// <summary> /// Concatenates a set of individual strings into a single string. /// </summary> /// <param name="strings">The sequence of strings</param> /// <returns>The concatenated string.</returns> [InlineCode("{strings}.join('')")] public static string Concat(params string[] strings) { return null; } [InlineCode("[{o1}, {o2}].join('')")] public static string Concat(object o1, object o2) { return null; } [InlineCode("[{o1}, {o2}, {o3}].join('')")] public static string Concat(object o1, object o2, object o3) { return null; } [InlineCode("[{o1}, {o2}, {o3}, {o4}].join('')")] public static string Concat(object o1, object o2, object o3, object o4) { return null; } [InlineCode("{o}.join('')")] public static string Concat(params object[] o) { return null; } [InlineCode("[{o}].join('')")] public static string Concat(object o) { return null; } /// <summary> /// Returns the unencoded version of a complete encoded URI. /// </summary> /// <returns>The unencoded string.</returns> [ScriptAlias("decodeURI")] public static string DecodeUri(string s) { return null; } /// <summary> /// Returns the unencoded version of a single part or component of an encoded URI. /// </summary> /// <returns>The unencoded string.</returns> [ScriptAlias("decodeURIComponent")] public static string DecodeUriComponent(string s) { return null; } /// <summary> /// Encodes the complete URI. /// </summary> /// <returns>The encoded string.</returns> [ScriptAlias("encodeURI")] public static string EncodeUri(string s) { return null; } /// <summary> /// Encodes a single part or component of a URI. /// </summary> /// <returns>The encoded string.</returns> [ScriptAlias("encodeURIComponent")] public static string EncodeUriComponent(string s) { return null; } /// <summary> /// Determines if the string ends with the specified character. /// </summary> /// <param name="ch">The character to test for.</param> /// <returns>true if the string ends with the character; false otherwise.</returns> [InlineCode("{$System.Script}.endsWithString({this}, {$System.String}.fromCharCode({ch}))")] public bool EndsWith(char ch) { return false; } /// <summary> /// Determines if the string ends with the specified substring or suffix. /// </summary> /// <param name="suffix">The string to test for.</param> /// <returns>true if the string ends with the suffix; false otherwise.</returns> [InlineCode("{$System.Script}.endsWithString({this}, {suffix})")] public bool EndsWith(string suffix) { return false; } /// <summary> /// Determines if the strings are equal. /// </summary> /// <returns>true if the string s1 = s2; false otherwise.</returns> [InlineCode("{$System.Script}.compareStrings({s1}, {s2}, {ignoreCase}) === 0)")] public static bool Equals(string s1, string s2, bool ignoreCase) { return false; } /// <summary> /// Encodes a string by replacing punctuation, spaces etc. with their escaped equivalents. /// </summary> /// <returns>The escaped string.</returns> [ScriptAlias("escape") ] public static string Escape(string s) { return null; } [InlineCode("{$System.Script}.formatString({format}, {*values})", NonExpandedFormCode = "{$System.Script}.formatString.apply(null, [{format}].concat({values}))")] public static string Format(string format, params object[] values) { return null; } [ExpandParams] public static string FromCharCode(params char[] charCode) { return null; } [InlineCode("{$System.Script}.htmlDecode({this})")] public string HtmlDecode() { return null; } [InlineCode("{$System.Script}.htmlEncode({this})")] public string HtmlEncode() { return null; } [InlineCode("{this}.indexOf({$System.String}.fromCharCode({ch}))")] public int IndexOf(char ch) { return 0; } public int IndexOf(string subString) { return 0; } [InlineCode("{this}.indexOf({$System.String}.fromCharCode({ch}), {startIndex})")] public int IndexOf(char ch, int startIndex) { return 0; } public int IndexOf(string ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.indexOfString({this}, {$System.String}.fromCharCode({ch}), {startIndex}, {count})")] public int IndexOf(char ch, int startIndex, int count) { return 0; } [InlineCode("{$System.Script}.indexOfString({this}, {ch}, {startIndex}, {count})")] public int IndexOf(string ch, int startIndex, int count) { return 0; } [InlineCode("{$System.Script}.indexOfAnyString({this}, {ch})")] public int IndexOfAny(params char[] ch) { return 0; } [InlineCode("{$System.Script}.indexOfAnyString({this}, {ch}, {startIndex})")] public int IndexOfAny(char[] ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.indexOfAnyString({this}, {ch}, {startIndex}, {count})")] public int IndexOfAny(char[] ch, int startIndex, int count) { return 0; } [InlineCode("{$System.Script}.insertString({this}, {index}, {value})")] public string Insert(int index, string value) { return null; } [InlineCode("{$System.Script}.isNullOrEmptyString({s})")] public static bool IsNullOrEmpty(string s) { return false; } [InlineCode("{this}.lastIndexOf({$System.String}.fromCharCode({ch}))")] public int LastIndexOf(char ch) { return 0; } public int LastIndexOf(string subString) { return 0; } public int LastIndexOf(string subString, int startIndex) { return 0; } [InlineCode("{$System.Script}.lastIndexOfString({this}, {$System.String}.fromCharCode({ch}), {startIndex}, {count})")] public int LastIndexOf(char ch, int startIndex, int count) { return 0; } [InlineCode("{$System.Script}.lastIndexOfString({this}, {subString}, {startIndex}, {count})")] public int LastIndexOf(string subString, int startIndex, int count) { return 0; } [InlineCode("{this}.lastIndexOf({$System.String}.fromCharCode({ch}), {startIndex})")] public int LastIndexOf(char ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.lastIndexOfAnyString({this}, {ch})")] public int LastIndexOfAny(params char[] ch) { return 0; } [InlineCode("{$System.Script}.lastIndexOfAnyString({this}, {ch}, {startIndex})")] public int LastIndexOfAny(char[] ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.lastIndexOfAnyString({this}, {ch}, {startIndex}, {count})")] public int LastIndexOfAny(char[] ch, int startIndex, int count) { return 0; } public int LocaleCompare(string string2) { return 0; } [ExpandParams] public static string LocaleFormat(string format, params object[] values) { return null; } public string[] Match(Regex regex) { return null; } [InlineCode("{$System.Script}.padLeftString({this}, {totalWidth})")] public string PadLeft(int totalWidth) { return null; } [InlineCode("{$System.Script}.padLeftString({this}, {totalWidth}, {ch})")] public string PadLeft(int totalWidth, char ch) { return null; } [InlineCode("{$System.Script}.padRightString({this}, {totalWidth})")] public string PadRight(int totalWidth) { return null; } [InlineCode("{$System.Script}.padRightString({this}, {totalWidth}, {ch})")] public string PadRight(int totalWidth, char ch) { return null; } [InlineCode("{$System.Script}.removeString({this}, {index})")] public string Remove(int index) { return null; } [InlineCode("{$System.Script}.removeString({this}, {index}, {count})")] public string Remove(int index, int count) { return null; } [InlineCode("{$System.Script}.replaceAllString({this}, {oldText}, {replaceText})")] public string Replace(string oldText, string replaceText) { return null; } [InlineCode("{$System.Script}.replaceAllString({this}, {$System.String}.fromCharCode({oldChar}), {$System.String}.fromCharCode({replaceChar}))")] public string Replace(char oldChar, char replaceChar) { return null; } [ScriptName("replace")] public string ReplaceFirst(string oldText, string replaceText) { return null; } [ScriptName("replace")] public string Replace(Regex regex, string replaceText) { return null; } [ScriptName("replace")] public string Replace(Regex regex, StringReplaceCallback callback) { return null; } public int Search(Regex regex) { return 0; } public string[] Split(string separator) { return null; } [InlineCode("{this}.split({$System.String}.fromCharCode({separator}))")] public string[] Split(char separator) { return null; } public string[] Split(string separator, int limit) { return null; } [InlineCode("{this}.split({$System.String}.fromCharCode({separator}), {limit})")] public string[] Split(char separator, int limit) { return null; } public string[] Split(Regex regex) { return null; } public string[] Split(Regex regex, int limit) { return null; } [InlineCode("{$System.Script}.startsWithString({this}, {$System.String}.fromCharCode({ch}))")] public bool StartsWith(char ch) { return false; } [InlineCode("{$System.Script}.startsWithString({this}, {prefix})")] public bool StartsWith(string prefix) { return false; } public string Substr(int startIndex) { return null; } public string Substr(int startIndex, int length) { return null; } public string Substring(int startIndex) { return null; } [ScriptName("substr")] public string Substring(int startIndex, int length) { return null; } [ScriptName("substring")] public string JsSubstring(int startIndex, int end) { return null; } public string ToLocaleLowerCase() { return null; } public string ToLocaleUpperCase() { return null; } public string ToLowerCase() { return null; } [ScriptName("toLowerCase")] public string ToLower() { return null; } public string ToUpperCase() { return null; } [ScriptName("toUpperCase")] public string ToUpper() { return null; } public string Trim() { return null; } [InlineCode("{$System.Script}.trimString({this}, {values})")] public string Trim(params char[] values) { return null; } [InlineCode("{$System.Script}.trimStartString({this}, {values})")] public string TrimStart(params char[] values) { return null; } [InlineCode("{$System.Script}.trimEndString({this}, {values})")] public string TrimEnd(params char[] values) { return null; } [InlineCode("{$System.Script}.trimStartString({this})")] public string TrimStart() { return null; } [InlineCode("{$System.Script}.trimEndString({this})")] public string TrimEnd() { return null; } /// <summary> /// Decodes a string by replacing escaped parts with their equivalent textual representation. /// </summary> /// <returns>The unescaped string.</returns> [ScriptAlias("unescape")] public static string Unescape(string s) { return null; } [IntrinsicOperator] public static bool operator ==(string s1, string s2) { return false; } [IntrinsicOperator] public static bool operator !=(string s1, string s2) { return false; } [InlineCode("{$System.Script}.compare({this}, {other})")] public int CompareTo(string other) { return 0; } [InlineCode("{$System.Script}.equalsT({this}, {other})")] public bool Equals(string other) { return false; } [InlineCode("{$System.Script}.equalsT({a}, {b})")] public static bool Equals(string a, string b) { return false; } [InlineCode("{args}.join({separator})")] public static string Join(string separator, params string[] args) { return null; } [InlineCode("{args}.join({separator})")] public static string Join(string separator, params Object[] args) { return null; } [InlineCode("{$System.Script}.arrayFromEnumerable({args}).join({separator})")] public static string Join(string separator, IEnumerable<string> args) { return null; } [InlineCode("{$System.Script}.arrayFromEnumerable({args}).join({separator})")] public static string Join<T>(string separator, IEnumerable<T> args) { return null; } [InlineCode("{args}.slice({startIndex}, {startIndex} + {count}).join({separator})")] public static string Join(string separator, string[] args, int startIndex, int count) { return null; } [InlineCode("({this}.indexOf({value}) !== -1)")] public bool Contains(string value) { return false; } } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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. #endregion // License using System.Linq; namespace C { /// <summary> /// Base class for collections of C files, be they compilable source or header files. Provides methods that automatically /// generate modules of the correct type given the source paths. /// </summary> [System.Obsolete("Use CModuleCollection instead", true)] abstract class CModuleContainer<ChildModuleType> : CModuleCollection<ChildModuleType> where ChildModuleType : Bam.Core.Module, Bam.Core.IChildModule, IRequiresSourceModule, new() { } /// <summary> /// Base class for collections of C files, be they compilable source or header files. Provides methods that automatically /// generate modules of the correct type given the source paths. /// </summary> abstract class CModuleCollection<ChildModuleType> : CModule, // TODO: should this be here? it has no headers, nor version number Bam.Core.IModuleGroup, IAddFiles where ChildModuleType : Bam.Core.Module, Bam.Core.IChildModule, new() { /// <summary> /// list of child Modules /// </summary> protected System.Collections.Generic.List<ChildModuleType> children = new System.Collections.Generic.List<ChildModuleType>(); /// <summary> /// Add a single child module, given the source path, to the collection. Path must resolve to a single file. /// If the path contains a wildcard (*) character, an exception is thrown. /// </summary> /// <returns>The child module, in order to manage patches.</returns> /// <param name="path">Path to the child file.</param> /// <param name="macroModuleOverride">Macro module override.</param> /// <param name="verbatim">If set to <c>true</c> verbatim.</param> public abstract ChildModuleType AddFile( string path, Bam.Core.Module macroModuleOverride = null, bool verbatim = false); /// <summary> /// Add multiple object files, given a wildcarded source path. /// Allow filtering on the expanded paths, so that only matching paths are included. /// </summary> /// <returns>The files.</returns> /// <param name="path">Path.</param> /// <param name="macroModuleOverride">Macro module override.</param> /// <param name="filter">Filter.</param> public Bam.Core.Array<Bam.Core.Module> AddFiles( string path, Bam.Core.Module macroModuleOverride = null, System.Text.RegularExpressions.Regex filter = null) { if (System.String.IsNullOrEmpty(path)) { throw new Bam.Core.Exception("Cannot add files from an empty path"); } var macroModule = macroModuleOverride ?? this; var tokenizedPath = macroModule.CreateTokenizedString(path); tokenizedPath.Parse(); var wildcardPath = tokenizedPath.ToString(); var dir = System.IO.Path.GetDirectoryName(wildcardPath); if (!System.IO.Directory.Exists(dir)) { throw new Bam.Core.Exception($"The directory {dir} does not exist"); } var leafname = System.IO.Path.GetFileName(wildcardPath); var option = leafname.Contains("**") ? System.IO.SearchOption.AllDirectories : System.IO.SearchOption.TopDirectoryOnly; var files = System.IO.Directory.GetFiles(dir, leafname, option); if (0 == files.Length) { throw new Bam.Core.Exception($"No files were found that matched the pattern '{wildcardPath}'"); } if (filter != null) { var filteredFiles = files.Where(pathname => filter.IsMatch(pathname)).ToArray(); if (0 == filteredFiles.Length) { throw new Bam.Core.Exception( $"No files were found that matched the pattern '{wildcardPath}', after applying the regex filter. {files.Count()} were found prior to applying the filter." ); } files = filteredFiles; } var modulesCreated = new Bam.Core.Array<Bam.Core.Module>(); foreach (var filepath in files) { modulesCreated.Add(this.AddFile(filepath, verbatim: true)); } return modulesCreated; } // note that this is 'new' to hide the version in Bam.Core.Module // C# does not support return type covariance (https://en.wikipedia.org/wiki/Covariant_return_type) /// <summary> /// Return an enumerable of the children of this collection, using the ChildModuleType generic type for each module in the collection. /// </summary> public new System.Collections.Generic.IEnumerable<ChildModuleType> Children => base.Children.Select(item => item as ChildModuleType); /// <summary> /// Return a list of all child modules whose input path contains the specified filename. /// A ForEach function can be applied to the results, to run the same action on each of the child modules. /// </summary> /// <param name="filename">The filename to match</param> /// <returns>List of child modules.</returns> public System.Collections.Generic.List<ChildModuleType> this[string filename] { get { var truePath = filename.Replace(System.IO.Path.AltDirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar); var validSources = this.children.Where(child => { var requiresSourceModule = child as IRequiresSourceModule; if (!requiresSourceModule.Source.InputPath.IsParsed) { requiresSourceModule.Source.InputPath.Parse(); } return requiresSourceModule.Source.InputPath.ToString().Contains(truePath); }); if (!validSources.Any()) { var list_of_valid_source = new System.Text.StringBuilder(); foreach (var child in this.children) { list_of_valid_source.AppendLine($"\t{(child as IRequiresSourceModule).Source.InputPath.ToString()}"); } if (!filename.Equals(truePath, System.StringComparison.Ordinal)) { var message = new System.Text.StringBuilder(); message.Append($"No source files found matching '{filename} "); message.Append($"(actually checking '{truePath}' after directory slash replacement) "); message.Append($"in module {Bam.Core.Graph.Instance.CommonModuleType.Peek().ToString()}. "); message.AppendLine("Found"); message.Append(list_of_valid_source.ToString()); throw new Bam.Core.Exception(message.ToString()); } else { var message = new System.Text.StringBuilder(); message.AppendLine($"No source files found matching '{filename}' in module {Bam.Core.Graph.Instance.CommonModuleType.Peek().ToString()}. Found"); message.Append(list_of_valid_source.ToString()); throw new Bam.Core.Exception(message.ToString()); } } return validSources.ToList(); } } /// <summary> /// Execute the module /// </summary> /// <param name="context">in this context</param> protected override void ExecuteInternal( Bam.Core.ExecutionContext context) { // do nothing } /// <summary> /// Evaluate the module to determine if it's up-to-date /// </summary> protected override void EvaluateInternal() { this.ReasonToExecute = null; try { foreach (var child in this.children) { child.EvaluationTask?.Wait(); if (null != child.ReasonToExecute) { switch (child.ReasonToExecute.Reason) { case Bam.Core.ExecuteReasoning.EReason.FileDoesNotExist: case Bam.Core.ExecuteReasoning.EReason.InputFileIsNewer: { this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer(child.ReasonToExecute.OutputFilePath, child.ReasonToExecute.OutputFilePath); return; } default: throw new Bam.Core.Exception($"Unknown reason, {child.ReasonToExecute.Reason.ToString()}"); } } } } catch (System.AggregateException exception) { throw new Bam.Core.Exception(exception, "Failed to evaluate modules"); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Agent.Sdk; using Agent.Sdk.Knob; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.TeamFoundation.Framework.Common; using Microsoft.VisualStudio.Services.Agent.Util; namespace Microsoft.VisualStudio.Services.Agent.Worker.Container { [ServiceLocator(Default = typeof(DockerCommandManager))] public interface IDockerCommandManager : IAgentService { string DockerPath { get; } string DockerInstanceLabel { get; } Task<DockerVersion> DockerVersion(IExecutionContext context); Task<int> DockerLogin(IExecutionContext context, string server, string username, string password); Task<int> DockerLogout(IExecutionContext context, string server); Task<int> DockerPull(IExecutionContext context, string image); Task<string> DockerCreate(IExecutionContext context, ContainerInfo container); Task<int> DockerStart(IExecutionContext context, string containerId); Task<int> DockerLogs(IExecutionContext context, string containerId); Task<List<string>> DockerPS(IExecutionContext context, string options); Task<int> DockerRemove(IExecutionContext context, string containerId); Task<int> DockerNetworkCreate(IExecutionContext context, string network); Task<int> DockerNetworkRemove(IExecutionContext context, string network); Task<int> DockerNetworkPrune(IExecutionContext context); Task<int> DockerExec(IExecutionContext context, string containerId, string options, string command); Task<int> DockerExec(IExecutionContext context, string containerId, string options, string command, List<string> outputs); Task<string> DockerInspect(IExecutionContext context, string dockerObject, string options); Task<List<PortMapping>> DockerPort(IExecutionContext context, string containerId); Task<bool> IsContainerRunning(IExecutionContext context, string containerId); } public class DockerCommandManager : AgentService, IDockerCommandManager { public string DockerPath { get; private set; } public string DockerInstanceLabel { get; private set; } private static UtilKnobValueContext _knobContext = UtilKnobValueContext.Instance(); public override void Initialize(IHostContext hostContext) { ArgUtil.NotNull(hostContext, nameof(hostContext)); base.Initialize(hostContext); DockerPath = WhichUtil.Which("docker", true, Trace); DockerInstanceLabel = IOUtil.GetPathHash(hostContext.GetDirectory(WellKnownDirectory.Root)).Substring(0, 6); } public async Task<DockerVersion> DockerVersion(IExecutionContext context) { ArgUtil.NotNull(context, nameof(context)); string serverVersionStr = (await ExecuteDockerCommandAsync(context, "version", "--format '{{.Server.APIVersion}}'")).FirstOrDefault(); ArgUtil.NotNullOrEmpty(serverVersionStr, "Docker.Server.Version"); context.Output($"Docker daemon API version: {serverVersionStr}"); string clientVersionStr = (await ExecuteDockerCommandAsync(context, "version", "--format '{{.Client.APIVersion}}'")).FirstOrDefault(); ArgUtil.NotNullOrEmpty(serverVersionStr, "Docker.Client.Version"); context.Output($"Docker client API version: {clientVersionStr}"); // we interested about major.minor.patch version Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase); Version serverVersion = null; var serverVersionMatchResult = verRegex.Match(serverVersionStr); if (serverVersionMatchResult.Success && !string.IsNullOrEmpty(serverVersionMatchResult.Value)) { if (!Version.TryParse(serverVersionMatchResult.Value, out serverVersion)) { serverVersion = null; } } Version clientVersion = null; var clientVersionMatchResult = verRegex.Match(serverVersionStr); if (clientVersionMatchResult.Success && !string.IsNullOrEmpty(clientVersionMatchResult.Value)) { if (!Version.TryParse(clientVersionMatchResult.Value, out clientVersion)) { clientVersion = null; } } return new DockerVersion(serverVersion, clientVersion); } public async Task<int> DockerLogin(IExecutionContext context, string server, string username, string password) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(server, nameof(server)); ArgUtil.NotNull(username, nameof(username)); ArgUtil.NotNull(password, nameof(password)); if (PlatformUtil.RunningOnWindows) { // Wait for 17.07 to switch using stdin for docker registry password. return await ExecuteDockerCommandAsync(context, "login", $"--username \"{username}\" --password \"{password.Replace("\"", "\\\"")}\" {server}", new List<string>() { password }, context.CancellationToken); } return await ExecuteDockerCommandAsync(context, "login", $"--username \"{username}\" --password-stdin {server}", new List<string>() { password }, context.CancellationToken); } public async Task<int> DockerLogout(IExecutionContext context, string server) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(server, nameof(server)); return await ExecuteDockerCommandAsync(context, "logout", $"{server}", context.CancellationToken); } public async Task<int> DockerPull(IExecutionContext context, string image) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(image, nameof(image)); return await ExecuteDockerCommandAsync(context, "pull", image, context.CancellationToken); } public async Task<string> DockerCreate(IExecutionContext context, ContainerInfo container) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(container, nameof(container)); IList<string> dockerOptions = new List<string>(); // OPTIONS dockerOptions.Add($"--name {container.ContainerDisplayName}"); dockerOptions.Add($"--label {DockerInstanceLabel}"); if (!string.IsNullOrEmpty(container.ContainerNetwork)) { dockerOptions.Add($"--network {container.ContainerNetwork}"); } if (!string.IsNullOrEmpty(container.ContainerNetworkAlias)) { dockerOptions.Add($"--network-alias {container.ContainerNetworkAlias}"); } foreach (var port in container.UserPortMappings) { dockerOptions.Add($"-p {port.Value}"); } dockerOptions.Add($"{container.ContainerCreateOptions}"); foreach (var env in container.ContainerEnvironmentVariables) { if (String.IsNullOrEmpty(env.Value) && String.IsNullOrEmpty(context?.Variables.Get("_VSTS_DONT_RESOLVE_ENV_FROM_HOST"))) { // TODO: Remove fallback variable if stable dockerOptions.Add($"-e \"{env.Key}\""); } else { dockerOptions.Add($"-e \"{env.Key}={env.Value.Replace("\"", "\\\"")}\""); } } foreach (var volume in container?.MountVolumes) { // replace `"` with `\"` and add `"{0}"` to all path. String volumeArg; String targetVolume = container.TranslateContainerPathForImageOS(PlatformUtil.HostOS, volume.TargetVolumePath).Replace("\"", "\\\""); if (String.IsNullOrEmpty(volume.SourceVolumePath)) { // Anonymous docker volume volumeArg = $"-v \"{targetVolume}\""; } else { // Named Docker volume / host bind mount volumeArg = $"-v \"{volume.SourceVolumePath.Replace("\"", "\\\"")}\":\"{targetVolume}\""; } if (volume.ReadOnly) { volumeArg += ":ro"; } dockerOptions.Add(volumeArg); } // IMAGE dockerOptions.Add($"{container.ContainerImage}"); // COMMAND dockerOptions.Add($"{container.ContainerCommand}"); var optionsString = string.Join(" ", dockerOptions); List<string> outputStrings = await ExecuteDockerCommandAsync(context, "create", optionsString); return outputStrings.FirstOrDefault(); } public async Task<int> DockerStart(IExecutionContext context, string containerId) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(containerId, nameof(containerId)); return await ExecuteDockerCommandAsync(context, "start", containerId, context.CancellationToken); } public async Task<int> DockerRemove(IExecutionContext context, string containerId) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(containerId, nameof(containerId)); return await ExecuteDockerCommandAsync(context, "rm", $"--force {containerId}", context.CancellationToken); } public async Task<int> DockerLogs(IExecutionContext context, string containerId) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(containerId, nameof(containerId)); return await ExecuteDockerCommandAsync(context, "logs", $"--details {containerId}", context.CancellationToken); } public async Task<List<string>> DockerPS(IExecutionContext context, string options) { ArgUtil.NotNull(context, nameof(context)); return await ExecuteDockerCommandAsync(context, "ps", options); } public async Task<int> DockerNetworkCreate(IExecutionContext context, string network) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(network, nameof(network)); var usingWindowsContainers = context.Containers.Where(x => x.ExecutionOS != PlatformUtil.OS.Windows).Count() == 0; var networkDrivers = await ExecuteDockerCommandAsync(context, "info", "-f \"{{range .Plugins.Network}}{{println .}}{{end}}\""); var valueMTU = AgentKnobs.MTUValueForContainerJobs.GetValue(_knobContext).AsString(); string optionMTU = ""; if (!String.IsNullOrEmpty(valueMTU)) { optionMTU = $"-o \"com.docker.network.driver.mtu={valueMTU}\""; } if (usingWindowsContainers && networkDrivers.Contains("nat")) { return await ExecuteDockerCommandAsync(context, "network", $"create --label {DockerInstanceLabel} {network} {optionMTU} --driver nat", context.CancellationToken); } return await ExecuteDockerCommandAsync(context, "network", $"create --label {DockerInstanceLabel} {network} {optionMTU}", context.CancellationToken); } public async Task<int> DockerNetworkRemove(IExecutionContext context, string network) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(network, nameof(network)); return await ExecuteDockerCommandAsync(context, "network", $"rm {network}", context.CancellationToken); } public async Task<int> DockerNetworkPrune(IExecutionContext context) { ArgUtil.NotNull(context, nameof(context)); return await ExecuteDockerCommandAsync(context, "network", $"prune --force --filter \"label={DockerInstanceLabel}\"", context.CancellationToken); } public async Task<int> DockerExec(IExecutionContext context, string containerId, string options, string command) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(containerId, nameof(containerId)); ArgUtil.NotNull(options, nameof(options)); ArgUtil.NotNull(command, nameof(command)); return await ExecuteDockerCommandAsync(context, "exec", $"{options} {containerId} {command}", context.CancellationToken); } public async Task<int> DockerExec(IExecutionContext context, string containerId, string options, string command, List<string> output) { ArgUtil.NotNull(output, nameof(output)); string arg = $"exec {options} {containerId} {command}".Trim(); context.Command($"{DockerPath} {arg}"); object outputLock = new object(); var processInvoker = HostContext.CreateService<IProcessInvoker>(); processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { if (!string.IsNullOrEmpty(message.Data)) { lock (outputLock) { output.Add(message.Data); } } }; processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { if (!string.IsNullOrEmpty(message.Data)) { lock (outputLock) { output.Add(message.Data); } } }; return await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Work), fileName: DockerPath, arguments: arg, environment: null, requireExitCodeZero: false, outputEncoding: null, cancellationToken: CancellationToken.None); } public async Task<string> DockerInspect(IExecutionContext context, string dockerObject, string options) { return (await ExecuteDockerCommandAsync(context, "inspect", $"{options} {dockerObject}")).FirstOrDefault(); } public async Task<List<PortMapping>> DockerPort(IExecutionContext context, string containerId) { List<string> portMappingLines = await ExecuteDockerCommandAsync(context, "port", containerId); return DockerUtil.ParseDockerPort(portMappingLines); } /// <summary> /// Checks if container with specified id is running /// </summary> /// <param name="context">Current execution context</param> /// <param name="containerId">String representing container id</param> /// <returns /// <c>true</c>, if specified container is running, <c>false</c> otherwise. /// </returns> public async Task<bool> IsContainerRunning(IExecutionContext context, string containerId) { List<string> filteredItems = await DockerPS(context, $"--filter id={containerId}"); // docker ps function is returning table with containers in Running state. // This table is adding to the list line by line. The first string in List is always table header. // The second string appeared only if container by specified id was found and in Running state. // Therefore, we assume that the container is running if the list contains two elements. var isContainerRunning = (filteredItems.Count == 2); return isContainerRunning; } private Task<int> ExecuteDockerCommandAsync(IExecutionContext context, string command, string options, CancellationToken cancellationToken = default(CancellationToken)) { return ExecuteDockerCommandAsync(context, command, options, null, cancellationToken); } private async Task<int> ExecuteDockerCommandAsync(IExecutionContext context, string command, string options, IList<string> standardIns = null, CancellationToken cancellationToken = default(CancellationToken)) { string arg = $"{command} {options}".Trim(); context.Command($"{DockerPath} {arg}"); var processInvoker = HostContext.CreateService<IProcessInvoker>(); processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { context.Output(message.Data); }; processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { context.Output(message.Data); }; InputQueue<string> redirectStandardIn = null; if (standardIns != null) { redirectStandardIn = new InputQueue<string>(); foreach (var input in standardIns) { redirectStandardIn.Enqueue(input); } } using (redirectStandardIn) { return await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Work), fileName: DockerPath, arguments: arg, environment: null, requireExitCodeZero: false, outputEncoding: null, killProcessOnCancel: false, redirectStandardIn: redirectStandardIn, cancellationToken: cancellationToken); } } private async Task<List<string>> ExecuteDockerCommandAsync(IExecutionContext context, string command, string options) { string arg = $"{command} {options}".Trim(); context.Command($"{DockerPath} {arg}"); List<string> output = new List<string>(); var processInvoker = HostContext.CreateService<IProcessInvoker>(); processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { if (!string.IsNullOrEmpty(message.Data)) { output.Add(message.Data); context.Output(message.Data); } }; processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { if (!string.IsNullOrEmpty(message.Data)) { context.Output(message.Data); } }; await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Work), fileName: DockerPath, arguments: arg, environment: null, requireExitCodeZero: true, outputEncoding: null, cancellationToken: CancellationToken.None); return output; } } }
/* * 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.Data; using System.Reflection; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Data.MySQL { public class MySQLEstateStore : IEstateDataStore { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string m_waitTimeoutSelect = "select @@wait_timeout"; private string m_connectionString; private long m_waitTimeout; private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond; private long m_lastConnectionUse; private FieldInfo[] m_Fields; private Dictionary<string, FieldInfo> m_FieldMap = new Dictionary<string, FieldInfo>(); public void Initialise(string connectionString) { m_connectionString = connectionString; try { m_log.Info("[REGION DB]: MySql - connecting: " + Util.GetDisplayConnectionString(m_connectionString)); } catch (Exception e) { m_log.Debug("Exception: password not found in connection string\n" + e.ToString()); } GetWaitTimeout(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); Assembly assem = GetType().Assembly; Migration m = new Migration(dbcon, assem, "EstateStore"); m.Update(); Type t = typeof(EstateSettings); m_Fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (FieldInfo f in m_Fields) { if (f.Name.Substring(0, 2) == "m_") m_FieldMap[f.Name.Substring(2)] = f; } } } private string[] FieldList { get { return new List<string>(m_FieldMap.Keys).ToArray(); } } protected void GetWaitTimeout() { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon)) { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { m_waitTimeout = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; } } } m_lastConnectionUse = DateTime.Now.Ticks; m_log.DebugFormat( "[REGION DB]: Connection wait timeout {0} seconds", m_waitTimeout / TimeSpan.TicksPerSecond); } } public EstateSettings LoadEstateSettings(UUID regionID) { EstateSettings es = new EstateSettings(); es.OnSave += StoreEstateSettings; string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = ?RegionID"; bool migration = true; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); using (IDataReader r = cmd.ExecuteReader()) { if (r.Read()) { migration = false; foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { int v = Convert.ToInt32(r[name]); if (v != 0) m_FieldMap[name].SetValue(es, true); else m_FieldMap[name].SetValue(es, false); } else if (m_FieldMap[name].GetValue(es) is UUID) { UUID uuid = UUID.Zero; UUID.TryParse(r[name].ToString(), out uuid); m_FieldMap[name].SetValue(es, uuid); } else { m_FieldMap[name].SetValue(es, r[name]); } } } } } if (migration) { // Migration case List<string> names = new List<string>(FieldList); names.Remove("EstateID"); sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")"; using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.Clear(); foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) cmd.Parameters.AddWithValue("?" + name, "1"); else cmd.Parameters.AddWithValue("?" + name, "0"); } else { cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString()); } } cmd.ExecuteNonQuery(); cmd.CommandText = "select LAST_INSERT_ID() as id"; cmd.Parameters.Clear(); using (IDataReader r = cmd.ExecuteReader()) { r.Read(); es.EstateID = Convert.ToUInt32(r["id"]); } cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)"; cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); // This will throw on dupe key try { cmd.ExecuteNonQuery(); } catch (Exception) { } // Munge and transfer the ban list cmd.Parameters.Clear(); cmd.CommandText = "insert into estateban select " + es.EstateID.ToString() + ", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = ?UUID"; cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); try { cmd.ExecuteNonQuery(); } catch (Exception) { } es.Save(); } } } LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); return es; } public void StoreEstateSettings(EstateSettings es) { string sql = "replace into estate_settings (" + String.Join(",", FieldList) + ") values ( ?" + String.Join(", ?", FieldList) + ")"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) cmd.Parameters.AddWithValue("?" + name, "1"); else cmd.Parameters.AddWithValue("?" + name, "0"); } else { cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString()); } } cmd.ExecuteNonQuery(); } } SaveBanList(es); SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups); } private void LoadBanList(EstateSettings es) { es.ClearBans(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", es.EstateID); using (IDataReader r = cmd.ExecuteReader()) { while (r.Read()) { EstateBan eb = new EstateBan(); UUID uuid = new UUID(); UUID.TryParse(r["bannedUUID"].ToString(), out uuid); eb.BannedUserID = uuid; eb.BannedHostAddress = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0"; es.AddBan(eb); } } } } } private void SaveBanList(EstateSettings es) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "delete from estateban where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )"; foreach (EstateBan b in es.EstateBans) { cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } } void SaveUUIDList(uint EstateID, string table, UUID[] data) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )"; foreach (UUID uuid in data) { cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.Parameters.AddWithValue("?uuid", uuid.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } } UUID[] LoadUUIDList(uint EstateID, string table) { List<UUID> uuids = new List<UUID>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", EstateID); using (IDataReader r = cmd.ExecuteReader()) { while (r.Read()) { // EstateBan eb = new EstateBan(); UUID uuid = new UUID(); UUID.TryParse(r["uuid"].ToString(), out uuid); uuids.Add(uuid); } } } } return uuids.ToArray(); } } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at https://github.com/jeremyskinner/FluentValidation #endregion namespace FluentValidation.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Internal; using Xunit; using Validators; public class DefaultValidatorExtensionTester { private AbstractValidator<Person> validator; public DefaultValidatorExtensionTester() { validator = new TestValidator(); } [Fact] public void NotNull_should_create_NotNullValidator() { validator.RuleFor(x => x.Surname).NotNull(); AssertValidator<NotNullValidator>(); } [Fact] public void NotEmpty_should_create_NotEmptyValidator() { validator.RuleFor(x => x.Surname).NotEmpty(); AssertValidator<NotEmptyValidator>(); } [Fact] public void Empty_should_create_EmptyValidator() { validator.RuleFor(x => x.Surname).Empty(); AssertValidator<EmptyValidator>(); } [Fact] public void Length_should_create_LengthValidator() { validator.RuleFor(x => x.Surname).Length(1, 20); AssertValidator<LengthValidator>(); } [Fact] public void Length_should_create_ExactLengthValidator() { validator.RuleFor(x => x.Surname).Length(5); AssertValidator<ExactLengthValidator>(); } [Fact] public void NotEqual_should_create_NotEqualValidator_with_explicit_value() { validator.RuleFor(x => x.Surname).NotEqual("Foo"); AssertValidator<NotEqualValidator>(); } [Fact] public void NotEqual_should_create_NotEqualValidator_with_lambda() { validator.RuleFor(x => x.Surname).NotEqual(x => "Foo"); AssertValidator<NotEqualValidator>(); } [Fact] public void Equal_should_create_EqualValidator_with_explicit_value() { validator.RuleFor(x => x.Surname).Equal("Foo"); AssertValidator<EqualValidator>(); } [Fact] public void Equal_should_create_EqualValidator_with_lambda() { validator.RuleFor(x => x.Surname).Equal(x => "Foo"); AssertValidator<EqualValidator>(); } [Fact] public void Must_should_create_PredicteValidator() { validator.RuleFor(x => x.Surname).Must(x => true); AssertValidator<PredicateValidator>(); } [Fact] public void Must_should_create_PredicateValidator_with_context() { validator.RuleFor(x => x.Surname).Must((x, val) => true); AssertValidator<PredicateValidator>(); } [Fact] public void Must_should_create_PredicateValidator_with_PropertyValidatorContext() { var hasPropertyValidatorContext = false; this.validator.RuleFor(x => x.Surname).Must((x, val, ctx) => { hasPropertyValidatorContext = ctx != null; return true; }); this.validator.Validate(new Person() { Surname = "Surname" }); this.AssertValidator<PredicateValidator>(); hasPropertyValidatorContext.ShouldBeTrue(); } [Fact] public void MustAsync_should_create_AsyncPredicteValidator() { validator.RuleFor(x => x.Surname).MustAsync(async (x, cancel) => true); AssertValidator<AsyncPredicateValidator>(); } [Fact] public void MustAsync_should_create_AsyncPredicateValidator_with_context() { validator.RuleFor(x => x.Surname).MustAsync(async (x, val) => true); AssertValidator<AsyncPredicateValidator>(); } [Fact] public void MustAsync_should_create_AsyncPredicateValidator_with_PropertyValidatorContext() { var hasPropertyValidatorContext = false; this.validator.RuleFor(x => x.Surname).MustAsync(async (x, val, ctx, cancel) => { hasPropertyValidatorContext = ctx != null; return true; }); this.validator.ValidateAsync(new Person { Surname = "Surname" }).Wait(); this.AssertValidator<AsyncPredicateValidator>(); hasPropertyValidatorContext.ShouldBeTrue(); } [Fact] public void LessThan_should_create_LessThanValidator_with_explicit_value() { validator.RuleFor(x => x.Surname).LessThan("foo"); AssertValidator<LessThanValidator>(); } [Fact] public void LessThan_should_create_LessThanValidator_with_lambda() { validator.RuleFor(x => x.Surname).LessThan(x => "foo"); AssertValidator<LessThanValidator>(); } [Fact] public void LessThanOrEqual_should_create_LessThanOrEqualValidator_with_explicit_value() { validator.RuleFor(x => x.Surname).LessThanOrEqualTo("foo"); AssertValidator<LessThanOrEqualValidator>(); } [Fact] public void LessThanOrEqual_should_create_LessThanOrEqualValidator_with_lambda() { validator.RuleFor(x => x.Surname).LessThanOrEqualTo(x => "foo"); AssertValidator<LessThanOrEqualValidator>(); } [Fact] public void LessThanOrEqual_should_create_LessThanOrEqualValidator_with_lambda_with_other_Nullable() { validator.RuleFor(x => x.NullableInt).LessThanOrEqualTo(x => x.OtherNullableInt); AssertValidator<LessThanOrEqualValidator>(); } [Fact] public void GreaterThan_should_create_GreaterThanValidator_with_explicit_value() { validator.RuleFor(x => x.Surname).GreaterThan("foo"); AssertValidator<GreaterThanValidator>(); } [Fact] public void GreaterThan_should_create_GreaterThanValidator_with_lambda() { validator.RuleFor(x => x.Surname).GreaterThan(x => "foo"); AssertValidator<GreaterThanValidator>(); } [Fact] public void GreaterThanOrEqual_should_create_GreaterThanOrEqualValidator_with_explicit_value() { validator.RuleFor(x => x.Surname).GreaterThanOrEqualTo("foo"); AssertValidator<GreaterThanOrEqualValidator>(); } [Fact] public void GreaterThanOrEqual_should_create_GreaterThanOrEqualValidator_with_lambda() { validator.RuleFor(x => x.Surname).GreaterThanOrEqualTo(x => "foo"); AssertValidator<GreaterThanOrEqualValidator>(); } [Fact] public void GreaterThanOrEqual_should_create_GreaterThanOrEqualValidator_with_lambda_with_other_Nullable() { validator.RuleFor(x => x.NullableInt).GreaterThanOrEqualTo(x => x.OtherNullableInt); AssertValidator<GreaterThanOrEqualValidator>(); } #if !PORTABLE40 [Fact] public void MustAsync_should_not_throw_InvalidCastException() { var model = new Model { Ids = new Guid[0] }; var validator = new AsyncModelTestValidator(); // this fails with "Specified cast is not valid" error var result = validator.ValidateAsync(model).Result; result.IsValid.ShouldBeTrue(); } #endif private void AssertValidator<TValidator>() { var rule = (PropertyRule)validator.First(); rule.CurrentValidator.ShouldBe<TValidator>(); } class Model { public IEnumerable<Guid> Ids { get; set; } } #if !PORTABLE40 class AsyncModelTestValidator : AbstractValidator<Model> { public AsyncModelTestValidator() { RuleForEach(m => m.Ids) .MustAsync((g, cancel) => Task.FromResult(true)); } } #endif } }
namespace Sordid.Core.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.Aspects", c => new { Id = c.Int(nullable: false, identity: true), Order = c.Int(nullable: false), HeadingLabel = c.String(), SubHeadingLabel = c.String(), DescriptiveBlurb = c.String(), EventsLabel = c.String(), StoryTitleLabel = c.String(), StarringLabel = c.String(), DateCreated = c.DateTime(nullable: false), DateUpdated = c.DateTime(nullable: false), ConcurrencyVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.CharacterPowers", c => new { Id = c.Int(nullable: false, identity: true), PowerId = c.Int(nullable: false), CharacterId = c.Int(nullable: false), DateCreated = c.DateTime(nullable: false), DateUpdated = c.DateTime(nullable: false), ConcurrencyVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Characters", t => t.CharacterId, cascadeDelete: true) .ForeignKey("dbo.Powers", t => t.PowerId, cascadeDelete: true) .Index(t => t.CharacterId) .Index(t => t.PowerId); CreateTable( "dbo.Characters", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), PlayerName = c.String(), Appearance = c.String(), Notes = c.String(), StoryTitle = c.String(), Starring = c.String(), ImageUrl = c.String(), MaxSkillPoints = c.Int(nullable: false), BaseRefresh = c.Int(nullable: false), PowerLevelId = c.Int(), TemplateId = c.Int(), PhysicalStress = c.Int(nullable: false), MentalStress = c.Int(nullable: false), SocialStress = c.Int(nullable: false), ApplicationUserId = c.String(nullable: false, maxLength: 128), DateCreated = c.DateTime(nullable: false), DateUpdated = c.DateTime(nullable: false), ConcurrencyVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.PowerLevels", t => t.PowerLevelId) .ForeignKey("dbo.Templates", t => t.TemplateId) .ForeignKey("dbo.Users", t => t.ApplicationUserId, cascadeDelete: true) .Index(t => t.PowerLevelId) .Index(t => t.TemplateId) .Index(t => t.ApplicationUserId); CreateTable( "dbo.CharacterAspects", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Events = c.String(), Starring = c.String(), StoryTitle = c.String(), CharacterId = c.Int(nullable: false), AspectId = c.Int(nullable: false), DateCreated = c.DateTime(nullable: false), DateUpdated = c.DateTime(nullable: false), ConcurrencyVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Aspects", t => t.AspectId, cascadeDelete: true) .ForeignKey("dbo.Characters", t => t.CharacterId, cascadeDelete: true) .Index(t => t.AspectId) .Index(t => t.CharacterId); CreateTable( "dbo.Consequences", c => new { Id = c.Int(nullable: false, identity: true), Type = c.String(), StressType = c.String(), StressAmount = c.Int(nullable: false), UserCreated = c.Boolean(nullable: false), CharacterId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Characters", t => t.CharacterId, cascadeDelete: true) .Index(t => t.CharacterId); CreateTable( "dbo.PowerLevels", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), BaseRefresh = c.Int(nullable: false), SkillPoints = c.Int(nullable: false), MaxSkillRank = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.CharacterSkills", c => new { Id = c.Int(nullable: false, identity: true), Rank = c.Int(nullable: false), CharacterId = c.Int(nullable: false), SkillId = c.Int(nullable: false), DateCreated = c.DateTime(nullable: false), DateUpdated = c.DateTime(nullable: false), ConcurrencyVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Skills", t => t.SkillId, cascadeDelete: true) .ForeignKey("dbo.Characters", t => t.CharacterId, cascadeDelete: true) .Index(t => t.SkillId) .Index(t => t.CharacterId); CreateTable( "dbo.Skills", c => new { Id = c.Int(nullable: false, identity: true), Type = c.Int(nullable: false), Name = c.String(), Trappings = c.String(), DateCreated = c.DateTime(nullable: false), DateUpdated = c.DateTime(nullable: false), ConcurrencyVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Templates", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Users", c => new { Id = c.String(nullable: false, maxLength: 128), UserName = c.String(), PasswordHash = c.String(), SecurityStamp = c.String(), Discriminator = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.UserClaims", c => new { Id = c.Int(nullable: false, identity: true), ClaimType = c.String(), ClaimValue = c.String(), User_Id = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.User_Id, cascadeDelete: true) .Index(t => t.User_Id); CreateTable( "dbo.UserLogins", c => new { UserId = c.String(nullable: false, maxLength: 128), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.LoginProvider, t.ProviderKey }) .ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.UserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.Roles", t => t.RoleId, cascadeDelete: true) .ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.Roles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Powers", c => new { Id = c.Int(nullable: false, identity: true), Type = c.Int(nullable: false), Cost = c.Int(nullable: false), Name = c.String(), Notes = c.String(), DateCreated = c.DateTime(nullable: false), DateUpdated = c.DateTime(nullable: false), ConcurrencyVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.CharacterPowers", "PowerId", "dbo.Powers"); DropForeignKey("dbo.Characters", "ApplicationUserId", "dbo.Users"); DropForeignKey("dbo.UserClaims", "User_Id", "dbo.Users"); DropForeignKey("dbo.UserRoles", "UserId", "dbo.Users"); DropForeignKey("dbo.UserRoles", "RoleId", "dbo.Roles"); DropForeignKey("dbo.UserLogins", "UserId", "dbo.Users"); DropForeignKey("dbo.Characters", "TemplateId", "dbo.Templates"); DropForeignKey("dbo.CharacterSkills", "CharacterId", "dbo.Characters"); DropForeignKey("dbo.CharacterSkills", "SkillId", "dbo.Skills"); DropForeignKey("dbo.CharacterPowers", "CharacterId", "dbo.Characters"); DropForeignKey("dbo.Characters", "PowerLevelId", "dbo.PowerLevels"); DropForeignKey("dbo.Consequences", "CharacterId", "dbo.Characters"); DropForeignKey("dbo.CharacterAspects", "CharacterId", "dbo.Characters"); DropForeignKey("dbo.CharacterAspects", "AspectId", "dbo.Aspects"); DropIndex("dbo.CharacterPowers", new[] { "PowerId" }); DropIndex("dbo.Characters", new[] { "ApplicationUserId" }); DropIndex("dbo.UserClaims", new[] { "User_Id" }); DropIndex("dbo.UserRoles", new[] { "UserId" }); DropIndex("dbo.UserRoles", new[] { "RoleId" }); DropIndex("dbo.UserLogins", new[] { "UserId" }); DropIndex("dbo.Characters", new[] { "TemplateId" }); DropIndex("dbo.CharacterSkills", new[] { "CharacterId" }); DropIndex("dbo.CharacterSkills", new[] { "SkillId" }); DropIndex("dbo.CharacterPowers", new[] { "CharacterId" }); DropIndex("dbo.Characters", new[] { "PowerLevelId" }); DropIndex("dbo.Consequences", new[] { "CharacterId" }); DropIndex("dbo.CharacterAspects", new[] { "CharacterId" }); DropIndex("dbo.CharacterAspects", new[] { "AspectId" }); DropTable("dbo.Powers"); DropTable("dbo.Roles"); DropTable("dbo.UserRoles"); DropTable("dbo.UserLogins"); DropTable("dbo.UserClaims"); DropTable("dbo.Users"); DropTable("dbo.Templates"); DropTable("dbo.Skills"); DropTable("dbo.CharacterSkills"); DropTable("dbo.PowerLevels"); DropTable("dbo.Consequences"); DropTable("dbo.CharacterAspects"); DropTable("dbo.Characters"); DropTable("dbo.CharacterPowers"); DropTable("dbo.Aspects"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System { // This file defines an internal class used to throw exceptions in BCL code. // The main purpose is to reduce code size. // // The old way to throw an exception generates quite a lot IL code and assembly code. // Following is an example: // C# source // throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); // IL code: // IL_0003: ldstr "key" // IL_0008: ldstr "ArgumentNull_Key" // IL_000d: call string System.Environment::GetResourceString(string) // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string) // IL_0017: throw // which is 21bytes in IL. // // So we want to get rid of the ldstr and call to Environment.GetResource in IL. // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the // argument name and resource name in a small integer. The source code will be changed to // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); // // The IL code will be 7 bytes. // IL_0008: ldc.i4.4 // IL_0009: ldc.i4.4 // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) // IL_000f: ldarg.0 // // This will also reduce the Jitted code size a lot. // // It is very important we do this for generic classes because we can easily generate the same code // multiple times for different instantiation. // using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics.Contracts; [Pure] internal static class ThrowHelper { internal static void ThrowArgumentOutOfRangeException() { ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType) { throw new ArgumentException(Environment.GetResourceString("Arg_WrongType", key, targetType), "key"); } internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType) { throw new ArgumentException(Environment.GetResourceString("Arg_WrongType", value, targetType), "value"); } #if FEATURE_CORECLR internal static void ThrowAddingDuplicateWithKeyArgumentException(object key) { throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicateWithKey", key)); } #endif internal static void ThrowKeyNotFoundException() { throw new System.Collections.Generic.KeyNotFoundException(); } internal static void ThrowArgumentException(ExceptionResource resource) { throw new ArgumentException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument) { throw new ArgumentException(Environment.GetResourceString(GetResourceName(resource)), GetArgumentName(argument)); } internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw new ArgumentNullException(GetArgumentName(argument)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { // Dev11 474369 quirk: Mango had an empty message string: throw new ArgumentOutOfRangeException(GetArgumentName(argument), String.Empty); } else { throw new ArgumentOutOfRangeException(GetArgumentName(argument), Environment.GetResourceString(GetResourceName(resource))); } } internal static void ThrowInvalidOperationException(ExceptionResource resource) { throw new InvalidOperationException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowSerializationException(ExceptionResource resource) { throw new SerializationException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowSecurityException(ExceptionResource resource) { throw new System.Security.SecurityException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowNotSupportedException(ExceptionResource resource) { throw new NotSupportedException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowUnauthorizedAccessException(ExceptionResource resource) { throw new UnauthorizedAccessException(Environment.GetResourceString(GetResourceName(resource))); } internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource) { throw new ObjectDisposedException(objectName, Environment.GetResourceString(GetResourceName(resource))); } // Allow nulls for reference types and Nullable<U>, but not for value types. internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName) { // Note that default(T) is not equal to null for value types except when T is Nullable<U>. if (value == null && !(default(T) == null)) ThrowHelper.ThrowArgumentNullException(argName); } // // This function will convert an ExceptionArgument enum value to the argument name string. // internal static string GetArgumentName(ExceptionArgument argument) { string argumentName = null; switch (argument) { case ExceptionArgument.array: argumentName = "array"; break; case ExceptionArgument.arrayIndex: argumentName = "arrayIndex"; break; case ExceptionArgument.capacity: argumentName = "capacity"; break; case ExceptionArgument.collection: argumentName = "collection"; break; case ExceptionArgument.list: argumentName = "list"; break; case ExceptionArgument.converter: argumentName = "converter"; break; case ExceptionArgument.count: argumentName = "count"; break; case ExceptionArgument.dictionary: argumentName = "dictionary"; break; case ExceptionArgument.dictionaryCreationThreshold: argumentName = "dictionaryCreationThreshold"; break; case ExceptionArgument.index: argumentName = "index"; break; case ExceptionArgument.info: argumentName = "info"; break; case ExceptionArgument.key: argumentName = "key"; break; case ExceptionArgument.match: argumentName = "match"; break; case ExceptionArgument.obj: argumentName = "obj"; break; case ExceptionArgument.queue: argumentName = "queue"; break; case ExceptionArgument.stack: argumentName = "stack"; break; case ExceptionArgument.startIndex: argumentName = "startIndex"; break; case ExceptionArgument.value: argumentName = "value"; break; case ExceptionArgument.name: argumentName = "name"; break; case ExceptionArgument.mode: argumentName = "mode"; break; case ExceptionArgument.item: argumentName = "item"; break; case ExceptionArgument.options: argumentName = "options"; break; case ExceptionArgument.view: argumentName = "view"; break; case ExceptionArgument.sourceBytesToCopy: argumentName = "sourceBytesToCopy"; break; default: Contract.Assert(false, "The enum value is not defined, please checked ExceptionArgumentName Enum."); return string.Empty; } return argumentName; } // // This function will convert an ExceptionResource enum value to the resource string. // internal static string GetResourceName(ExceptionResource resource) { string resourceName = null; switch (resource) { case ExceptionResource.Argument_ImplementIComparable: resourceName = "Argument_ImplementIComparable"; break; case ExceptionResource.Argument_AddingDuplicate: resourceName = "Argument_AddingDuplicate"; break; case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection: resourceName = "ArgumentOutOfRange_BiggerThanCollection"; break; case ExceptionResource.ArgumentOutOfRange_Count: resourceName = "ArgumentOutOfRange_Count"; break; case ExceptionResource.ArgumentOutOfRange_Index: resourceName = "ArgumentOutOfRange_Index"; break; case ExceptionResource.ArgumentOutOfRange_InvalidThreshold: resourceName = "ArgumentOutOfRange_InvalidThreshold"; break; case ExceptionResource.ArgumentOutOfRange_ListInsert: resourceName = "ArgumentOutOfRange_ListInsert"; break; case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum: resourceName = "ArgumentOutOfRange_NeedNonNegNum"; break; case ExceptionResource.ArgumentOutOfRange_SmallCapacity: resourceName = "ArgumentOutOfRange_SmallCapacity"; break; case ExceptionResource.Arg_ArrayPlusOffTooSmall: resourceName = "Arg_ArrayPlusOffTooSmall"; break; case ExceptionResource.Arg_RankMultiDimNotSupported: resourceName = "Arg_RankMultiDimNotSupported"; break; case ExceptionResource.Arg_NonZeroLowerBound: resourceName = "Arg_NonZeroLowerBound"; break; case ExceptionResource.Argument_InvalidArrayType: resourceName = "Argument_InvalidArrayType"; break; case ExceptionResource.Argument_InvalidOffLen: resourceName = "Argument_InvalidOffLen"; break; case ExceptionResource.Argument_ItemNotExist: resourceName = "Argument_ItemNotExist"; break; case ExceptionResource.InvalidOperation_CannotRemoveFromStackOrQueue: resourceName = "InvalidOperation_CannotRemoveFromStackOrQueue"; break; case ExceptionResource.InvalidOperation_EmptyQueue: resourceName = "InvalidOperation_EmptyQueue"; break; case ExceptionResource.InvalidOperation_EnumOpCantHappen: resourceName = "InvalidOperation_EnumOpCantHappen"; break; case ExceptionResource.InvalidOperation_EnumFailedVersion: resourceName = "InvalidOperation_EnumFailedVersion"; break; case ExceptionResource.InvalidOperation_EmptyStack: resourceName = "InvalidOperation_EmptyStack"; break; case ExceptionResource.InvalidOperation_EnumNotStarted: resourceName = "InvalidOperation_EnumNotStarted"; break; case ExceptionResource.InvalidOperation_EnumEnded: resourceName = "InvalidOperation_EnumEnded"; break; case ExceptionResource.NotSupported_KeyCollectionSet: resourceName = "NotSupported_KeyCollectionSet"; break; case ExceptionResource.NotSupported_ReadOnlyCollection: resourceName = "NotSupported_ReadOnlyCollection"; break; case ExceptionResource.NotSupported_ValueCollectionSet: resourceName = "NotSupported_ValueCollectionSet"; break; case ExceptionResource.NotSupported_SortedListNestedWrite: resourceName = "NotSupported_SortedListNestedWrite"; break; case ExceptionResource.Serialization_InvalidOnDeser: resourceName = "Serialization_InvalidOnDeser"; break; case ExceptionResource.Serialization_MissingKeys: resourceName = "Serialization_MissingKeys"; break; case ExceptionResource.Serialization_NullKey: resourceName = "Serialization_NullKey"; break; case ExceptionResource.Argument_InvalidType: resourceName = "Argument_InvalidType"; break; case ExceptionResource.Argument_InvalidArgumentForComparison: resourceName = "Argument_InvalidArgumentForComparison"; break; case ExceptionResource.InvalidOperation_NoValue: resourceName = "InvalidOperation_NoValue"; break; case ExceptionResource.InvalidOperation_RegRemoveSubKey: resourceName = "InvalidOperation_RegRemoveSubKey"; break; case ExceptionResource.Arg_RegSubKeyAbsent: resourceName = "Arg_RegSubKeyAbsent"; break; case ExceptionResource.Arg_RegSubKeyValueAbsent: resourceName = "Arg_RegSubKeyValueAbsent"; break; case ExceptionResource.Arg_RegKeyDelHive: resourceName = "Arg_RegKeyDelHive"; break; case ExceptionResource.Security_RegistryPermission: resourceName = "Security_RegistryPermission"; break; case ExceptionResource.Arg_RegSetStrArrNull: resourceName = "Arg_RegSetStrArrNull"; break; case ExceptionResource.Arg_RegSetMismatchedKind: resourceName = "Arg_RegSetMismatchedKind"; break; case ExceptionResource.UnauthorizedAccess_RegistryNoWrite: resourceName = "UnauthorizedAccess_RegistryNoWrite"; break; case ExceptionResource.ObjectDisposed_RegKeyClosed: resourceName = "ObjectDisposed_RegKeyClosed"; break; case ExceptionResource.Arg_RegKeyStrLenBug: resourceName = "Arg_RegKeyStrLenBug"; break; case ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck: resourceName = "Argument_InvalidRegistryKeyPermissionCheck"; break; case ExceptionResource.NotSupported_InComparableType: resourceName = "NotSupported_InComparableType"; break; case ExceptionResource.Argument_InvalidRegistryOptionsCheck: resourceName = "Argument_InvalidRegistryOptionsCheck"; break; case ExceptionResource.Argument_InvalidRegistryViewCheck: resourceName = "Argument_InvalidRegistryViewCheck"; break; default: Contract.Assert( false, "The enum value is not defined, please checked ExceptionArgumentName Enum."); return string.Empty; } return resourceName; } } // // The convention for this enum is using the argument name as the enum name // internal enum ExceptionArgument { obj, dictionary, dictionaryCreationThreshold, array, info, key, collection, list, match, converter, queue, stack, capacity, index, startIndex, value, count, arrayIndex, name, mode, item, options, view, sourceBytesToCopy, } // // The convention for this enum is using the resource name as the enum name // internal enum ExceptionResource { Argument_ImplementIComparable, Argument_InvalidType, Argument_InvalidArgumentForComparison, Argument_InvalidRegistryKeyPermissionCheck, ArgumentOutOfRange_NeedNonNegNum, Arg_ArrayPlusOffTooSmall, Arg_NonZeroLowerBound, Arg_RankMultiDimNotSupported, Arg_RegKeyDelHive, Arg_RegKeyStrLenBug, Arg_RegSetStrArrNull, Arg_RegSetMismatchedKind, Arg_RegSubKeyAbsent, Arg_RegSubKeyValueAbsent, Argument_AddingDuplicate, Serialization_InvalidOnDeser, Serialization_MissingKeys, Serialization_NullKey, Argument_InvalidArrayType, NotSupported_KeyCollectionSet, NotSupported_ValueCollectionSet, ArgumentOutOfRange_SmallCapacity, ArgumentOutOfRange_Index, Argument_InvalidOffLen, Argument_ItemNotExist, ArgumentOutOfRange_Count, ArgumentOutOfRange_InvalidThreshold, ArgumentOutOfRange_ListInsert, NotSupported_ReadOnlyCollection, InvalidOperation_CannotRemoveFromStackOrQueue, InvalidOperation_EmptyQueue, InvalidOperation_EnumOpCantHappen, InvalidOperation_EnumFailedVersion, InvalidOperation_EmptyStack, ArgumentOutOfRange_BiggerThanCollection, InvalidOperation_EnumNotStarted, InvalidOperation_EnumEnded, NotSupported_SortedListNestedWrite, InvalidOperation_NoValue, InvalidOperation_RegRemoveSubKey, Security_RegistryPermission, UnauthorizedAccess_RegistryNoWrite, ObjectDisposed_RegKeyClosed, NotSupported_InComparableType, Argument_InvalidRegistryOptionsCheck, Argument_InvalidRegistryViewCheck } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Microsoft.PythonTools.Debugger; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.Python; namespace DebuggerTests { public class BaseDebuggerTests { static BaseDebuggerTests() { AssertListener.Initialize(); PythonTestData.Deploy(); } protected const int DefaultWaitForExitTimeout = 20000; internal virtual string DebuggerTestPath { get { return TestData.GetPath(@"TestData\DebuggerProject\"); } } internal static void ForEachLine(TextReader reader, Action<string> action) { for (var line = reader.ReadLine(); line != null; line = reader.ReadLine()) { action(line); } } internal class EvalResult { private readonly string _typeName, _repr; private readonly long? _length; private readonly PythonEvaluationResultFlags? _flags; private readonly bool _allowOtherFlags; public readonly string ExceptionText, Expression; public readonly bool IsError; public string HexRepr; public bool ValidateRepr = true; public bool ValidateHexRepr = false; public static EvalResult Exception(string expression, string exceptionText) { return new EvalResult(expression, exceptionText, false); } public static EvalResult Value(string expression, string typeName, string repr, long? length = null, PythonEvaluationResultFlags? flags = null, bool allowOtherFlags = false) { return new EvalResult(expression, typeName, repr, length, flags, allowOtherFlags); } public static EvalResult ErrorExpression(string expression, string error) { return new EvalResult(expression, error, true); } EvalResult(string expression, string exceptionText, bool isError) { Expression = expression; ExceptionText = exceptionText; IsError = isError; } EvalResult(string expression, string typeName, string repr, long? length, PythonEvaluationResultFlags? flags, bool allowOtherFlags) { Expression = expression; _typeName = typeName; _repr = repr; _length = length; _flags = flags; _allowOtherFlags = allowOtherFlags; } public void Validate(PythonEvaluationResult result) { if (ExceptionText != null) { Assert.AreEqual(ExceptionText, result.ExceptionText); } else { if (_typeName != null) { Assert.AreEqual(_typeName, result.TypeName); } if (ValidateRepr) { Assert.AreEqual(_repr, result.StringRepr); } if (ValidateHexRepr) { Assert.AreEqual(HexRepr, result.HexRepr); } if (_length != null) { Assert.AreEqual(_length.Value, result.Length); } if (_flags != null) { if (_allowOtherFlags) { Assert.AreEqual(_flags.Value, _flags.Value & result.Flags); } else { Assert.AreEqual(_flags.Value, result.Flags); } } } } } internal class VariableCollection : List<EvalResult> { public void Add(string name, string typeName = null, string repr = null) { var er = EvalResult.Value(name, typeName, repr); if (repr == null) { er.ValidateRepr = false; } Add(er); } public void AddRange(params string[] names) { foreach (var name in names) { Add(name); } } } internal class BreakpointBase { public string FileName; // if null, BreakpointTest.BreakFileName is used instead public int LineNumber; public bool? ExpectHitOnMainThread; public bool RemoveWhenHit; public Action<BreakpointHitEventArgs> OnHit; } internal class Breakpoint : BreakpointBase { public PythonBreakpointConditionKind ConditionKind; public string Condition; public PythonBreakpointPassCountKind PassCountKind; public int PassCount; public bool? IsBindFailureExpected; public Breakpoint(int lineNumber) { LineNumber = lineNumber; } public Breakpoint(string fileName, int lineNumber) { Assert.IsTrue(fileName.EndsWith(".py")); FileName = fileName; LineNumber = lineNumber; } } internal class DjangoBreakpoint : BreakpointBase { public DjangoBreakpoint(int lineNumber) { LineNumber = lineNumber; } } internal class BreakpointCollection : List<BreakpointBase> { public void Add(int lineNumber) { Add(new Breakpoint(lineNumber)); } public void AddRange(params int[] lineNumbers) { foreach (var lineNumber in lineNumbers) { Add(lineNumber); } } } internal PythonProcess DebugProcess(PythonDebugger debugger, string filename, Action<PythonProcess, PythonThread> onLoaded = null, bool resumeOnProcessLoaded = true, string interpreterOptions = null, PythonDebugOptions debugOptions = PythonDebugOptions.RedirectOutput, string cwd = null, string arguments = "") { return debugger.DebugProcess(Version, filename, onLoaded, resumeOnProcessLoaded, interpreterOptions, debugOptions, cwd, arguments); } internal class BreakpointTest { private readonly BaseDebuggerTests _tests; public readonly BreakpointCollection Breakpoints = new BreakpointCollection(); public readonly List<int> ExpectedHits = new List<int>(); // indices into Breakpoints public string WorkingDirectory; public string RunFileName; public string BreakFileName; // if null, RunFileName is used instead public PythonDebugOptions DebugOptions = PythonDebugOptions.RedirectOutput; public bool WaitForExit = true; public bool ExpectHitOnMainThread = true; public bool IsBindFailureExpected = false; public string Arguments = ""; public string InterpreterOptions = null; public Action<PythonProcess> OnProcessLoaded; public BreakpointTest(BaseDebuggerTests tests, string runFileName) { _tests = tests; RunFileName = runFileName; } public void Run() { string runFileName = RunFileName; if (!Path.IsPathRooted(runFileName)) { runFileName = _tests.DebuggerTestPath + runFileName; } string breakFileName = BreakFileName; if (breakFileName != null && !Path.IsPathRooted(breakFileName)) { breakFileName = _tests.DebuggerTestPath + breakFileName; } foreach (var bp in Breakpoints) { var fileName = bp.FileName ?? breakFileName ?? runFileName; if (fileName.EndsWith(".py")) { Assert.IsTrue(bp is Breakpoint); } else { Assert.IsTrue(bp is DjangoBreakpoint); } } var bps = new Dictionary<PythonBreakpoint, BreakpointBase>(); var unboundBps = new HashSet<Breakpoint>(); var breakpointsToBeBound = Breakpoints.Count; var debugger = new PythonDebugger(); PythonThread thread = null; // Used to signal exceptions from debugger event handlers that run on a background thread. var backgroundException = new TaskCompletionSource<bool>(); var processLoaded = new TaskCompletionSource<bool>(); var process = _tests.DebugProcess( debugger, runFileName, cwd: WorkingDirectory, arguments: Arguments, resumeOnProcessLoaded: false, onLoaded: (newproc, newthread) => { try { foreach (var bp in Breakpoints) { var fileName = bp.FileName ?? breakFileName ?? runFileName; PythonBreakpoint breakpoint; var pyBP = bp as Breakpoint; if (pyBP != null) { breakpoint = newproc.AddBreakPoint(fileName, pyBP.LineNumber, pyBP.ConditionKind, pyBP.Condition, pyBP.PassCountKind, pyBP.PassCount); unboundBps.Add(pyBP); } else { var djangoBP = bp as DjangoBreakpoint; if (djangoBP != null) { breakpoint = newproc.AddDjangoBreakPoint(fileName, djangoBP.LineNumber); // Django breakpoints are never bound. --breakpointsToBeBound; } else { Assert.Fail("Unknown breakpoint type."); return; } } breakpoint.Add(); bps.Add(breakpoint, bp); } if (OnProcessLoaded != null) { OnProcessLoaded(newproc); } thread = newthread; processLoaded.SetResult(true); } catch (Exception ex) { backgroundException.TrySetException(ex); } }, interpreterOptions: InterpreterOptions ); int breakpointsBound = 0; int breakpointsNotBound = 0; int nextExpectedHit = 0; var allBreakpointsHit = new TaskCompletionSource<bool>(); var allBreakpointBindResults = new TaskCompletionSource<bool>(); if (breakpointsToBeBound == 0) { allBreakpointBindResults.SetResult(true); } try { process.BreakpointBindFailed += (sender, args) => { try { var bp = (Breakpoint)bps[args.Breakpoint]; if (bp != null && !(bp.IsBindFailureExpected ?? IsBindFailureExpected)) { Assert.Fail("Breakpoint at {0}:{1} failed to bind.", bp.FileName ?? breakFileName ?? runFileName, bp.LineNumber); } ++breakpointsNotBound; if (breakpointsBound + breakpointsNotBound == breakpointsToBeBound) { allBreakpointBindResults.SetResult(true); } } catch (Exception ex) { backgroundException.TrySetException(ex); } }; process.BreakpointBindSucceeded += (sender, args) => { try { var bp = (Breakpoint)bps[args.Breakpoint]; Assert.AreEqual(bp.FileName ?? breakFileName ?? runFileName, args.Breakpoint.Filename); Assert.IsTrue(unboundBps.Remove(bp)); ++breakpointsBound; if (breakpointsBound + breakpointsNotBound == breakpointsToBeBound) { allBreakpointBindResults.SetResult(true); } } catch (Exception ex) { backgroundException.TrySetException(ex); } }; process.BreakpointHit += (sender, args) => { try { if (nextExpectedHit < ExpectedHits.Count) { var bp = Breakpoints[ExpectedHits[nextExpectedHit]]; Trace.TraceInformation("Hit {0}:{1}", args.Breakpoint.Filename, args.Breakpoint.LineNo); Assert.AreSame(bp, bps[args.Breakpoint]); if (bp.RemoveWhenHit) { args.Breakpoint.Remove(); } if (bp.ExpectHitOnMainThread ?? ExpectHitOnMainThread) { Assert.AreSame(thread, args.Thread); } if (bp.OnHit != null) { bp.OnHit(args); } if (++nextExpectedHit == ExpectedHits.Count) { allBreakpointsHit.SetResult(true); } } process.Continue(); } catch (Exception ex) { backgroundException.TrySetException(ex); } }; process.Start(); Assert.IsTrue(WaitForAny(10000, processLoaded.Task, backgroundException.Task), "Timed out waiting for process load"); process.AutoResumeThread(thread.Id); if (breakpointsToBeBound > 0) { Assert.IsTrue(WaitForAny(10000, allBreakpointBindResults.Task, backgroundException.Task), "Timed out waiting for breakpoints to bind"); } } finally { if (WaitForExit) { _tests.WaitForExit(process); } else { Assert.IsTrue(WaitForAny(20000, allBreakpointsHit.Task, backgroundException.Task), "Timed out waiting for breakpoints to hit"); process.Terminate(); } } if (backgroundException.Task.IsFaulted) { backgroundException.Task.GetAwaiter().GetResult(); } Assert.AreEqual(ExpectedHits.Count, nextExpectedHit); Assert.IsTrue(unboundBps.All(bp => bp.IsBindFailureExpected ?? IsBindFailureExpected)); } private static bool WaitForAny(int timeout, params Task[] tasks) { try { Task.WhenAny(tasks.Concat(new[] { Task.Delay(Timeout.Infinite, new CancellationTokenSource(timeout).Token) })) .GetAwaiter().GetResult() // At this point we have the task that ran to completion first. Now we need to // get its result to get an exception if that task failed or got canceled. .GetAwaiter().GetResult(); return true; } catch (OperationCanceledException) { return false; } } } internal class LocalsTest { private readonly BaseDebuggerTests _tests; public readonly VariableCollection Locals = new VariableCollection(); public readonly VariableCollection Params = new VariableCollection(); public string FileName; public int LineNo; public string BreakFileName; public string Arguments; public Action ProcessLoaded; public PythonDebugOptions DebugOptions = PythonDebugOptions.RedirectOutput; public bool WaitForExit = true; public bool IgnoreExtra = false; public LocalsTest(BaseDebuggerTests tests, string fileName, int lineNo) { _tests = tests; FileName = fileName; LineNo = lineNo; } public void Run() { PythonThread thread = _tests.RunAndBreak(FileName, LineNo, breakFilename: BreakFileName, arguments: Arguments, processLoaded: ProcessLoaded, debugOptions: DebugOptions); PythonProcess process = thread.Process; try { var frames = thread.Frames; var localNamesExpected = Locals.Select(v => v.Expression).ToSet(); var paramNamesExpected = Params.Select(v => v.Expression).ToSet(); string fileNameExpected; if (BreakFileName == null) { fileNameExpected = Path.GetFullPath(_tests.DebuggerTestPath + FileName); } else if (Path.IsPathRooted(BreakFileName)) { fileNameExpected = BreakFileName; } else { fileNameExpected = Path.GetFullPath(_tests.DebuggerTestPath + BreakFileName); } Assert.AreEqual(frames[0].FileName, fileNameExpected, true); if (!IgnoreExtra) { AssertUtil.ContainsExactly(frames[0].Locals.Select(x => x.Expression), localNamesExpected); AssertUtil.ContainsExactly(frames[0].Parameters.Select(x => x.Expression), paramNamesExpected); } foreach (var expectedLocal in Locals) { var actualLocal = frames[0].Locals.First(v => v.Expression == expectedLocal.Expression); expectedLocal.Validate(actualLocal); } foreach (var expectedParam in Params) { var actualParam = frames[0].Parameters.First(v => v.Expression == expectedParam.Expression); expectedParam.Validate(actualParam); } process.Continue(); if (WaitForExit) { _tests.WaitForExit(process); } } finally { if (!process.HasExited) { process.Terminate(); } } } } internal PythonThread RunAndBreak(string filename, int lineNo, string breakFilename = null, string arguments = "", Action processLoaded = null, PythonDebugOptions debugOptions = PythonDebugOptions.RedirectOutput) { PythonThread thread; var debugger = new PythonDebugger(); thread = null; PythonProcess process = DebugProcess(debugger, DebuggerTestPath + filename, (newproc, newthread) => { var breakPoint = newproc.AddBreakPointByFileExtension(lineNo, breakFilename ?? filename); breakPoint.Add(); thread = newthread; if (processLoaded != null) { processLoaded(); } }, arguments: arguments, debugOptions: debugOptions); AutoResetEvent brkHit = new AutoResetEvent(false); process.BreakpointHit += (sender, args) => { thread = args.Thread; brkHit.Set(); }; bool ready = false; try { process.Start(); AssertWaited(brkHit); ready = true; } finally { if (!ready) { process.Terminate(); } } return thread; } internal static void AssertWaited(EventWaitHandle eventObj) { if (!eventObj.WaitOne(20000)) { Assert.Fail("Failed to wait on event"); } } internal virtual PythonVersion Version { get { return PythonPaths.Python26; } } internal enum StepKind { Into, Out, Over, Resume } internal class ExpectedStep { public readonly StepKind Kind; public readonly int StartLine; public ExpectedStep(StepKind kind, int startLine) { Kind = kind; StartLine = startLine; } } internal void StepTest(string filename, params ExpectedStep[] kinds) { StepTest(filename, new int[0], new Action<PythonProcess>[0], kinds); } internal void StepTest(string filename, int[] breakLines, Action<PythonProcess>[] breakAction, params ExpectedStep[] kinds) { StepTest(filename, null, null, breakLines, breakAction, null, PythonDebugOptions.RedirectOutput, true, kinds); } internal void StepTest(string filename, string breakFile, string arguments, int[] breakLines, Action<PythonProcess>[] breakAction, Action processLoaded, PythonDebugOptions options = PythonDebugOptions.RedirectOutput, bool waitForExit = true, params ExpectedStep[] kinds) { Console.WriteLine("--- Begin Step Test ---"); var debugger = new PythonDebugger(); if (breakFile == null) { breakFile = filename; } string fullPath = Path.GetFullPath(filename); string dir = Path.GetDirectoryName(filename); var process = debugger.CreateProcess(Version.Version, Version.InterpreterPath, "\"" + fullPath + "\" " + (arguments ?? ""), dir, "", null, options); try { PythonThread thread = null; process.ThreadCreated += (sender, args) => { thread = args.Thread; }; AutoResetEvent processEvent = new AutoResetEvent(false); bool processLoad = false, stepComplete = false; process.ProcessLoaded += (sender, args) => { foreach (var breakLine in breakLines) { var bp = process.AddBreakPointByFileExtension(breakLine, breakFile); bp.Add(); } processLoad = true; processEvent.Set(); if (processLoaded != null) { processLoaded(); } }; process.StepComplete += (sender, args) => { stepComplete = true; processEvent.Set(); }; int breakHits = 0; ExceptionDispatchInfo edi = null; process.BreakpointHit += (sender, args) => { try { Console.WriteLine("Breakpoint hit"); if (breakAction != null) { if (breakHits >= breakAction.Length) { Assert.Fail("Unexpected breakpoint hit at {0}:{1}", args.Breakpoint.Filename, args.Breakpoint.LineNo); } breakAction[breakHits++](process); } stepComplete = true; processEvent.Set(); } catch (Exception ex) { edi = ExceptionDispatchInfo.Capture(ex); try { processEvent.Set(); } catch { } } }; process.Start(); for (int curStep = 0; curStep < kinds.Length; curStep++) { Console.WriteLine("Step {0} {1}", curStep, kinds[curStep].Kind); // process the stepping events as they occur, we cannot callback during the // event because the notificaiton happens on the debugger thread and we // need to callback to get the frames. AssertWaited(processEvent); edi?.Throw(); // first time through we hit process load, each additional time we should hit step complete. Debug.Assert((processLoad == true && stepComplete == false && curStep == 0) || (stepComplete == true && processLoad == false && curStep != 0)); processLoad = stepComplete = false; var frames = thread.Frames; var stepInfo = kinds[curStep]; Assert.AreEqual(stepInfo.StartLine, frames[0].LineNo, String.Format("{0} != {1} on {2} step", stepInfo.StartLine, frames[0].LineNo, curStep)); switch (stepInfo.Kind) { case StepKind.Into: thread.StepInto(); break; case StepKind.Out: thread.StepOut(); break; case StepKind.Over: thread.StepOver(); break; case StepKind.Resume: process.Resume(); break; } } if (waitForExit) { WaitForExit(process); } } finally { process.Terminate(); } } internal void WaitForExit(PythonProcess process, bool assert = true) { bool exited = process.WaitForExit(DefaultWaitForExitTimeout); if (!exited) { process.Terminate(); if (assert) { Assert.Fail("Timeout while waiting for Python process to exit."); } } } internal void StartAndWaitForExit(PythonProcess process) { bool exited = false; try { process.Start(); exited = process.WaitForExit(DefaultWaitForExitTimeout); } finally { if (!exited && !process.HasExited) { process.Terminate(); Assert.Fail("Timeout while waiting for Python process to exit."); } } } internal void DetachProcess(PythonProcess p) { try { p.Detach(); } catch (Exception ex) { Console.WriteLine("Failed to detach process"); Console.WriteLine(ex); } } internal void TerminateProcess(PythonProcess p) { try { p.Terminate(); } catch (Exception ex) { Console.WriteLine("Failed to detach process"); Console.WriteLine(ex); } } internal void DisposeProcess(Process p) { try { if (!p.HasExited) { p.Kill(); } if (p.StartInfo.RedirectStandardOutput) { ForEachLine(p.StandardOutput, s => Trace.TraceInformation("STDOUT: {0}", s)); } if (p.StartInfo.RedirectStandardError) { ForEachLine(p.StandardError, s => Trace.TraceWarning("STDERR: {0}", s)); } } catch (Exception ex) { Console.WriteLine("Failed to kill process"); Console.WriteLine(ex); } p.Dispose(); } internal object DebugProcess(PythonDebugger debugger, string runFileName, string cwd, string arguments, bool resumeOnProcessLoaded, object onLoaded, string interpreterOptions) { throw new NotImplementedException(); } } }
using IrcClientCore; using OpenGraph_Net; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel.DataTransfer; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; using WinIRC.Net; using WinIRC.Views; using WinIRC.Views.InlineViewers; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 namespace WinIRC.Ui { public sealed partial class MessageLine : UserControl, INotifyPropertyChanged { public static readonly DependencyProperty MessageProperty = DependencyProperty.Register( "MessageItem", typeof(MessageGroup), typeof(MessageLine), new PropertyMetadata(null)); public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public string Username { get { if (MessageItem == null) return ""; var user = MessageItem.Parent.User ?? ""; if (user.Contains("*")) { return "*"; } if (MessageItem.Parent.Type == MessageType.Normal) { return String.Format("{0}", user); } else if (MessageItem.Parent.Type == MessageType.Notice) { return String.Format("->{0}<-", user); } else { return String.Format("* {0}", user); } } } public bool HasLoaded { get; private set; } public MessageGroup MessageItem { get { return (MessageGroup)GetValue(MessageProperty); } set { SetValue(MessageProperty, value); NotifyPropertyChanged("MessageItem"); NotifyPropertyChanged("Username"); NotifyPropertyChanged("UserColor"); NotifyPropertyChanged("UserColorBrush"); NotifyPropertyChanged("MessageColor"); NotifyPropertyChanged("TextIndent"); NotifyPropertyChanged("NormalMessage"); UpdateUi(); } } public Color MentionRed => ThemeColor(Colors.Red); public bool NormalMessage { get { return MessageItem.Parent.Type != MessageType.JoinPart; } } public SolidColorBrush UserColorBrush { get { if (MessageItem == null) return null; return new SolidColorBrush(UserColor); } } public Color UserColor { get { if (MessageItem == null) return Colors.White; var color = ThemeColor(ColorUtils.GenerateColor(MessageItem.Parent.User)); if (MessageItem.Parent.Mention) { return MentionRed; } return color; } } public SolidColorBrush MessageColor { get { if (MessageItem == null) return null; if (MessageItem.Parent.Mention) { return new SolidColorBrush(MentionRed); } Color defaultColor = Config.GetBoolean(Config.DarkTheme, true) ? Colors.White : Colors.Black; return new SolidColorBrush(defaultColor); } } public MessageLine() : this(null) { } private Color ThemeColor(Color color) { if (Config.GetBoolean(Config.DarkTheme, true)) { color = ColorUtils.ChangeColorBrightness(color, 0.2f); } else { color = ColorUtils.ChangeColorBrightness(color, -0.4f); } return color; } public MessageLine(MessageGroup line) { this.InitializeComponent(); this.MessageItem = line; Unloaded += MessageLine_Unloaded; Loaded += MessageLine_Loaded; MainPage.instance.UiUpdated += Instance_UiUpdated; } private void Instance_UiUpdated(object sender, EventArgs e) { UpdateUi(); NotifyPropertyChanged("UserColor"); NotifyPropertyChanged("MessageColor"); } private void MessageLine_Loaded(object sender, RoutedEventArgs e) { UpdateUi(); } public void UpdateUi() { if (double.IsNaN(UsernameBox.ActualWidth) || double.IsNaN(TimestampBox.ActualWidth)) return; if (MessageItem != null) { if (MessageItem.Parent.Type == MessageType.Info || MessageItem.Parent.Type == MessageType.JoinPart) { UsernameBox.Style = (Style)Application.Current.Resources["InfoTextBlockStyle"]; } else if (MessageItem.Parent.Type == MessageType.Action) { UsernameBox.FontStyle = Windows.UI.Text.FontStyle.Italic; } if (MessageItem.Parent.Mention) { UsernameBox.Foreground = new SolidColorBrush(Colors.Red); } if (MessageItem.Parent.Type == MessageType.MOTD) { this.FontFamily = new FontFamily("Consolas"); } } this.HasLoaded = true; UpdateLayout(); } private void MessageLine_Unloaded(object sender, RoutedEventArgs e) { MainPage.instance.UiUpdated -= Instance_UiUpdated; UpdateLayout(); } } }
// Transport Security Layer (TLS) // Copyright (c) 2003-2004 Carlos Guzman Alvarez // Copyright (C) 2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; namespace Mono.Security.Protocol.Tls { internal class TlsStream : Stream { #region Fields private bool canRead; private bool canWrite; private MemoryStream buffer; private byte[] temp; private const int temp_size = 4; #endregion #region Properties public bool EOF { get { if (this.Position < this.Length) { return false; } else { return true; } } } #endregion #region Stream Properties public override bool CanWrite { get { return this.canWrite; } } public override bool CanRead { get { return this.canRead; } } public override bool CanSeek { get { return this.buffer.CanSeek; } } public override long Position { get { return this.buffer.Position; } set { this.buffer.Position = value; } } public override long Length { get { return this.buffer.Length; } } #endregion #region Constructors public TlsStream() : base() { this.buffer = new MemoryStream(0); this.canRead = false; this.canWrite = true; } public TlsStream(byte[] data) : base() { if (data != null) this.buffer = new MemoryStream(data); else this.buffer = new MemoryStream (); this.canRead = true; this.canWrite = false; } #endregion #region Specific Read Methods // hack for reducing memory allocations // returned value is valid only for the length asked *and* // cannot be directly returned outside the class // note: Mono's Stream.ReadByte does a 1 byte array allocation private byte[] ReadSmallValue (int length) { if (length > temp_size) throw new ArgumentException ("8 bytes maximum"); if (temp == null) temp = new byte[temp_size]; if (this.Read (temp, 0, length) != length) throw new TlsException (String.Format ("buffer underrun")); return temp; } public new byte ReadByte() { byte[] result = ReadSmallValue (1); return result [0]; } public short ReadInt16() { byte[] result = ReadSmallValue (2); return (short) (result[0] << 8 | result[1]); } public int ReadInt24() { byte[] result = ReadSmallValue (3); return ((result[0] << 16) | (result[1] << 8) | result[2]); } public int ReadInt32() { byte[] result = ReadSmallValue (4); return ((result[0] << 24) | (result[1] << 16) | (result[2] << 8) | result[3]); } public byte[] ReadBytes(int count) { byte[] bytes = new byte[count]; if (this.Read(bytes, 0, count) != count) throw new TlsException ("buffer underrun"); return bytes; } #endregion #region Specific Write Methods // note: Mono's Stream.WriteByte does a 1 byte array allocation public void Write(byte value) { if (temp == null) temp = new byte[temp_size]; temp[0] = value; this.Write (temp, 0, 1); } public void Write(short value) { if (temp == null) temp = new byte[temp_size]; temp[0] = ((byte)(value >> 8)); temp[1] = ((byte)value); this.Write (temp, 0, 2); } public void WriteInt24(int value) { if (temp == null) temp = new byte[temp_size]; temp[0] = ((byte)(value >> 16)); temp[1] = ((byte)(value >> 8)); temp[2] = ((byte)value); this.Write (temp, 0, 3); } public void Write(int value) { if (temp == null) temp = new byte[temp_size]; temp[0] = ((byte)(value >> 24)); temp[1] = ((byte)(value >> 16)); temp[2] = ((byte)(value >> 8)); temp[3] = ((byte)value); this.Write (temp, 0, 4); } public void Write(ulong value) { Write ((int)(value >> 32)); Write ((int)value); } public void Write(byte[] buffer) { this.Write(buffer, 0, buffer.Length); } #endregion #region Methods public void Reset() { this.buffer.SetLength(0); this.buffer.Position = 0; } public byte[] ToArray() { return this.buffer.ToArray(); } #endregion #region Stream Methods public override void Flush() { this.buffer.Flush(); } public override void SetLength(long length) { this.buffer.SetLength(length); } public override long Seek(long offset, System.IO.SeekOrigin loc) { return this.buffer.Seek(offset, loc); } public override int Read(byte[] buffer, int offset, int count) { if (this.canRead) { return this.buffer.Read(buffer, offset, count); } throw new InvalidOperationException("Read operations are not allowed by this stream"); } public override void Write(byte[] buffer, int offset, int count) { if (this.canWrite) { this.buffer.Write(buffer, offset, count); } else { throw new InvalidOperationException("Write operations are not allowed by this stream"); } } #endregion } }
/* * Copyright 2006-2015 TIBIC SOLUTIONS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Data; using LWAS.Extensible.Exceptions; using LWAS.Extensible.Interfaces; using LWAS.Extensible.Interfaces.Configuration; using LWAS.Extensible.Interfaces.Expressions; using LWAS.Extensible.Interfaces.Monitoring; using LWAS.Extensible.Interfaces.Translation; using LWAS.Extensible.Interfaces.WebParts; using LWAS.Infrastructure; using LWAS.CustomControls; using LWAS.CustomControls.DataControls; using LWAS.CustomControls.DataControls.Events; namespace LWAS.WebParts { public class ContainerWebPart : BindableWebPart, IContainerWebPart, IConfigurableWebPart, IBindableWebPart, IInitializable, ILifetime, ITemplatable, IReporter { Container _container; public Container Container { get { return _container; } } public IConfigurationType TemplateConfig { get { return _container.TemplateConfig; } set { _container.TemplateConfig = value; } } public override IDataSource DataSource { get { return base.DataSource; } set { base.DataSource = value; _container.DataSource = base.DataSource; this.OnMilestone("source"); } } public ITemplatingItemsCollection Items { get { return _container.Items; } set { _container.Items = value; } } public string Filter { set { _container.Filter = value; } } public ITemplatingItemsCollection FilterItems { get { return _container.FilterItems; } set { _container.FilterItems = value; } } public ITemplatingItem CurrentItem { get { return _container.CurrentItem; } } public ITemplatingItem ContextItem { get { return _container.ContextItem; } } public object Data { get { return _container.Data; } } public string Command { get { return _container.Command; } set { _container.Command = value; } } public Dictionary<string, List<Container.CheckDefinition>> Checks { get { return _container.Checks; } set { _container.Checks = value; } } public Dictionary<string, Control> Commanders { get { return _container.Commanders; } set { _container.Commanders = value; } } public Dictionary<string, Control> Selectors { get { return _container.Selectors; } set { _container.Selectors = value; } } public Dictionary<string, object> DataSources { get { return _container.DataSources; } } public bool DisablePaginater { get { return _container.DisablePaginater; } set { _container.DisablePaginater = value; } } public bool DisableFilters { get { return _container.DisableFilters; } set { _container.DisableFilters = value; } } public TableStyle SelectorsStyle { get; set; } public TableStyle CommandersStyle { get; set; } public TableStyle FilterStyle { get; set; } public TableStyle HeaderStyle { get; set; } public TableStyle GroupingStyle { get; set; } public TableStyle TotalsStyle { get; set; } public TableStyle DetailsStyle { get; set; } public TableStyle FooterStyle { get; set; } public TableItemStyle SelectorsRowStyle { get; set; } public TableItemStyle CommandersRowStyle { get; set; } public TableItemStyle FilterRowStyle { get; set; } public TableItemStyle HeaderRowStyle { get; set; } public TableItemStyle GroupRowStyle { get; set; } public TableItemStyle TotalsRowStyle { get; set; } public TableItemStyle RowStyle { get; set; } public TableItemStyle EditRowStyle { get; set; } public TableItemStyle SelectedRowStyle { get; set; } public TableItemStyle AlternatingRowStyle { get; set; } public TableItemStyle FooterRowStyle { get; set; } public TableItemStyle InvalidItemStyle { get; set; } public TableItemStyle MessageStyle { get { return _container.MessageStyle; } set { _container.MessageStyle = value; } } public IMonitor Monitor { get { return _container.Monitor; } set { _container.Monitor = value; } } public string GroupByMember { get { return _container.GroupByMember; } set { _container.GroupByMember = value; } } public string TotalsByMembers { get { return _container.TotalsByMembers; } set { _container.TotalsByMembers = value; } } public IEnumerable ReceiveData { set { _container.ReceiveData = value; } } public IEnumerable RawData { get { return _container.RawData; } set { _container.RawData = value; } } public DataSet FilteredData { get { return _container.FilteredData; } } public ITemplatingProvider Template { get { return _container.Template; } set { _container.Template = value; } } public bool PassLastCheck { get { return _container.PassLastCheck; } set { _container.PassLastCheck = value; } } public ContainerWebPart() { this.ExportMode = WebPartExportMode.All; _container = InstantiateContainer(); } protected override void OnInit(EventArgs e) { base.OnInit(e); _container.ID = "container"; this.Controls.Add(_container); _container.Recover += new EventHandler<RecoverEventArgs>(_container_Recover); _container.RequestData += new EventHandler(_container_RequestData); _container.Milestone += new EventHandler<MilestoneEventArgs>(_container_Milestone); _container.Insert += new EventHandler<InsertEventArgs>(_container_Insert); _container.Update += new EventHandler<UpdateEventArgs>(_container_Update); _container.Delete += new EventHandler<DeleteEventArgs>(_container_Delete); } protected virtual Container InstantiateContainer() { return new Container(); } void _container_Recover(object sender, RecoverEventArgs e) { if (!this.IsInitialized) { if (null == base.RequestInitialization) { e.Cancel = true; return; } base.RequestInitialization(this); } } void _container_RequestData(object sender, EventArgs e) { OnRequestData(); } void _container_Milestone(object sender, MilestoneEventArgs e) { OnMilestone(e.Key); } void _container_Insert(object sender, InsertEventArgs e) { base.Insert(e.Data); } void _container_Update(object sender, UpdateEventArgs e) { base.Update(null, e.Data, null); } void _container_Delete(object sender, DeleteEventArgs e) { base.Delete(e.Data, null); } protected override bool OnBubbleEvent(object source, EventArgs args) { return _container.ParentEvent(source, args); } protected virtual void OnRequestData() { try { base.Select(DataSourceSelectArguments.Empty); } catch (Exception ex) { _container.Monitor.Register(this, _container.Monitor.NewEventInstance("request data error", null, ex, EVENT_TYPE.Error)); } } protected override void DataSourceSelectCallback(IEnumerable data) { _container.ReceiveData = data; base.DataSourceSelectCallback(data); } protected override void OnChange() { _container.PerformOperation(); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); _container.CompleteWithData(); } public override void Initialize() { if (null == this.Configuration) throw new MissingProviderException("Configuration"); if (null == this.ConfigurationParser) throw new MissingProviderException("Configuration parser"); if (null == this.Binder) throw new MissingProviderException("Binder"); if (null == this.Template) throw new MissingProviderException("Templating"); if (null == base.ValidationManager)throw new MissingProviderException("ValidationManager"); if (null == base.ExpressionsManager)throw new MissingProviderException("ExpressionsManager"); if (null == this.Items)throw new InitializationException("Items collection not set"); if (null == this.FilterItems)throw new InitializationException("FilterItems collection not set"); if (null == this.Monitor)throw new MissingProviderException("Monitor"); _container.InitEx(); base.TranslationTargets.Clear(); base.TranslationTargets.Add("_message", _container.Message); this.ConfigurationParser.Parse(this); base.Initialize(); _container.InitProviders(this.Binder, this.ValidationManager, this, this, this.Translator); _container.Rebuild(); } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Description { using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime; using System.ServiceModel.Channels; using System.Xml; public abstract partial class MetadataImporter { //Consider, [....]: make this public internal static IEnumerable<PolicyConversionContext> GetPolicyConversionContextEnumerator(ServiceEndpoint endpoint, PolicyAlternatives policyAlternatives) { return ImportedPolicyConversionContext.GetPolicyConversionContextEnumerator(endpoint, policyAlternatives, MetadataImporterQuotas.Defaults); } internal static IEnumerable<PolicyConversionContext> GetPolicyConversionContextEnumerator(ServiceEndpoint endpoint, PolicyAlternatives policyAlternatives, MetadataImporterQuotas quotas) { return ImportedPolicyConversionContext.GetPolicyConversionContextEnumerator(endpoint, policyAlternatives, quotas); } internal sealed class ImportedPolicyConversionContext : PolicyConversionContext { BindingElementCollection bindingElements = new BindingElementCollection(); readonly PolicyAssertionCollection endpointAssertions; readonly Dictionary<OperationDescription, PolicyAssertionCollection> operationBindingAssertions = new Dictionary<OperationDescription, PolicyAssertionCollection>(); readonly Dictionary<MessageDescription, PolicyAssertionCollection> messageBindingAssertions = new Dictionary<MessageDescription, PolicyAssertionCollection>(); readonly Dictionary<FaultDescription, PolicyAssertionCollection> faultBindingAssertions = new Dictionary<FaultDescription, PolicyAssertionCollection>(); ImportedPolicyConversionContext(ServiceEndpoint endpoint, IEnumerable<XmlElement> endpointAssertions, Dictionary<OperationDescription, IEnumerable<XmlElement>> operationBindingAssertions, Dictionary<MessageDescription, IEnumerable<XmlElement>> messageBindingAssertions, Dictionary<FaultDescription, IEnumerable<XmlElement>> faultBindingAssertions, MetadataImporterQuotas quotas) : base(endpoint) { int remainingAssertionsAllowed = quotas.MaxPolicyAssertions; this.endpointAssertions = new PolicyAssertionCollection(new MaxItemsEnumerable<XmlElement>(endpointAssertions, remainingAssertionsAllowed)); remainingAssertionsAllowed -= this.endpointAssertions.Count; foreach (OperationDescription operationDescription in endpoint.Contract.Operations) { this.operationBindingAssertions.Add(operationDescription, new PolicyAssertionCollection()); foreach (MessageDescription messageDescription in operationDescription.Messages) { this.messageBindingAssertions.Add(messageDescription, new PolicyAssertionCollection()); } foreach (FaultDescription faultDescription in operationDescription.Faults) { this.faultBindingAssertions.Add(faultDescription, new PolicyAssertionCollection()); } } foreach (KeyValuePair<OperationDescription, IEnumerable<XmlElement>> entry in operationBindingAssertions) { this.operationBindingAssertions[entry.Key].AddRange(new MaxItemsEnumerable<XmlElement>(entry.Value, remainingAssertionsAllowed)); remainingAssertionsAllowed -= this.operationBindingAssertions[entry.Key].Count; } foreach (KeyValuePair<MessageDescription, IEnumerable<XmlElement>> entry in messageBindingAssertions) { this.messageBindingAssertions[entry.Key].AddRange(new MaxItemsEnumerable<XmlElement>(entry.Value, remainingAssertionsAllowed)); remainingAssertionsAllowed -= this.messageBindingAssertions[entry.Key].Count; } foreach (KeyValuePair<FaultDescription, IEnumerable<XmlElement>> entry in faultBindingAssertions) { this.faultBindingAssertions[entry.Key].AddRange(new MaxItemsEnumerable<XmlElement>(entry.Value, remainingAssertionsAllowed)); remainingAssertionsAllowed -= this.faultBindingAssertions[entry.Key].Count; } } // // PolicyConversionContext implementation // public override BindingElementCollection BindingElements { get { return this.bindingElements; } } public override PolicyAssertionCollection GetBindingAssertions() { return this.endpointAssertions; } public override PolicyAssertionCollection GetOperationBindingAssertions(OperationDescription operation) { return this.operationBindingAssertions[operation]; } public override PolicyAssertionCollection GetMessageBindingAssertions(MessageDescription message) { return this.messageBindingAssertions[message]; } public override PolicyAssertionCollection GetFaultBindingAssertions(FaultDescription message) { return this.faultBindingAssertions[message]; } // // Policy Alternative Enumeration code // public static IEnumerable<PolicyConversionContext> GetPolicyConversionContextEnumerator(ServiceEndpoint endpoint, PolicyAlternatives policyAlternatives, MetadataImporterQuotas quotas) { IEnumerable<Dictionary<MessageDescription, IEnumerable<XmlElement>>> messageAssertionEnumerator; IEnumerable<Dictionary<FaultDescription, IEnumerable<XmlElement>>> faultAssertionEnumerator; IEnumerable<Dictionary<OperationDescription, IEnumerable<XmlElement>>> operationAssertionEnumerator; faultAssertionEnumerator = PolicyIterationHelper.GetCartesianProduct<FaultDescription, IEnumerable<XmlElement>>(policyAlternatives.FaultBindingAlternatives); messageAssertionEnumerator = PolicyIterationHelper.GetCartesianProduct<MessageDescription, IEnumerable<XmlElement>>(policyAlternatives.MessageBindingAlternatives); operationAssertionEnumerator = PolicyIterationHelper.GetCartesianProduct<OperationDescription, IEnumerable<XmlElement>>(policyAlternatives.OperationBindingAlternatives); foreach (Dictionary<FaultDescription, IEnumerable<XmlElement>> faultAssertionsSelection in faultAssertionEnumerator) { foreach (Dictionary<MessageDescription, IEnumerable<XmlElement>> messageAssertionsSelection in messageAssertionEnumerator) { foreach (Dictionary<OperationDescription, IEnumerable<XmlElement>> operationAssertionsSelection in operationAssertionEnumerator) { foreach (IEnumerable<XmlElement> endpointAssertionsSelection in policyAlternatives.EndpointAlternatives) { ImportedPolicyConversionContext conversionContext; try { conversionContext = new ImportedPolicyConversionContext(endpoint, endpointAssertionsSelection, operationAssertionsSelection, messageAssertionsSelection, faultAssertionsSelection, quotas); } catch (MaxItemsEnumeratorExceededMaxItemsException) { yield break; } yield return conversionContext; } } } } } internal class MaxItemsEnumerable<T> : IEnumerable<T> { IEnumerable<T> inner; int maxItems; public MaxItemsEnumerable(IEnumerable<T> inner, int maxItems) { this.inner = inner; this.maxItems = maxItems; } public IEnumerator<T> GetEnumerator() { return new MaxItemsEnumerator<T>(inner.GetEnumerator(), maxItems); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } } internal class MaxItemsEnumerator<T> : IEnumerator<T> { int maxItems; int currentItem; IEnumerator<T> inner; public MaxItemsEnumerator(IEnumerator<T> inner, int maxItems) { this.maxItems = maxItems; this.currentItem = 0; this.inner = inner; } public T Current { get { return inner.Current; } } public void Dispose() { inner.Dispose(); } object IEnumerator.Current { get { return ((IEnumerator)inner).Current; } } public bool MoveNext() { bool moveNext = inner.MoveNext(); if (++currentItem > maxItems) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MaxItemsEnumeratorExceededMaxItemsException()); } return moveNext; } public void Reset() { currentItem = 0; inner.Reset(); } } internal class MaxItemsEnumeratorExceededMaxItemsException : Exception { } static class PolicyIterationHelper { // This method returns an iterator over the cartesian product of a colleciton of sets. // e.g. If the following 3 sets are provided: // i) { 1, 2, 3 } // ii) { a, b } // iii) { x, y, z } // // You would get an enumerator that returned the following 18 collections: // { 1, a, x}, { 2, a, x}, { 3, a, x}, { 1, b, x}, { 2, b, x}, { 3, b, x}, // { 1, a, y}, { 2, a, y}, { 3, a, y}, { 1, b, y}, { 2, b, y}, { 3, b, y}, // { 1, a, z}, { 2, a, z}, { 3, a, z}, { 1, b, z}, { 2, b, z}, { 3, b, z} // // This method allows us to enumerate over all the possible policy selections in a // dictiaonary of policy alternatives. // e.g. given all the policy alternatives in all the messages in a contract, // we can enumerate over all the possilbe policy selections. // // Note: A general implementation of this method would differ in that it would probably use a List<T> or an array instead of // a dictionary and it would yield clones of the the counterValue. // - We don't clone because we know that we don't need to based on our useage // - We use a dictionary because we need to correlate the selections with the alternative source. // internal static IEnumerable<Dictionary<K, V>> GetCartesianProduct<K, V>(Dictionary<K, IEnumerable<V>> sets) { Dictionary<K, V> counterValue = new Dictionary<K, V>(sets.Count); // The iterator is implemented as a counter with each digit being an IEnumerator over one of the sets. KeyValuePair<K, IEnumerator<V>>[] digits = InitializeCounter<K, V>(sets, counterValue); do { yield return (Dictionary<K, V>)counterValue; } while (IncrementCounter<K, V>(digits, sets, counterValue)); } static KeyValuePair<K, IEnumerator<V>>[] InitializeCounter<K, V>(Dictionary<K, IEnumerable<V>> sets, Dictionary<K, V> counterValue) { KeyValuePair<K, IEnumerator<V>>[] digits = new KeyValuePair<K, IEnumerator<V>>[sets.Count]; // Initialize the digit enumerators and set the counter's current Value. int i = 0; foreach (KeyValuePair<K, IEnumerable<V>> kvp in sets) { digits[i] = new KeyValuePair<K, IEnumerator<V>>(kvp.Key, kvp.Value.GetEnumerator()); if (!(digits[i].Value.MoveNext())) { Fx.Assert("each set must have at least one item in it"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Each set must have at least one item in it"))); } counterValue[digits[i].Key] = digits[i].Value.Current; i++; } return digits; } static bool IncrementCounter<K, V>(KeyValuePair<K, IEnumerator<V>>[] digits, Dictionary<K, IEnumerable<V>> sets, Dictionary<K, V> counterValue) { // // Do rollover and carryying for digits. // - starting at least significant digit, move digits to next value. // if digit rolls over, carry to next digit and repeat. // int currentDigit; for (currentDigit = 0; currentDigit < digits.Length && !digits[currentDigit].Value.MoveNext(); currentDigit++) { IEnumerator<V> newDigit = sets[digits[currentDigit].Key].GetEnumerator(); digits[currentDigit] = new KeyValuePair<K, IEnumerator<V>>(digits[currentDigit].Key, newDigit); digits[currentDigit].Value.MoveNext(); } // // if we just rolled over on the most significant digit, return false // if (currentDigit == digits.Length) return false; // // update countervalue stores for all digits that changed. // for (int i = currentDigit; i >= 0; i--) { counterValue[digits[i].Key] = digits[i].Value.Current; } return true; } } } internal class PolicyAlternatives { public IEnumerable<IEnumerable<XmlElement>> EndpointAlternatives; public Dictionary<OperationDescription, IEnumerable<IEnumerable<XmlElement>>> OperationBindingAlternatives; public Dictionary<MessageDescription, IEnumerable<IEnumerable<XmlElement>>> MessageBindingAlternatives; public Dictionary<FaultDescription, IEnumerable<IEnumerable<XmlElement>>> FaultBindingAlternatives; } } }
/* * PROPRIETARY INFORMATION. This software is proprietary to * Side Effects Software Inc., and is not to be reproduced, * transmitted, or disclosed in any way without written permission. * * Produced by: * Side Effects Software Inc * 123 Front Street West, Suite 1401 * Toronto, Ontario * Canada M5J 2M2 * 416-504-9876 * * COMMENTS: * Continuation of HAPI_Host class definition. Here we include all libdll dll imports. * */ // Master control for enabling runtime. #if ( UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_STANDALONE_LINUX || ( UNITY_METRO && UNITY_EDITOR ) ) #define HAPI_ENABLE_RUNTIME #endif using UnityEngine; using System.Collections; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; // Typedefs (copy these from HAPI_Common.cs) using HAPI_StringHandle = System.Int32; using HAPI_AssetLibraryId = System.Int32; using HAPI_AssetId = System.Int32; using HAPI_NodeId = System.Int32; using HAPI_ParmId = System.Int32; using HAPI_ObjectId = System.Int32; using HAPI_GeoId = System.Int32; using HAPI_PartId = System.Int32; using HAPI_MaterialId = System.Int32; /// <summary> /// Singleton Houdini host object that maintains the singleton Houdini scene and all access to the /// Houdini runtime. /// </summary> public static partial class HoudiniHost { #if ( HAPI_ENABLE_RUNTIME ) // SESSIONS ------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CreateInProcessSession( out HAPI_Session session ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_StartThriftSocketServer( bool auto_close, int port, float timeout_ms, out int process_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CreateThriftSocketSession( out HAPI_Session session, string host_name, int port ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_StartThriftNamedPipeServer( bool auto_close, string pipe_name, float timeout_ms, out int process_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CreateThriftNamedPipeSession( out HAPI_Session session, string pipe_name ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_BindCustomImplementation( HAPI_SessionType session_type, string dll_path ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CreateCustomSession( HAPI_SessionType session_type, byte[] session_info, out HAPI_Session session ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_IsSessionValid( ref HAPI_Session session ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CloseSession( ref HAPI_Session session ); // INITIALIZATION / CLEANUP --------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_IsInitialized( ref HAPI_Session session ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_Initialize( ref HAPI_Session session, ref HAPI_CookOptions cook_options, [ MarshalAs( UnmanagedType.U1 ) ] bool use_cooking_thread, int cooking_thread_stack_size, string otl_search_path, string dso_search_path, string image_dso_search_path, string audio_dso_search_path ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_Cleanup( ref HAPI_Session session ); // DIAGNOSTICS ---------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetEnvInt( HAPI_EnvIntType int_type, out int value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetSessionEnvInt( ref HAPI_Session session, HAPI_SessionEnvIntType int_type, out int value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetServerEnvInt( ref HAPI_Session session, string variable_name, out int value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetServerEnvString( ref HAPI_Session session, string variable_name, out HAPI_StringHandle value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetServerEnvInt( ref HAPI_Session session, string variable_name, int value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetServerEnvString( ref HAPI_Session session, string variable_name, string value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetStatus( ref HAPI_Session session, HAPI_StatusType status_code, out int status ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetStatusStringBufLength( ref HAPI_Session session, HAPI_StatusType status_code, HAPI_StatusVerbosity verbosity, out int buffer_size ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetStatusString( ref HAPI_Session session, HAPI_StatusType status_type, StringBuilder string_value, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetCookingTotalCount( ref HAPI_Session session, out int count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetCookingCurrentCount( ref HAPI_Session session, out int count ); // UTILITY -------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ConvertTransform( ref HAPI_Session session, ref HAPI_TransformEuler transform_in, HAPI_RSTOrder rst_order, HAPI_XYZOrder rot_order, out HAPI_TransformEuler transform_out ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ConvertMatrixToQuat( ref HAPI_Session session, float[] matrix, HAPI_RSTOrder rst_order, ref HAPI_Transform transform_out ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ConvertMatrixToEuler( ref HAPI_Session session, float[] matrix, HAPI_RSTOrder rst_order, HAPI_XYZOrder rot_order, ref HAPI_TransformEuler transform_out ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ConvertTransformQuatToMatrix( ref HAPI_Session session, ref HAPI_Transform transform, [Out] float[] matrix ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ConvertTransformEulerToMatrix( ref HAPI_Session session, ref HAPI_TransformEuler transform, [Out] float[] matrix ); // STRINGS -------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetStringBufLength( ref HAPI_Session session, HAPI_StringHandle string_handle, out int buffer_length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetString( ref HAPI_Session session, HAPI_StringHandle string_handle, StringBuilder string_value, int length ); // TIME ----------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetTime( ref HAPI_Session session, out float time ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetTime( ref HAPI_Session session, float time ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetTimelineOptions( ref HAPI_Session session, ref HAPI_TimelineOptions timeline_options ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetTimelineOptions( ref HAPI_Session session, ref HAPI_TimelineOptions timeline_options ); // ASSETS --------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_IsAssetValid( ref HAPI_Session session, HAPI_AssetId asset_id, int asset_validation_id, out int answer ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_LoadAssetLibraryFromFile( ref HAPI_Session session, string file_path, [ MarshalAs( UnmanagedType.U1 ) ] bool allow_overwrite, out HAPI_AssetLibraryId library_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_LoadAssetLibraryFromMemory( ref HAPI_Session session, byte[] library_buffer, int library_buffer_length, [ MarshalAs( UnmanagedType.U1 ) ] bool allow_overwrite, out HAPI_AssetLibraryId library_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetAvailableAssetCount( ref HAPI_Session session, HAPI_AssetLibraryId library_id, out int asset_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetAvailableAssets( ref HAPI_Session session, HAPI_AssetLibraryId library_id, [Out] HAPI_StringHandle[] asset_names_array, int asset_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_InstantiateAsset( ref HAPI_Session session, string asset_name, [ MarshalAs( UnmanagedType.U1 ) ] bool cook_on_load, out HAPI_AssetId asset_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CreateCurve( ref HAPI_Session session, out HAPI_AssetId asset_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CreateInputAsset( ref HAPI_Session session, out HAPI_AssetId asset_id, string name ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_DestroyAsset( ref HAPI_Session session, HAPI_AssetId asset_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetAssetInfo( ref HAPI_Session session, HAPI_AssetId asset_id, ref HAPI_AssetInfo asset_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CookAsset( ref HAPI_Session session, HAPI_AssetId asset_id, ref HAPI_CookOptions cook_options ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CookAsset( ref HAPI_Session session, HAPI_AssetId asset_id, System.IntPtr cook_options ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_Interrupt( ref HAPI_Session session ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetAssetTransform( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_RSTOrder rst_order, HAPI_XYZOrder rot_order, out HAPI_TransformEuler transform ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetAssetTransform( ref HAPI_Session session, HAPI_AssetId asset_id, ref HAPI_TransformEuler transform ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetInputName( ref HAPI_Session session, HAPI_AssetId asset_id, int input_idx, int input_type, out HAPI_StringHandle name ); // HIP FILES ------------------------------------------------------------------------------------------------ [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_LoadHIPFile( ref HAPI_Session session, string file_name, [ MarshalAs( UnmanagedType.U1 ) ] bool cook_on_load ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CheckForNewAssets( ref HAPI_Session session, ref int asset_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetNewAssetIds( ref HAPI_Session session, [Out] HAPI_AssetId[] asset_ids_array, int new_asset_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SaveHIPFile( ref HAPI_Session session, string file_name, [ MarshalAs( UnmanagedType.U1 ) ] bool lock_nodes ); // NODES ---------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetNodeInfo( ref HAPI_Session session, HAPI_NodeId node_id, ref HAPI_NodeInfo node_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetEditableNodeNetworks( ref HAPI_Session session, HAPI_AssetId asset_id, [Out] HAPI_NodeId[] node_networks_array, int count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetNodeNetworkChildren( ref HAPI_Session session, HAPI_NodeId network_node_id, [Out] HAPI_NodeId[] child_node_ids_array, int count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CreateNode( ref HAPI_Session session, HAPI_NodeId parent_node_id, string operator_name, out HAPI_NodeId new_node_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_DeleteNode( ref HAPI_Session session, HAPI_NodeId node_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_RenameNode( ref HAPI_Session session, HAPI_NodeId node_id, string new_name ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ConnectNodeInput( ref HAPI_Session session, HAPI_NodeId node_id, int input_index, HAPI_NodeId node_id_to_connect ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_DisconnectNodeInput( ref HAPI_Session session, HAPI_NodeId node_id, int input_index ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_QueryNodeInput( ref HAPI_Session session, HAPI_NodeId node_to_query, int input_index, out HAPI_NodeId connected_node_id ); // PARAMETERS ----------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParameters( ref HAPI_Session session, HAPI_NodeId node_id, [Out] HAPI_ParmInfo[] parm_infos_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmInfo( ref HAPI_Session session, HAPI_NodeId node_id, HAPI_ParmId parm_id, out HAPI_ParmInfo parm_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmIdFromName( ref HAPI_Session session, HAPI_NodeId node_id, string parm_name, out HAPI_ParmId parm_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmInfoFromName( ref HAPI_Session session, HAPI_NodeId node_id, string parm_name, out HAPI_ParmInfo parm_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmIntValue( ref HAPI_Session session, HAPI_NodeId node_id, string parm_name, int index, out int value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmIntValues( ref HAPI_Session session, HAPI_NodeId node_id, [Out] int[] values_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmFloatValue( ref HAPI_Session session, HAPI_NodeId node_id, string parm_name, int index, out float value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmFloatValues( ref HAPI_Session session, HAPI_NodeId node_id, [Out] float[] values_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmStringValue( ref HAPI_Session session, HAPI_NodeId node_id, string parm_name, int index, [ MarshalAs( UnmanagedType.U1 ) ] bool evaluate, out HAPI_StringHandle value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmStringValues( ref HAPI_Session session, HAPI_NodeId node_id, [ MarshalAs( UnmanagedType.U1 ) ] bool evaluate, [Out] HAPI_StringHandle[] values_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmFile( ref HAPI_Session session, HAPI_NodeId node_id, string parm_name, string destination_directory, string destination_file_name ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetParmChoiceLists( ref HAPI_Session session, HAPI_NodeId node_id, [Out] HAPI_ParmChoiceInfo[] parm_choices_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetParmIntValue( ref HAPI_Session session, HAPI_NodeId node_id, string parm_name, int index, int value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetParmIntValues( ref HAPI_Session session, HAPI_NodeId node_id, int[] values_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetParmFloatValue( ref HAPI_Session session, HAPI_NodeId node_id, string parm_name, int index, float value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetParmFloatValues( ref HAPI_Session session, HAPI_NodeId node_id, float[] values_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetParmStringValue( ref HAPI_Session session, HAPI_NodeId node_id, string value, HAPI_ParmId parm_id, int index ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_InsertMultiparmInstance( ref HAPI_Session session, HAPI_NodeId node_id, HAPI_ParmId parm_id, int instance_position ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_RemoveMultiparmInstance( ref HAPI_Session session, HAPI_NodeId node_id, HAPI_ParmId parm_id, int instance_position ); // HANDLES -------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetHandleInfo( ref HAPI_Session session, HAPI_AssetId asset_id, [Out] HAPI_HandleInfo[] handle_infos_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetHandleBindingInfo( ref HAPI_Session session, HAPI_AssetId asset_id, int handle_index, [Out] HAPI_HandleBindingInfo[] handle_binding_infos_array, int start, int length ); // PRESETS -------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetPresetBufLength( ref HAPI_Session session, HAPI_NodeId node_id, HAPI_PresetType preset_type, string preset_name, ref int buffer_length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetPreset( ref HAPI_Session session, HAPI_NodeId node_id, [Out] byte[] preset, int buffer_length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetPreset( ref HAPI_Session session, HAPI_NodeId node_id, HAPI_PresetType preset_type, string preset_name, byte[] preset, int buffer_length ); // OBJECTS -------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetObjects( ref HAPI_Session session, HAPI_AssetId asset_id, [Out] HAPI_ObjectInfo[] object_infos_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetObjectTransforms( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_RSTOrder rst_order, [Out] HAPI_Transform[] transforms_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetInstanceTransforms( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_RSTOrder rst_order, [Out] HAPI_Transform[] transforms_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetObjectTransform( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, ref HAPI_TransformEuler transform ); // GEOMETRY GETTERS ----------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetGeoInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, out HAPI_GeoInfo geo_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetPartInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, out HAPI_PartInfo part_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetFaceCounts( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, [Out] int[] face_counts_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetVertexList( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, [Out] int[] vertex_list_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetAttributeInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, string name, HAPI_AttributeOwner owner, ref HAPI_AttributeInfo attr_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetAttributeNames( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, HAPI_AttributeOwner owner, [Out] HAPI_StringHandle[] attribute_names_array, int count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetAttributeIntData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, string name, ref HAPI_AttributeInfo attr_info, [Out] int[] data, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetAttributeFloatData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, string name, ref HAPI_AttributeInfo attr_info, [Out] float[] data_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetAttributeStringData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, string name, ref HAPI_AttributeInfo attr_info, [Out] int[] data_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetGroupNames( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_GroupType group_type, [Out] HAPI_StringHandle[] group_names_array, int group_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetGroupMembership( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, HAPI_GroupType group_type, string group_name, [Out] int[] membership_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetInstancedPartIds( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, [Out] HAPI_PartId[] instanced_parts_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetInstancerPartTransforms( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, HAPI_RSTOrder rst_order, [Out] HAPI_Transform[] instanced_parts_array, int start, int length ); // GEOMETRY SETTERS ----------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetGeoInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, ref HAPI_GeoInfo geo_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetPartInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, ref HAPI_PartInfo part_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetFaceCounts( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, int[] face_counts_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetVertexList( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, int[] vertex_list_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_AddAttribute( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, string name, ref HAPI_AttributeInfo attr_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetAttributeIntData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, string name, ref HAPI_AttributeInfo attr_info, int[] data_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetAttributeFloatData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, string name, ref HAPI_AttributeInfo attr_info, float[] data_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetAttributeStringData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, string name, ref HAPI_AttributeInfo attr_info, string[] data_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_AddGroup( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_GroupType group_type, string group_name ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetGroupMembership( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_GroupType group_type, string group_name, [Out] int[] membership_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_CommitGeo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_RevertGeo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id ); // INTER ASSET ---------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ConnectAssetTransform( ref HAPI_Session session, HAPI_AssetId asset_id_from, HAPI_AssetId asset_id_to, int input_idx ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_DisconnectAssetTransform( ref HAPI_Session session, HAPI_AssetId asset_id, int input_idx ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ConnectAssetGeometry( ref HAPI_Session session, HAPI_AssetId asset_id_from, HAPI_ObjectId object_id_from, HAPI_AssetId asset_id_to, int input_idx ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_DisconnectAssetGeometry( ref HAPI_Session session, HAPI_AssetId asset_id, int input_idx ); // MATERIALS ------------------------------------------------------------------------------------------------ [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetMaterialIdsOnFaces( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, [ MarshalAs( UnmanagedType.U1 ) ] ref bool are_all_the_same, [Out] HAPI_MaterialId[] material_ids_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetMaterialInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_MaterialId material_id, out HAPI_MaterialInfo material_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetMaterialOnPart( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, out HAPI_MaterialInfo material_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetMaterialOnGroup( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, string group_name, out HAPI_MaterialInfo material_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_RenderTextureToImage( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_MaterialId material_id, HAPI_ParmId parm_id ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetSupportedImageFileFormatCount( ref HAPI_Session session, out int file_format_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetSupportedImageFileFormats( ref HAPI_Session session, [Out] HAPI_ImageFileFormat[] formats_array, int file_format_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetImageInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_MaterialId material_id, out HAPI_ImageInfo image_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetImageInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_MaterialId material_id, ref HAPI_ImageInfo image_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetImagePlaneCount( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_MaterialId material_id, out int image_plane_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetImagePlanes( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_MaterialId material_id, [Out] HAPI_StringHandle[] image_planes_array, int image_plane_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ExtractImageToFile( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_MaterialId material_id, string image_file_format_name, string image_planes, string destination_folder_path, string destination_file_name, out int destination_file_path ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ExtractImageToMemory( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_MaterialId material_id, string image_file_format_name, string image_planes, out int buffer_size ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetImageMemoryBuffer( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_MaterialId material_id, [Out] byte[] buffer, int length ); // SIMULATION/ANIMATIONS ------------------------------------------------------------------------------------ [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetAnimCurve( ref HAPI_Session session, HAPI_NodeId node_id, HAPI_ParmId parm_id, int parm_index, HAPI_Keyframe[] curve_keyframes_array, int keyframe_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetTransformAnimCurve( ref HAPI_Session session, HAPI_NodeId node_id, HAPI_TransformComponent transform_component, HAPI_Keyframe[] curve_keyframes_array, int keyframe_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_ResetSimulation( ref HAPI_Session session, HAPI_AssetId asset_id ); // VOLUMES -------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetVolumeInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, ref HAPI_VolumeInfo volume_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetFirstVolumeTile( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, ref HAPI_VolumeTileInfo tile ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetNextVolumeTile( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, ref HAPI_VolumeTileInfo tile ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetVolumeVoxelFloatData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, int x_index, int y_index, int z_index, [Out] float[] values_array, int value_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetVolumeTileFloatData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, float fill_value, ref HAPI_VolumeTileInfo tile, [Out] float[] values_array, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetVolumeVoxelIntData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, int x_index, int y_index, int z_index, [Out] int[] values_array, int value_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetVolumeTileIntData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, int fill_value, ref HAPI_VolumeTileInfo tile, [Out] int[] values_array, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetVolumeInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, ref HAPI_VolumeInfo volume_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetVolumeTileFloatData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, ref HAPI_VolumeTileInfo tile, float[] values_array, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetVolumeTileIntData( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, ref HAPI_VolumeTileInfo tile, int[] values_array, int length ); // CURVES --------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetCurveInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, ref HAPI_CurveInfo curve_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetCurveCounts( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, [Out] int[] counts_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetCurveOrders( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, [Out] int[] orders_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetCurveKnots( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, [Out] float[] knots_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetCurveInfo( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, ref HAPI_CurveInfo curve_info ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetCurveCounts( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, int[] counts_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetCurveOrders( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, int[] orders_array, int start, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetCurveKnots( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, HAPI_PartId part_id, float[] knots_array, int start, int length ); // CACHING -------------------------------------------------------------------------------------------------- [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetActiveCacheCount( ref HAPI_Session session, out int active_cache_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetActiveCacheNames( ref HAPI_Session session, [Out] HAPI_StringHandle[] cache_names_array, int active_cache_count ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetCacheProperty( ref HAPI_Session session, string cache_name, HAPI_CacheProperty cache_property, out int property_value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SetCacheProperty( ref HAPI_Session session, string cache_name, HAPI_CacheProperty cache_property, int property_value ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SaveGeoToFile( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, string file_name ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_LoadGeoFromFile( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, string file_name ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_GetGeoSize( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, string format, out int size ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_SaveGeoToMemory( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, [Out] byte[] buffer, int length ); [ DllImport( HoudiniVersion.HAPI_LIBRARY, CallingConvention = CallingConvention.Cdecl ) ] private static extern HAPI_Result HAPI_LoadGeoFromMemory( ref HAPI_Session session, HAPI_AssetId asset_id, HAPI_ObjectId object_id, HAPI_GeoId geo_id, string format, byte[] buffer, int length ); #endif // ( HAPI_ENABLE_RUNTIME ) }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Windows.Forms; using System.Data; using Epi; using Epi.Windows; using Epi.Windows.Dialogs; using Epi.Data; using Epi.Fields; using Epi.Collections; namespace Epi.Windows.MakeView.Dialogs { public partial class CodesDialog : LegalValuesDialog { private double MULTICOLUMN_WIDTH_MULTIPLE = .4; private string fieldName = string.Empty; private DataTable fieldSetupTable; private DataTable fieldValueSetupTable; private Page page; private NamedObjectCollection<Field> selectedFields; private new DDLFieldOfCodes ddlField; public KeyValuePairCollection kvPairs; public string relateCondition = string.Empty; #region Constructors /// <summary> /// Default Constructor - Design mode only /// </summary> [Obsolete("Use of default constructor not allowed", true)] public CodesDialog() { InitializeComponent(); } /// <summary> /// Contructor of the CodesDialog /// </summary> /// <param name="field">The field</param> /// <param name="frm">The main form</param> /// <param name="name">The field name</param> /// <param name="currentPage">The current page</param> /// <param name="selectedItems">The names of the fields from the Code Field Definition dialog</param> public CodesDialog(TableBasedDropDownField field, MainForm frm, string name, Page currentPage, NamedObjectCollection<Field> selectedItems) : base(field, frm, name, currentPage) { InitializeComponent(); fieldName = name; page = currentPage; ddlField = (DDLFieldOfCodes)field; selectedFields = selectedItems; SetDataSource(ddlField); SetDgCodes(dgCodes, fieldName); dgCodes.Visible = true; relateCondition = ddlField.RelateConditionString; } #endregion Constructors #region Public Properties public new string SourceTableName { get { return (sourceTableName); } set { sourceTableName = value; } } public new string TextColumnName { get { return (textColumnName); } } public NamedObjectCollection<Field> SelectedFields { get { return (selectedFields); } } #endregion Public Properties #region Protected Methods protected override void ShowFieldSelection(string tableName) { ShowMatchFieldsDialog(tableName); } #endregion Protected Methods #region Protected Events // NEW protected override void btnCreate_Click(object sender, System.EventArgs e) { creationMode = CreationMode.CreateNew; CreateCodes(); btnCreate.Enabled = false; btnFromExisting.Enabled = false; btnUseExisting.Enabled = false; dgCodes.Visible = true; btnOK.Enabled = true; this.btnMatchFields.Enabled = true; } // NEW FROM EXISTING protected override void btnFromExisting_Click(object sender, System.EventArgs e) { creationMode = CreationMode.CreateNewFromExisting; ViewSelectionDialog dialog = new ViewSelectionDialog(MainForm, page.GetProject()); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { sourceTableName = dialog.TableName; dialog.Close(); if (page.GetProject().CollectedData.TableExists(sourceTableName)) { codeTable = page.GetProject().GetTableData(sourceTableName); } else { string separator = " - "; if (sourceTableName.Contains(separator)) { string[] view_page = sourceTableName.Replace(separator, "^").Split('^'); string viewName = view_page[0].ToString(); string pageName = view_page[1].ToString(); string filterExpression = string.Empty; string tableName = null; View targetView = page.GetProject().Metadata.GetViewByFullName(viewName); if (targetView != null) { DataTable targetPages = page.GetProject().Metadata.GetPagesForView(targetView.Id); DataView dataView = new DataView(targetPages); filterExpression = string.Format("Name = '{0}'", pageName); DataRow[] pageArray = targetPages.Select(filterExpression); if (pageArray.Length > 0) { int pageId = (int)pageArray[0]["PageId"]; tableName = viewName + pageId; } } if (page.GetProject().CollectedData.TableExists(tableName)) { codeTable = page.GetProject().GetTableData(tableName); } } } if (codeTable != null) { dgCodes.Visible = true; codeTable.TableName = sourceTableName; dgCodes.DataSource = codeTable; if (DdlField != null) cbxSort.Checked = !DdlField.ShouldSort; if (DdlColumn != null) cbxSort.Checked = !DdlColumn.ShouldSort; btnCreate.Enabled = false; btnFromExisting.Enabled = false; btnUseExisting.Enabled = false; btnDelete.Enabled = true; btnMatchFields.Enabled = true; } else { btnCreate.Enabled = true; btnFromExisting.Enabled = true; btnUseExisting.Enabled = true; btnDelete.Enabled = false; btnMatchFields.Enabled = false; } isExclusiveTable = true; } } // USE EXISTING protected override void btnUseExisting_Click(object sender, System.EventArgs e) { creationMode = CreationMode.UseExisting; ViewSelectionDialog dialog = new ViewSelectionDialog(MainForm, page.GetProject()); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { sourceTableName = dialog.TableName; dialog.Close(); if (page.GetProject().CollectedData.TableExists(sourceTableName)) { codeTable = page.GetProject().GetTableData(sourceTableName); } else { string separator = " - "; if (sourceTableName.Contains(separator)) { string[] view_page = sourceTableName.Replace(separator, "^").Split('^'); string viewName = view_page[0].ToString(); string pageName = view_page[1].ToString(); string filterExpression = string.Empty; string tableName = null; View targetView = page.GetProject().Metadata.GetViewByFullName(viewName); if (targetView != null) { DataTable targetPages = page.GetProject().Metadata.GetPagesForView(targetView.Id); DataView dataView = new DataView(targetPages); filterExpression = string.Format("Name = '{0}'", pageName); DataRow[] pageArray = targetPages.Select(filterExpression); if (pageArray.Length > 0) { int pageId = (int)pageArray[0]["PageId"]; tableName = viewName + pageId; } } if (page.GetProject().CollectedData.TableExists(tableName)) { codeTable = page.GetProject().GetTableData(tableName); } } } if (codeTable != null) { dgCodes.Visible = true; codeTable.TableName = sourceTableName; dgCodes.DataSource = codeTable; if (DdlField != null) cbxSort.Checked = !DdlField.ShouldSort; if (DdlColumn != null) cbxSort.Checked = !DdlColumn.ShouldSort; btnCreate.Enabled = false; btnFromExisting.Enabled = false; btnUseExisting.Enabled = false; btnDelete.Enabled = true; btnMatchFields.Enabled = true; } else { btnCreate.Enabled = true; btnFromExisting.Enabled = true; btnUseExisting.Enabled = true; btnDelete.Enabled = false; btnMatchFields.Enabled = false; } isExclusiveTable = true; } } protected void CallMatchFieldDialogs() { ViewSelectionDialog dialog = new ViewSelectionDialog(MainForm, page.GetProject()); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { sourceTableName = dialog.TableName; dialog.Close(); btnOK.Enabled = true; } } private void btnMatchFields_Click(object sender, EventArgs e) { if (this.sourceTableName != "") { SaveCodeTableToField(); ShowMatchFieldsDialog(this.sourceTableName); } } #endregion Protected Events #region Private Methods private void SetDgCodes(DataGridView dgCodes, string fieldName) { //dgCodes.CaptionText = "Codes for: " + fieldName.ToLowerInvariant(); //dgCodes.PreferredColumnWidth = Convert.ToInt32(dgCodes.Width * MULTICOLUMN_WIDTH_MULTIPLE); } private void SetDataSource(DDLFieldOfCodes ddlField) { if (!string.IsNullOrEmpty(ddlField.SourceTableName)) { codeTable = ddlField.GetSourceData(); sourceTableName = ddlField.SourceTableName; textColumnName = ddlField.TextColumnName; } } protected override void DisplayData() { bool relateFunctional = RelateConditionFunctional(); if (codeTable == null) { btnCreate.Enabled = true; btnFromExisting.Enabled = true; btnUseExisting.Enabled = true; btnDelete.Enabled = false; btnOK.Enabled = false; btnMatchFields.Enabled = false; } else { codeTable.TableName = sourceTableName; dgCodes.DataSource = codeTable; //dgCodes.CaptionText = sourceTableName; dgCodes.Visible = true; btnCreate.Enabled = false; btnFromExisting.Enabled = false; btnUseExisting.Enabled = false; btnDelete.Enabled = true; cbxSort.Checked = !ddlField.ShouldSort; btnMatchFields.Enabled = true; if (relateFunctional) { btnOK.Enabled = true; } else { btnOK.Enabled = false; } } btnOK.Visible = true; btnDelete.Visible = true; } private bool RelateConditionFunctional() { if (string.IsNullOrEmpty(relateCondition)) { return false; } return true; } private void CreateCodes() { dgCodes.Visible = true; Project project = page.GetProject(); DataTable bindingTable = project.CodeData.GetCodeTableNamesForProject(project); DataView dataView = bindingTable.DefaultView; //if (dgCodes.AllowSorting) { dataView.Sort = GetDisplayString(page); } string cleanedCodeTableName = CleanCodeTableName(fieldName, dataView); if (SelectedFields.Count >= 1) { int i = 1; string[] selectedFieldsForCodeColumns = new string[SelectedFields.Count + 1]; selectedFieldsForCodeColumns[0] = fieldName; foreach (Field field in SelectedFields) { selectedFieldsForCodeColumns[i] = field.Name; i += 1; } //dgCodes.PreferredColumnWidth = Convert.ToInt32(dgCodes.Width * MULTICOLUMN_WIDTH_MULTIPLE); project.CreateCodeTable(cleanedCodeTableName, selectedFieldsForCodeColumns); } else { project.CreateCodeTable(cleanedCodeTableName, fieldName.ToLowerInvariant()); } codeTable = project.GetTableData(cleanedCodeTableName); codeTable.TableName = cleanedCodeTableName; dgCodes.DataSource = codeTable; sourceTableName = codeTable.TableName; textColumnName = fieldName; newCodeTable = codeTable; } private void ShowMatchFieldsDialog(string tableName) { Project project = page.GetProject(); List<string> selectedFields = new List<string>(); foreach(Field field in SelectedFields) { selectedFields.Add(field.Name); } Dictionary<string, string> fieldColumnNamePairs = new Dictionary<string, string>(); foreach (KeyValuePair<string, int> kvp in ddlField.PairAssociated) { Field fieldById = page.view.GetFieldById(kvp.Value); fieldColumnNamePairs.Add(fieldById.Name, kvp.Key); } MatchFieldsDialog dialog = new MatchFieldsDialog ( MainForm, project, tableName, selectedFields, ddlField.TextColumnName, fieldColumnNamePairs); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { string valueTableName = tableName.ToString() + "value"; fieldSetupTable = new DataTable(tableName); fieldSetupTable.Columns.Add(fieldName, dialog.PrimaryColumnData.GetType()); fieldValueSetupTable = new DataTable(valueTableName); if (project.CollectedData.TableExists(tableName)) { fieldValueSetupTable = project.GetTableData(tableName, dialog.PrimaryColumnData.ToString()); } newCodeTable = new DataTable(); newCodeTable = fieldValueSetupTable.Clone(); newCodeTable.Clear(); if (newCodeTable.Columns.Count > 0) { newCodeTable.Columns.RemoveAt(0); } newCodeTable.Columns.Add(fieldName, dialog.PrimaryColumnData.GetType()); foreach (DataRow row in fieldValueSetupTable.Rows) { DataRow rowToAdd = newCodeTable.NewRow(); rowToAdd[0] = row[0]; newCodeTable.Rows.Add(rowToAdd); } kvPairs = dialog.Codes; System.Collections.ArrayList codeColumns = new System.Collections.ArrayList(); string columnNames = string.Empty; foreach (KeyValuePair kvPair in kvPairs) { codeColumns.Add(kvPair.Value); columnNames += kvPair.Value.ToString() + StringLiterals.COMMA; } if (columnNames.Length > 1) { columnNames = columnNames.Substring(0, (columnNames.Length - 1)); } sourceTableName = tableName; textColumnName = dialog.PrimaryColumnData; if (Mode == CreationMode.CreateNewFromExisting) { textColumnName = fieldName; string[] comma = { "," }; string column = string.Empty; foreach (KeyValuePair kvPair in kvPairs) { column += kvPair.Key.ToString() + StringLiterals.COMMA; } if (column.Length > 1) { column = column.Substring(0, (column.Length - 1)); } string[] columns = column.Split(comma, StringSplitOptions.None); for (int i = 0; i < columns.Length; i++) { newCodeTable.Columns.Add(columns[i]); } string columnNamesForValues = string.Empty; foreach (KeyValuePair kvPair in kvPairs) { columnNamesForValues += kvPair.Value.ToString() + StringLiterals.COMMA; } if (columnNamesForValues.Length > 1) { columnNamesForValues = columnNamesForValues.Substring(0, (columnNamesForValues.Length - 1)); } string newTableColumnName = string.Empty; string existingColumnName = string.Empty; foreach (DataColumn dataColumnOfNewTable in newCodeTable.Columns) { newTableColumnName = dataColumnOfNewTable.ColumnName; foreach (KeyValuePair kvPair in kvPairs) { if(kvPair.Key == newTableColumnName) { existingColumnName = kvPair.Value; break; } } if (string.IsNullOrEmpty(existingColumnName) == false) { for (int i = 0; i < codeTable.Rows.Count; i++) { newCodeTable.Rows[i][newTableColumnName] = codeTable.Rows[i][existingColumnName]; } } } sourceTableName = GetNewCodeTableName(FieldName); newCodeTable.TableName = sourceTableName; codeTable = newCodeTable; } else { relateCondition = string.Empty; foreach (KeyValuePair kvPair in kvPairs) { relateCondition = relateCondition.Length > 0 ? relateCondition + "," : relateCondition; int fieldId = this.page.Fields[kvPair.Key].Id; relateCondition = string.Format("{0}{1}:{2}", relateCondition, kvPair.Value, fieldId); } } dialog.Close(); DisplayData(); } } private void SaveShouldSort() { if (ddlField != null) { ddlField.ShouldSort = !cbxSort.Checked; } } #endregion Private Methods } }
using System; using UnityEngine; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.IO; namespace StrumpyShaderEditor { /* High level graph, stores all the subgraphs and shader settings */ [DataContract(Namespace = "http://strumpy.net/ShaderEditor/")] public class ShaderGraph { [DataMember] private ShaderSettings shaderSettings; [DataMember] private ShaderInputs shaderInputs; [DataMember] private PixelShaderGraph pixelGraph; [DataMember] private VertexShaderGraph vertexGraph; [DataMember] private SimpleLightingShaderGraph simpleLightingGraph; [DataMember] public SubGraphType CurrentSubGraphType{ get; set; } //This fetches the sub graph that is currently selected public SubGraph CurrentSubGraph { get{ switch( CurrentSubGraphType ) { case SubGraphType.Pixel: return pixelGraph; case SubGraphType.Vertex: return vertexGraph; case SubGraphType.SimpleLighting: return simpleLightingGraph; default: return pixelGraph; } } } public void Initialize ( Rect screenDimension, bool updateDrawPos ) { shaderInputs = shaderInputs ?? new ShaderInputs(); shaderSettings = shaderSettings ?? new ShaderSettings(); pixelGraph = pixelGraph ?? new PixelShaderGraph(); vertexGraph = vertexGraph ?? new VertexShaderGraph(); simpleLightingGraph = simpleLightingGraph ?? new SimpleLightingShaderGraph(); shaderInputs.Initialize(); shaderSettings.Initialize(); pixelGraph.Initialize(this, screenDimension, updateDrawPos); vertexGraph.Initialize(this, screenDimension, updateDrawPos); simpleLightingGraph.Initialize(this, screenDimension, updateDrawPos); MarkDirty(); } public IEnumerable<ShaderProperty> FindValidProperties( InputType type ) { return shaderInputs.FindValidProperties( type ); } public int AddProperty( ShaderProperty p ) { var result = shaderInputs.AddProperty( p ); MarkDirty(); return result; } public IEnumerable<ShaderProperty> GetProperties( ) { return shaderInputs.GetProperties( ); } public IEnumerable<T> GetValidNodes<T> () where T : class { var foundNodes = new List<T> (); foreach( var graph in AllSubGraphs() ) { foundNodes.AddRange( graph.GetValidNodes<T>() ); } return foundNodes; } private IEnumerable<SubGraph> AllSubGraphs() { return new List<SubGraph> {pixelGraph, vertexGraph, simpleLightingGraph}; } public void MarkDirty() { foreach( var graph in AllSubGraphs() ) { graph.MarkDirty(); } } public void Draw( NodeEditor editor, bool showComments, Rect drawWindow ) { CurrentSubGraph.Draw( editor, showComments, drawWindow ); } public void DrawSettings() { shaderSettings.Draw(); } public void DrawInput() { shaderInputs.Draw(); } public Node FirstSelected { get{ return CurrentSubGraph.FirstSelected; } } public void Deselect() { foreach( var graph in AllSubGraphs() ) { graph.Deselect(); } } public void Deselect( Node n ) { CurrentSubGraph.Deselect( n ); } public bool IsSelected( Node n ) { return CurrentSubGraph.IsSelected( n ); } public Node NodeAt (Vector2 location ) { return CurrentSubGraph.NodeAt( location ); } public bool ButtonAt (Vector2 location ) { return CurrentSubGraph.ButtonAt( location ); } public bool Select (Vector2 location, bool addSelect ) { return CurrentSubGraph.Select( location, addSelect ); } public bool Select (Rect area, bool addSelect ) { return CurrentSubGraph.Select( area, addSelect ); } public void Select ( Node node, bool addSelect ) { CurrentSubGraph.Select( node, addSelect ); } public void SelectAll ( ) { CurrentSubGraph.SelectAll( ); } public void MarkSelectedHot() { CurrentSubGraph.MarkSelectedHot(); } public void UnmarkSelectedHot() { CurrentSubGraph.UnmarkSelectedHot(); } public bool DragSelectedNodes (Vector2 delta) { return CurrentSubGraph.DragSelectedNodes( delta ); } public Rect DrawSize { get { return CurrentSubGraph.DrawSize; } } public RootNode RootNode { get { return CurrentSubGraph.RootNode; } } public bool ContainsCircularReferences () { return AllSubGraphs().Any( x => x.ContainsCircularReferences() ); } public bool IsGraphValid () { return AllSubGraphs().All( x => x.IsSubGraphValid() ) && shaderInputs.InputsValid() && shaderSettings.SettingsValid(); } // Texel - Oh the woes to be avoided if you just made settings public. public bool IsInputsValid () { return shaderInputs.InputsValid(); } public bool IsSettingsValid () { return shaderSettings.SettingsValid(); } /* Go through all the graphs and look for any errors in them * if there are errors the shader can not be compiled */ public void UpdateErrorState() { //If the graph is nor dirty... if( AllSubGraphs().All( x => x.Dirty == false ) ) { return; } foreach( var graph in AllSubGraphs() ) { graph.UpdateErrorState(); } foreach( var graph in AllSubGraphs() ) { foreach( var graph2 in AllSubGraphs() ) { if( graph != graph2 ) { var inputNodes = from node in graph.Nodes where node is IFieldInput select node as IFieldInput; var inputNodes2 = from node in graph2.Nodes where node is IFieldInput select node as IFieldInput; foreach( var input in inputNodes ) { var input1 = input; if( inputNodes2.Any( x => x.GetFieldName() == input1.GetFieldName() ) ) { var node = input as Node; if (node != null) { node.AddErrors( new List<string> {"Node with same name exists in " + graph2.GraphTypeName + " graph"} ); node.CurrentState = NodeState.Error; } } } } } } } /* Built the shader * this mushes the graphs from a tree structure into code, then * replaces the templated areas from the shader template with the generated * hlsl */ public string GetShader (string shaderTemplateLocation, bool isPreviewShader) { var shaderTemplate = File.ReadAllText (shaderTemplateLocation); bool needsTimeNode = false; bool needsSinTimeNode = false; bool needsCosTimeNode = false; foreach( var graph in AllSubGraphs() ) { graph.SetPreview( isPreviewShader ); needsTimeNode |= graph.NeedsTimeNode; needsSinTimeNode |= graph.NeedsSinTimeNode; needsCosTimeNode |= graph.NeedsCosTimeNode; } shaderTemplate = shaderTemplate.Replace ("${ShaderName}", isPreviewShader ? "ShaderEditor/EditorShaderCache" : shaderSettings.ShaderName ); shaderTemplate = shaderTemplate.Replace ("${Fallback}", shaderSettings.FallBack ); var properties = ""; var shaderVariableNames = ""; properties += shaderInputs.GetInputProperties(); shaderVariableNames += shaderInputs.GetInputVariables(); properties += (isPreviewShader && needsTimeNode ) ? "_EditorTime(\"_EditorTime\",Vector) = (0.0,0.0,0.0,0.0)\n" : ""; properties += (isPreviewShader && needsCosTimeNode ) ? "_EditorCosTime(\"_EditorCosTime\",Vector) = (0.0,0.0,0.0,0.0)\n" : ""; properties += (isPreviewShader && needsSinTimeNode ) ? "_EditorSinTime(\"_EditorSinTime\",Vector) = (0.0,0.0,0.0,0.0)\n" : ""; shaderVariableNames += (isPreviewShader && needsTimeNode ) ? "float4 _EditorTime;\n" : ""; shaderVariableNames += (isPreviewShader && needsCosTimeNode ) ? "float4 _EditorCosTime;\n" : ""; shaderVariableNames += (isPreviewShader && needsSinTimeNode ) ? "float4 _EditorSinTime;\n" : ""; var requiresGrabPass = AllSubGraphs().Any( x=> x.RequiresGrabPass ); shaderVariableNames += requiresGrabPass ? "sampler2D _GrabTexture;\n" : "" ; shaderVariableNames += AllSubGraphs().Any( x => x.RequiresSceneDepth ) ? "sampler2D _CameraDepthTexture;\n" : ""; shaderTemplate = shaderTemplate.Replace ("${ShaderProperties}", properties ); shaderTemplate = shaderTemplate.Replace ("${ShaderVariableNames}", shaderVariableNames ); shaderTemplate = shaderTemplate.Replace("${GrabPass}", requiresGrabPass ? "GrabPass { }" : ""); shaderTemplate = shaderTemplate.Replace ("${Tags}", shaderSettings.Tags); shaderTemplate = shaderTemplate.Replace ("${Options}", shaderSettings.Options); shaderTemplate = shaderTemplate.Replace ("${SurfaceFlags}", shaderSettings.SurfaceFlags ); shaderTemplate = shaderTemplate.Replace ("${ShaderPragma}", shaderSettings.Pragma); shaderTemplate = shaderTemplate.Replace ("${LightingFunctionPrePass}", simpleLightingGraph.LightingFunctionBody ); shaderTemplate = shaderTemplate.Replace ("${StructInputs}", pixelGraph.StructInput); shaderTemplate = shaderTemplate.Replace ("${VertexShader}", vertexGraph.ShaderBody ); shaderTemplate = shaderTemplate.Replace ("${VertexShaderMods}", pixelGraph.VertexShaderMods); shaderTemplate = shaderTemplate.Replace ("${SurfaceShader}", pixelGraph.ShaderBody ); return shaderTemplate; } } }
//----------------------------------------------------------------------------- // GameScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input.Touch; namespace UserInterfaceSample { /// <summary> /// Enum describes the screen transition state. /// </summary> public enum ScreenState { TransitionOn, Active, TransitionOff, Hidden, } /// <summary> /// A screen is a single layer that has update and draw logic, and which /// can be combined with other layers to build up a complex menu system. /// For instance the main menu, the options menu, the "are you sure you /// want to quit" message box, and the main game itself are all implemented /// as screens. /// </summary> public abstract class GameScreen { #region Properties /// <summary> /// Normally when one screen is brought up over the top of another, /// the first screen will transition off to make room for the new /// one. This property indicates whether the screen is only a small /// popup, in which case screens underneath it do not need to bother /// transitioning off. /// </summary> public bool IsPopup { get { return isPopup; } protected set { isPopup = value; } } bool isPopup = false; /// <summary> /// Indicates how long the screen takes to /// transition on when it is activated. /// </summary> public TimeSpan TransitionOnTime { get { return transitionOnTime; } protected set { transitionOnTime = value; } } TimeSpan transitionOnTime = TimeSpan.Zero; /// <summary> /// Indicates how long the screen takes to /// transition off when it is deactivated. /// </summary> public TimeSpan TransitionOffTime { get { return transitionOffTime; } protected set { transitionOffTime = value; } } TimeSpan transitionOffTime = TimeSpan.Zero; /// <summary> /// Gets the current position of the screen transition, ranging /// from zero (fully active, no transition) to one (transitioned /// fully off to nothing). /// </summary> public float TransitionPosition { get { return transitionPosition; } protected set { transitionPosition = value; } } float transitionPosition = 1; /// <summary> /// Gets the current alpha of the screen transition, ranging /// from 1 (fully active, no transition) to 0 (transitioned /// fully off to nothing). /// </summary> public float TransitionAlpha { get { return 1f - TransitionPosition; } } /// <summary> /// Gets the current screen transition state. /// </summary> public ScreenState ScreenState { get { return screenState; } protected set { screenState = value; } } ScreenState screenState = ScreenState.TransitionOn; /// <summary> /// There are two possible reasons why a screen might be transitioning /// off. It could be temporarily going away to make room for another /// screen that is on top of it, or it could be going away for good. /// This property indicates whether the screen is exiting for real: /// if set, the screen will automatically remove itself as soon as the /// transition finishes. /// </summary> public bool IsExiting { get { return isExiting; } protected internal set { isExiting = value; } } bool isExiting = false; /// <summary> /// Checks whether this screen is active and can respond to user input. /// </summary> public bool IsActive { get { return !otherScreenHasFocus && (screenState == ScreenState.TransitionOn || screenState == ScreenState.Active); } } bool otherScreenHasFocus; /// <summary> /// Gets the manager that this screen belongs to. /// </summary> public ScreenManager ScreenManager { get { return screenManager; } internal set { screenManager = value; } } ScreenManager screenManager; /// <summary> /// Gets the index of the player who is currently controlling this screen, /// or null if it is accepting input from any player. This is used to lock /// the game to a specific player profile. The main menu responds to input /// from any connected gamepad, but whichever player makes a selection from /// this menu is given control over all subsequent screens, so other gamepads /// are inactive until the controlling player returns to the main menu. /// </summary> public PlayerIndex? ControllingPlayer { get { return controllingPlayer; } internal set { controllingPlayer = value; } } PlayerIndex? controllingPlayer; /// <summary> /// Gets the gestures the screen is interested in. Screens should be as specific /// as possible with gestures to increase the accuracy of the gesture engine. /// For example, most menus only need Tap or perhaps Tap and VerticalDrag to operate. /// These gestures are handled by the ScreenManager when screens change and /// all gestures are placed in the InputState passed to the HandleInput method. /// </summary> public GestureType EnabledGestures { get { return enabledGestures; } protected set { enabledGestures = value; // the screen manager handles this during screen changes, but // if this screen is active and the gesture types are changing, // we have to update the TouchPanel ourself. if (ScreenState == ScreenState.Active) { TouchPanel.EnabledGestures = value; } } } GestureType enabledGestures = GestureType.None; /// <summary> /// Gets whether or not this screen is serializable. If this is true, /// the screen will be recorded into the screen manager's state and /// its Serialize and Deserialize methods will be called as appropriate. /// If this is false, the screen will be ignored during serialization. /// By default, all screens are assumed to be serializable. /// </summary> public bool IsSerializable { get { return isSerializable; } protected set { isSerializable = value; } } bool isSerializable = true; #endregion #region Initialization /// <summary> /// Load graphics content for the screen. /// </summary> public virtual void LoadContent() { } /// <summary> /// Unload content for the screen. /// </summary> public virtual void UnloadContent() { } #endregion #region Update and Draw /// <summary> /// Allows the screen to run logic, such as updating the transition position. /// Unlike HandleInput, this method is called regardless of whether the screen /// is active, hidden, or in the middle of a transition. /// </summary> public virtual void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { this.otherScreenHasFocus = otherScreenHasFocus; if (isExiting) { // If the screen is going away to die, it should transition off. screenState = ScreenState.TransitionOff; if (!UpdateTransition(gameTime, transitionOffTime, 1)) { // When the transition finishes, remove the screen. ScreenManager.RemoveScreen(this); } } else if (coveredByOtherScreen) { // If the screen is covered by another, it should transition off. if (UpdateTransition(gameTime, transitionOffTime, 1)) { // Still busy transitioning. screenState = ScreenState.TransitionOff; } else { // Transition finished! screenState = ScreenState.Hidden; } } else { // Otherwise the screen should transition on and become active. if (UpdateTransition(gameTime, transitionOnTime, -1)) { // Still busy transitioning. screenState = ScreenState.TransitionOn; } else { // Transition finished! screenState = ScreenState.Active; } } } /// <summary> /// Helper for updating the screen transition position. /// </summary> bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction) { // How much should we move by? float transitionDelta; if (time == TimeSpan.Zero) transitionDelta = 1; else transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds / time.TotalMilliseconds); // Update the transition position. transitionPosition += transitionDelta * direction; // Did we reach the end of the transition? if (((direction < 0) && (transitionPosition <= 0)) || ((direction > 0) && (transitionPosition >= 1))) { transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1); return false; } // Otherwise we are still busy transitioning. return true; } /// <summary> /// Allows the screen to handle user input. Unlike Update, this method /// is only called when the screen is active, and not when some other /// screen has taken the focus. /// </summary> public virtual void HandleInput(InputState input) { } /// <summary> /// This is called when the screen should draw itself. /// </summary> public virtual void Draw(GameTime gameTime) { } #endregion #region Public Methods /// <summary> /// Tells the screen to serialize its state into the given stream. /// </summary> public virtual void Serialize(Stream stream) { } /// <summary> /// Tells the screen to deserialize its state from the given stream. /// </summary> public virtual void Deserialize(Stream stream) { } /// <summary> /// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which /// instantly kills the screen, this method respects the transition timings /// and will give the screen a chance to gradually transition off. /// </summary> public void ExitScreen() { if (TransitionOffTime == TimeSpan.Zero) { // If the screen has a zero transition time, remove it immediately. ScreenManager.RemoveScreen(this); } else { // Otherwise flag that it should transition off and then exit. isExiting = true; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using ServiceStack.Text; namespace ServiceStack.Script { // ReSharper disable InconsistentNaming public class MarkdownTable { public bool IncludeHeaders { get; set; } = true; public bool IncludeRowNumbers { get; set; } = true; public string Caption { get; set; } public List<string> Headers { get; } = new List<string>(); public List<List<string>> Rows { get; } = new List<List<string>>(); public string Render() { if (Rows.Count == 0) return null; var sb = StringBuilderCache.Allocate(); var headersCount = Headers.Count; var colSize = new int[headersCount]; var i=0; var rowNumLength = IncludeRowNumbers ? (Rows.Count + 1).ToString().Length : 0; var noOfCols = IncludeHeaders && headersCount > 0 ? headersCount : Rows[0].Count; for (; i < noOfCols; i++) { colSize[i] = IncludeHeaders && i < headersCount ? Headers[i].Length : 0; foreach (var row in Rows) { var rowLen = i < row.Count ? row[i]?.Length ?? 0 : 0; if (rowLen > colSize[i]) colSize[i] = rowLen; } } if (!string.IsNullOrEmpty(Caption)) { sb.AppendLine(Caption) .AppendLine(); } if (IncludeHeaders && headersCount > 0) { sb.Append("| "); if (IncludeRowNumbers) { sb.Append("#".PadRight(rowNumLength, ' ')) .Append(" | "); } for (i = 0; i < headersCount; i++) { var header = Headers[i]; sb.Append(header.PadRight(colSize[i], ' ')) .Append( i + 1 < headersCount ? " | " : " |"); } sb.AppendLine(); sb.Append("|-"); if (IncludeRowNumbers) { sb.Append("".PadRight(rowNumLength, '-')) .Append("-|-"); } for (i = 0; i < headersCount; i++) { sb.Append("".PadRight(colSize[i], '-')) .Append( i + 1 < headersCount ? "-|-" : "-|"); } sb.AppendLine(); } for (var rowIndex = 0; rowIndex < Rows.Count; rowIndex++) { var row = Rows[rowIndex]; sb.Append("| "); if (IncludeRowNumbers) { sb.Append($"{rowIndex + 1}".PadRight(rowNumLength, ' ')) .Append(" | "); } for (i = 0; i < headersCount; i++) { var field = i < row.Count ? row[i] : null; sb.Append((field ?? "").PadRight(colSize[i], ' ')) .Append( i + 1 < headersCount ? " | " : " |"); } sb.AppendLine(); } sb.AppendLine(); return StringBuilderCache.ReturnAndFree(sb); } } public partial class DefaultScripts { public IRawString textList(IEnumerable target) => TextList(target, new TextDumpOptions { Defaults = Context.DefaultMethods }).ToRawString(); public IRawString textList(IEnumerable target, Dictionary<string, object> options) => TextList(target, TextDumpOptions.Parse(options, Context.DefaultMethods)).ToRawString(); public IRawString textDump(object target) => TextDump(target, new TextDumpOptions { Defaults = Context.DefaultMethods }).ToRawString(); public IRawString textDump(object target, Dictionary<string, object> options) => TextDump(target, TextDumpOptions.Parse(options, Context.DefaultMethods)).ToRawString(); public static string TextList(IEnumerable items, TextDumpOptions options) { if (options == null) options = new TextDumpOptions(); if (items is IDictionary<string, object> single) items = new[] { single }; var depth = options.Depth; options.Depth += 1; try { var headerStyle = options.HeaderStyle; List<string> keys = null; var table = new MarkdownTable { IncludeRowNumbers = options.IncludeRowNumbers }; foreach (var item in items) { if (item is IDictionary<string, object> d) { if (keys == null) { keys = d.Keys.ToList(); foreach (var key in keys) { table.Headers.Add(ViewUtils.StyleText(key, headerStyle)); } } var row = new List<string>(); foreach (var key in keys) { var value = d[key]; if (ReferenceEquals(value, items)) break; // Prevent cyclical deps like 'it' binding if (!isComplexType(value)) { row.Add(GetScalarText(value, options.Defaults)); } else { var cellValue = TextDump(value, options); row.Add(cellValue); } } table.Rows.Add(row); } } var isEmpty = table.Rows.Count == 0; if (isEmpty) return options.CaptionIfEmpty ?? string.Empty; var caption = options.Caption; if (caption != null && !options.HasCaption) { table.Caption = caption; options.HasCaption = true; } var txt = table.Render(); return txt; } finally { options.Depth = depth; } } public static string TextDump(object target, TextDumpOptions options) { if (options == null) options = new TextDumpOptions(); var depth = options.Depth; options.Depth += 1; try { target = ConvertDumpType(target); if (!isComplexType(target)) return GetScalarText(target, options.Defaults); var headerStyle = options.HeaderStyle; if (target is IEnumerable e) { var objs = e.Map(x => x); var isEmpty = objs.Count == 0; if (isEmpty) return options.CaptionIfEmpty ?? string.Empty; var first = objs[0]; if (first is IDictionary && objs.Count > 1) return TextList(objs, options); var sb = StringBuilderCacheAlt.Allocate(); string writeCaption = null; var caption = options.Caption; if (caption != null && !options.HasCaption) { writeCaption = caption; options.HasCaption = true; } if (!isEmpty) { var keys = new List<string>(); var values = new List<string>(); string TextKvps(StringBuilder s, IEnumerable<KeyValuePair<string, object>> kvps) { foreach (var kvp in kvps) { if (kvp.Value == target) break; // Prevent cyclical deps like 'it' binding keys.Add(ViewUtils.StyleText(kvp.Key, headerStyle) ?? ""); var field = !isComplexType(kvp.Value) ? GetScalarText(kvp.Value, options.Defaults) : TextDump(kvp.Value, options); values.Add(field); } var keySize = keys.Max(x => x.Length); var valuesSize = values.Max(x => x.Length); s.AppendLine(writeCaption != null ? $"| {writeCaption.PadRight(keySize + valuesSize + 2, ' ')} ||" : $"|||"); s.AppendLine(writeCaption != null ? $"|-{"".PadRight(keySize, '-')}-|-{"".PadRight(valuesSize, '-')}-|" : "|-|-|"); for (var i = 0; i < keys.Count; i++) { s.Append("| ") .Append(keys[i].PadRight(keySize, ' ')) .Append(" | ") .Append(values[i].PadRight(valuesSize, ' ')) .Append(" |") .AppendLine(); } return StringBuilderCache.ReturnAndFree(s); } if (first is KeyValuePair<string, object>) { return TextKvps(sb, objs.Cast<KeyValuePair<string, object>>()); } else { if (!isComplexType(first)) { foreach (var o in objs) { values.Add(GetScalarText(o, options.Defaults)); } var valuesSize = values.Max(MaxLineLength); if (writeCaption?.Length > valuesSize) valuesSize = writeCaption.Length; sb.AppendLine(writeCaption != null ? $"| {writeCaption.PadRight(valuesSize)} |" : $"||"); sb.AppendLine(writeCaption != null ? $"|-{"".PadRight(valuesSize,'-')}-|" : "|-|"); foreach (var value in values) { sb.Append("| ") .Append(value.PadRight(valuesSize, ' ')) .Append(" |") .AppendLine(); } } else { if (objs.Count > 1) { if (writeCaption != null) sb.AppendLine(writeCaption) .AppendLine(); var rows = objs.Map(x => x.ToObjectDictionary()); var list = TextList(rows, options); sb.AppendLine(list); return StringBuilderCache.ReturnAndFree(sb); } else { foreach (var o in objs) { if (!isComplexType(o)) { values.Add(GetScalarText(o, options.Defaults)); } else { var body = TextDump(o, options); values.Add(body); } } var valuesSize = values.Max(MaxLineLength); if (writeCaption?.Length > valuesSize) valuesSize = writeCaption.Length; sb.AppendLine(writeCaption != null ? $"| {writeCaption.PadRight(valuesSize, ' ')} |" : $"||"); sb.AppendLine(writeCaption != null ? $"|-{"".PadRight(valuesSize,'-')}-|" : "|-|"); foreach (var value in values) { sb.Append("| ") .Append(value.PadRight(valuesSize, ' ')) .Append(" |") .AppendLine(); } } } } } return StringBuilderCache.ReturnAndFree(sb); } return TextDump(target.ToObjectDictionary(), options); } finally { options.Depth = depth; } } internal static object ConvertDumpType(object target) { var targetType = target.GetType(); var genericKvps = targetType.GetTypeWithGenericTypeDefinitionOf(typeof(KeyValuePair<,>)); if (genericKvps != null) { var keyGetter = TypeProperties.Get(targetType).GetPublicGetter("Key"); var valueGetter = TypeProperties.Get(targetType).GetPublicGetter("Value"); return new Dictionary<string, object> { { keyGetter(target).ConvertTo<string>(), valueGetter(target) }, }; } if (target is IEnumerable e) { //Convert IEnumerable<object> to concrete generic collection so generic args can be inferred if (e is IEnumerable<object> enumObjs) { Type elType = null; foreach (var item in enumObjs) { elType = item.GetType(); break; } if (elType != null) { targetType = typeof(List<>).MakeGenericType(elType); var genericList = (IList)targetType.CreateInstance(); foreach (var item in e) { genericList.Add(item.ConvertTo(elType)); } target = genericList; } } if (targetType.GetKeyValuePairsTypes(out var keyType, out var valueType, out var kvpType)) { var keyGetter = TypeProperties.Get(kvpType).GetPublicGetter("Key"); var valueGetter = TypeProperties.Get(kvpType).GetPublicGetter("Value"); string key1 = null, key2 = null; foreach (var kvp in e) { if (key1 == null) { key1 = keyGetter(kvp).ConvertTo<string>(); continue; } key2 = keyGetter(kvp).ConvertTo<string>(); break; } var isColumn = key1 == key2; if (isColumn) { var to = new List<Dictionary<string, object>>(); foreach (var kvp in e) { to.Add(new Dictionary<string, object> { {keyGetter(kvp).ConvertTo<string>(), valueGetter(kvp) } }); } return to; } return target.ToObjectDictionary(); } } return target; } private static int MaxLineLength(string s) { if (string.IsNullOrEmpty(s)) return 0; var len = 0; foreach (var line in s.ReadLines()) { if (line.Length > len) len = line.Length; } return len; } private static string GetScalarText(object target, DefaultScripts defaults) { if (target == null || target.ToString() == string.Empty) return string.Empty; if (target is string s) return s; if (target is decimal dec) { var isMoney = dec == Math.Floor(dec * 100); if (isMoney) return defaults?.currency(dec) ?? dec.ToString(defaults.GetDefaultCulture()); } if (target.GetType().IsNumericType() || target is bool) return target.ToString(); if (target is DateTime d) return defaults?.dateFormat(d) ?? d.ToString(defaults.GetDefaultCulture()); if (target is TimeSpan t) return defaults?.timeFormat(t) ?? t.ToString(); return target.ToString() ?? ""; } private static bool isComplexType(object first) { return !(first == null || first is string || first.GetType().IsValueType); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using Microsoft.Owin; using Microsoft.Owin.Infrastructure; using Microsoft.Owin.Logging; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Infrastructure; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net.Http; using System.Security.Claims; using System.Threading.Tasks; namespace Aminjam.Owin.Security.Instagram { internal class InstagramAuthenticationHandler : AuthenticationHandler<InstagramAuthenticationOptions> { private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; private const string TokenEndpoint = "https://api.instagram.com/oauth/access_token"; private const string GraphApiEndpoint = "https://graph.facebook.com/me"; private readonly ILogger _logger; private readonly HttpClient _httpClient; public InstagramAuthenticationHandler(HttpClient httpClient, ILogger logger) { _httpClient = httpClient; _logger = logger; } protected override async Task<AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { string code = null; string state = null; IReadableStringCollection query = Request.Query; IList<string> values = query.GetValues("code"); if (values != null && values.Count == 1) { code = values[0]; } values = query.GetValues("state"); if (values != null && values.Count == 1) { state = values[0]; } properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return null; } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties, _logger)) { return new AuthenticationTicket(null, properties); } string requestPrefix = Request.Scheme + "://" + Request.Host; string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath; var postContent = new StringContent("grant_type=authorization_code" + "&code=" + Uri.EscapeDataString(code) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + "&client_id=" + Uri.EscapeDataString(Options.ClientId) + "&client_secret=" + Uri.EscapeDataString(Options.ClientSecret)); // Replace the default content-type so instagram parses postContent postContent.Headers.Remove("Content-Type"); postContent.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); HttpResponseMessage tokenResponse = await _httpClient.PostAsync(TokenEndpoint, postContent, Request.CallCancelled); tokenResponse.EnsureSuccessStatusCode(); string text = await tokenResponse.Content.ReadAsStringAsync(); dynamic form = JObject.Parse(text); string accessToken = form.access_token; JObject user = form.user; var context = new InstagramAuthenticatedContext(Context, user, accessToken) { Identity = new ClaimsIdentity( Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType) }; if (!string.IsNullOrEmpty(context.Id)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.UserName)) { context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.FullName)) { context.Identity.AddClaim(new Claim("urn:instagram:fullName", context.FullName, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.ProfilePicture)) { context.Identity.AddClaim(new Claim("urn:instagram:profilePic", context.ProfilePicture, XmlSchemaString, Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return new AuthenticationTicket(context.Identity, context.Properties); } catch (Exception ex) { _logger.WriteError(ex.Message); } return new AuthenticationTicket(null, properties); } protected override Task ApplyResponseChallengeAsync() { if (Response.StatusCode != 401) { return Task.FromResult<object>(null); } AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode); if (challenge != null) { string baseUri = Request.Scheme + Uri.SchemeDelimiter + Request.Host + Request.PathBase; string currentUri = baseUri + Request.Path + Request.QueryString; string redirectUri = baseUri + Options.CallbackPath; AuthenticationProperties properties = challenge.Properties; if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = currentUri; } // OAuth2 10.12 CSRF GenerateCorrelationId(properties); // comma separated string scope = string.Join("+", Options.Scope); string state = Options.StateDataFormat.Protect(properties); string authorizationEndpoint = "https://api.instagram.com/oauth/authorize/" + "?response_type=code" + "&client_id=" + Uri.EscapeDataString(Options.ClientId) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + "&scope=" + scope + "&state=" + Uri.EscapeDataString(state); Response.Redirect(authorizationEndpoint); } return Task.FromResult<object>(null); } public override async Task<bool> InvokeAsync() { return await InvokeReplyPathAsync(); } private async Task<bool> InvokeReplyPathAsync() { if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path) { // TODO: error responses AuthenticationTicket ticket = await AuthenticateAsync(); if (ticket == null) { _logger.WriteWarning("Invalid return state, unable to redirect."); Response.StatusCode = 500; return true; } var context = new InstagramReturnEndpointContext(Context, ticket); context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType; context.RedirectUri = ticket.Properties.RedirectUri; await Options.Provider.ReturnEndpoint(context); if (context.SignInAsAuthenticationType != null && context.Identity != null) { ClaimsIdentity grantIdentity = context.Identity; if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal)) { grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType); } Context.Authentication.SignIn(context.Properties, grantIdentity); } if (!context.IsRequestCompleted && context.RedirectUri != null) { string redirectUri = context.RedirectUri; if (context.Identity == null) { // add a redirect hint that sign-in failed in some way redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied"); } Response.Redirect(redirectUri); context.RequestCompleted(); } return context.IsRequestCompleted; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Diagnostics; using System.Data.SqlClient; using System.Reflection; namespace System.Data.Common { internal static class DbConnectionStringBuilderUtil { internal static bool ConvertToBoolean(object value) { Debug.Assert(null != value, "ConvertToBoolean(null)"); string svalue = (value as string); if (null != svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no")) return false; else { string tmp = svalue.Trim(); // Remove leading & trailing white space. if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no")) return false; } return Boolean.Parse(svalue); } try { return Convert.ToBoolean(value); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e); } } internal static bool ConvertToIntegratedSecurity(object value) { Debug.Assert(null != value, "ConvertToIntegratedSecurity(null)"); string svalue = (value as string); if (null != svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no")) return false; else { string tmp = svalue.Trim(); // Remove leading & trailing white space. if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no")) return false; } return Boolean.Parse(svalue); } try { return Convert.ToBoolean(value); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e); } } internal static int ConvertToInt32(object value) { try { return Convert.ToInt32(value); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(Int32), e); } } internal static string ConvertToString(object value) { try { return Convert.ToString(value); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(String), e); } } private const string ApplicationIntentReadWriteString = "ReadWrite"; private const string ApplicationIntentReadOnlyString = "ReadOnly"; internal static bool TryConvertToApplicationIntent(string value, out ApplicationIntent result) { Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed"); Debug.Assert(null != value, "TryConvertToApplicationIntent(null,...)"); if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadOnlyString)) { result = ApplicationIntent.ReadOnly; return true; } else if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadWriteString)) { result = ApplicationIntent.ReadWrite; return true; } else { result = DbConnectionStringDefaults.ApplicationIntent; return false; } } internal static bool IsValidApplicationIntentValue(ApplicationIntent value) { Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed"); return value == ApplicationIntent.ReadOnly || value == ApplicationIntent.ReadWrite; } internal static string ApplicationIntentToString(ApplicationIntent value) { Debug.Assert(IsValidApplicationIntentValue(value)); if (value == ApplicationIntent.ReadOnly) { return ApplicationIntentReadOnlyString; } else { return ApplicationIntentReadWriteString; } } /// <summary> /// This method attempts to convert the given value tp ApplicationIntent enum. The algorithm is: /// * if the value is from type string, it will be matched against ApplicationIntent enum names only, using ordinal, case-insensitive comparer /// * if the value is from type ApplicationIntent, it will be used as is /// * if the value is from integral type (SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64), it will be converted to enum /// * if the value is another enum or any other type, it will be blocked with an appropriate ArgumentException /// /// in any case above, if the converted value is out of valid range, the method raises ArgumentOutOfRangeException. /// </summary> /// <returns>application intent value in the valid range</returns> internal static ApplicationIntent ConvertToApplicationIntent(string keyword, object value) { Debug.Assert(null != value, "ConvertToApplicationIntent(null)"); string sValue = (value as string); ApplicationIntent result; if (null != sValue) { // We could use Enum.TryParse<ApplicationIntent> here, but it accepts value combinations like // "ReadOnly, ReadWrite" which are unwelcome here // Also, Enum.TryParse is 100x slower than plain StringComparer.OrdinalIgnoreCase.Equals method. if (TryConvertToApplicationIntent(sValue, out result)) { return result; } // try again after remove leading & trailing whitespaces. sValue = sValue.Trim(); if (TryConvertToApplicationIntent(sValue, out result)) { return result; } // string values must be valid throw ADP.InvalidConnectionOptionValue(keyword); } else { // the value is not string, try other options ApplicationIntent eValue; if (value is ApplicationIntent) { // quick path for the most common case eValue = (ApplicationIntent)value; } else if (value.GetType().GetTypeInfo().IsEnum) { // explicitly block scenarios in which user tries to use wrong enum types, like: // builder["ApplicationIntent"] = EnvironmentVariableTarget.Process; // workaround: explicitly cast non-ApplicationIntent enums to int throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), null); } else { try { // Enum.ToObject allows only integral and enum values (enums are blocked above), raising ArgumentException for the rest eValue = (ApplicationIntent)Enum.ToObject(typeof(ApplicationIntent), value); } catch (ArgumentException e) { // to be consistent with the messages we send in case of wrong type usage, replace // the error with our exception, and keep the original one as inner one for troubleshooting throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), e); } } // ensure value is in valid range if (IsValidApplicationIntentValue(eValue)) { return eValue; } else { throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)eValue); } } } } internal static class DbConnectionStringDefaults { // all // internal const string NamedConnection = ""; // SqlClient internal const ApplicationIntent ApplicationIntent = System.Data.SqlClient.ApplicationIntent.ReadWrite; internal const string ApplicationName = "Core .Net SqlClient Data Provider"; internal const string AttachDBFilename = ""; internal const int ConnectTimeout = 15; internal const string CurrentLanguage = ""; internal const string DataSource = ""; internal const bool Encrypt = false; internal const string FailoverPartner = ""; internal const string InitialCatalog = ""; internal const bool IntegratedSecurity = false; internal const int LoadBalanceTimeout = 0; // default of 0 means don't use internal const bool MultipleActiveResultSets = false; internal const bool MultiSubnetFailover = false; internal const int MaxPoolSize = 100; internal const int MinPoolSize = 0; internal const int PacketSize = 8000; internal const string Password = ""; internal const bool PersistSecurityInfo = false; internal const bool Pooling = true; internal const bool TrustServerCertificate = false; internal const string TypeSystemVersion = "Latest"; internal const string UserID = ""; internal const bool UserInstance = false; internal const bool Replication = false; internal const string WorkstationID = ""; internal const string TransactionBinding = "Implicit Unbind"; internal const int ConnectRetryCount = 1; internal const int ConnectRetryInterval = 10; } internal static class DbConnectionStringKeywords { // all // internal const string NamedConnection = "Named Connection"; // SqlClient internal const string ApplicationIntent = "ApplicationIntent"; internal const string ApplicationName = "Application Name"; internal const string AsynchronousProcessing = "Asynchronous Processing"; internal const string AttachDBFilename = "AttachDbFilename"; internal const string ConnectTimeout = "Connect Timeout"; internal const string ConnectionReset = "Connection Reset"; internal const string ContextConnection = "Context Connection"; internal const string CurrentLanguage = "Current Language"; internal const string Encrypt = "Encrypt"; internal const string FailoverPartner = "Failover Partner"; internal const string InitialCatalog = "Initial Catalog"; internal const string MultipleActiveResultSets = "MultipleActiveResultSets"; internal const string MultiSubnetFailover = "MultiSubnetFailover"; internal const string NetworkLibrary = "Network Library"; internal const string PacketSize = "Packet Size"; internal const string Replication = "Replication"; internal const string TransactionBinding = "Transaction Binding"; internal const string TrustServerCertificate = "TrustServerCertificate"; internal const string TypeSystemVersion = "Type System Version"; internal const string UserInstance = "User Instance"; internal const string WorkstationID = "Workstation ID"; internal const string ConnectRetryCount = "ConnectRetryCount"; internal const string ConnectRetryInterval = "ConnectRetryInterval"; // common keywords (OleDb, OracleClient, SqlClient) internal const string DataSource = "Data Source"; internal const string IntegratedSecurity = "Integrated Security"; internal const string Password = "Password"; internal const string PersistSecurityInfo = "Persist Security Info"; internal const string UserID = "User ID"; // managed pooling (OracleClient, SqlClient) internal const string Enlist = "Enlist"; internal const string LoadBalanceTimeout = "Load Balance Timeout"; internal const string MaxPoolSize = "Max Pool Size"; internal const string Pooling = "Pooling"; internal const string MinPoolSize = "Min Pool Size"; } internal static class DbConnectionStringSynonyms { //internal const string AsynchronousProcessing = Async; internal const string Async = "async"; //internal const string ApplicationName = APP; internal const string APP = "app"; //internal const string AttachDBFilename = EXTENDEDPROPERTIES+","+INITIALFILENAME; internal const string EXTENDEDPROPERTIES = "extended properties"; internal const string INITIALFILENAME = "initial file name"; //internal const string ConnectTimeout = CONNECTIONTIMEOUT+","+TIMEOUT; internal const string CONNECTIONTIMEOUT = "connection timeout"; internal const string TIMEOUT = "timeout"; //internal const string CurrentLanguage = LANGUAGE; internal const string LANGUAGE = "language"; //internal const string OraDataSource = SERVER; //internal const string SqlDataSource = ADDR+","+ADDRESS+","+SERVER+","+NETWORKADDRESS; internal const string ADDR = "addr"; internal const string ADDRESS = "address"; internal const string SERVER = "server"; internal const string NETWORKADDRESS = "network address"; //internal const string InitialCatalog = DATABASE; internal const string DATABASE = "database"; //internal const string IntegratedSecurity = TRUSTEDCONNECTION; internal const string TRUSTEDCONNECTION = "trusted_connection"; // underscore introduced in everett //internal const string LoadBalanceTimeout = ConnectionLifetime; internal const string ConnectionLifetime = "connection lifetime"; //internal const string NetworkLibrary = NET+","+NETWORK; internal const string NET = "net"; internal const string NETWORK = "network"; //internal const string Password = Pwd; internal const string Pwd = "pwd"; //internal const string PersistSecurityInfo = PERSISTSECURITYINFO; internal const string PERSISTSECURITYINFO = "persistsecurityinfo"; //internal const string UserID = UID+","+User; internal const string UID = "uid"; internal const string User = "user"; //internal const string WorkstationID = WSID; internal const string WSID = "wsid"; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed partial class CSharpFormatter : Formatter { private void AppendEnumTypeAndName(StringBuilder builder, Type typeToDisplayOpt, string name) { if (typeToDisplayOpt != null) { // We're showing the type of a value, so "dynamic" does not apply. bool unused; int index = 0; AppendQualifiedTypeName(builder, typeToDisplayOpt, default(DynamicFlagsCustomTypeInfo), ref index, escapeKeywordIdentifiers: true, sawInvalidIdentifier: out unused); builder.Append('.'); AppendIdentifierEscapingPotentialKeywords(builder, name, sawInvalidIdentifier: out unused); } else { builder.Append(name); } } internal override string GetArrayDisplayString(Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options) { Debug.Assert(lmrType.IsArray); Type originalLmrType = lmrType; // Strip off all array types. We'll process them at the end. while (lmrType.IsArray) { lmrType = lmrType.GetElementType(); } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append('{'); // We're showing the type of a value, so "dynamic" does not apply. bool unused; builder.Append(GetTypeName(new TypeAndCustomInfo(lmrType), escapeKeywordIdentifiers: false, sawInvalidIdentifier: out unused)); // NOTE: call our impl directly, since we're coupled anyway. var numSizes = sizes.Count; builder.Append('['); for (int i = 0; i < numSizes; i++) { if (i > 0) { builder.Append(", "); } var lowerBound = lowerBounds[i]; var size = sizes[i]; if (lowerBound == 0) { builder.Append(FormatLiteral(size, options)); } else { builder.Append(FormatLiteral(lowerBound, options)); builder.Append(".."); builder.Append(FormatLiteral(size + lowerBound - 1, options)); } } builder.Append(']'); lmrType = originalLmrType.GetElementType(); // Strip off one layer (already handled). while (lmrType.IsArray) { builder.Append('['); builder.Append(',', lmrType.GetArrayRank() - 1); builder.Append(']'); lmrType = lmrType.GetElementType(); } builder.Append('}'); return pooled.ToStringAndFree(); } internal override string GetArrayIndexExpression(int[] indices) { Debug.Assert(indices != null); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append('['); bool any = false; foreach (var index in indices) { if (any) { builder.Append(", "); } builder.Append(index); any = true; } builder.Append(']'); return pooled.ToStringAndFree(); } internal override string GetCastExpression(string argument, string type, bool parenthesizeArgument = false, bool parenthesizeEntireExpression = false) { Debug.Assert(!string.IsNullOrEmpty(argument)); Debug.Assert(!string.IsNullOrEmpty(type)); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; if (parenthesizeEntireExpression) { builder.Append('('); } var castExpressionFormat = parenthesizeArgument ? "({0})({1})" : "({0}){1}"; builder.AppendFormat(castExpressionFormat, type, argument); if (parenthesizeEntireExpression) { builder.Append(')'); } return pooled.ToStringAndFree(); } internal override string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt) { var usedFields = ArrayBuilder<EnumField>.GetInstance(); FillUsedEnumFields(usedFields, fields, underlyingValue); if (usedFields.Count == 0) { return null; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; for (int i = usedFields.Count - 1; i >= 0; i--) // Backwards to list smallest first. { AppendEnumTypeAndName(builder, typeToDisplayOpt, usedFields[i].Name); if (i > 0) { builder.Append(" | "); } } usedFields.Free(); return pooled.ToStringAndFree(); } internal override string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt) { foreach (var field in fields) { // First match wins (deterministic since sorted). if (underlyingValue == field.Value) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; AppendEnumTypeAndName(builder, typeToDisplayOpt, field.Name); return pooled.ToStringAndFree(); } } return null; } internal override string GetObjectCreationExpression(string type, string arguments) { Debug.Assert(!string.IsNullOrEmpty(type)); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append("new "); builder.Append(type); builder.Append('('); builder.Append(arguments); builder.Append(')'); return pooled.ToStringAndFree(); } internal override string FormatLiteral(char c, ObjectDisplayOptions options) { return ObjectDisplay.FormatLiteral(c, options); } internal override string FormatLiteral(int value, ObjectDisplayOptions options) { return ObjectDisplay.FormatLiteral(value, options & ~ObjectDisplayOptions.UseQuotes); } internal override string FormatPrimitiveObject(object value, ObjectDisplayOptions options) { return ObjectDisplay.FormatPrimitive(value, options); } internal override string FormatString(string str, ObjectDisplayOptions options) { return ObjectDisplay.FormatString(str, useQuotes: options.IncludesOption(ObjectDisplayOptions.UseQuotes)); } } }
// 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.Globalization; using System.IO; using System.Text; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return EnumerableHelpers.ToArray(EnumerateProcessIds()); } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { ThrowIfRemoteMachine(machineName); int[] procIds = GetProcessIds(machineName); // Iterate through all process IDs to load information about each process var reusableReader = new ReusableTextReader(); var processes = new List<ProcessInfo>(procIds.Length); foreach (int pid in procIds) { ProcessInfo pi = CreateProcessInfo(pid, reusableReader); if (pi != null) { processes.Add(pi); } } return processes.ToArray(); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> internal static ModuleInfo[] GetModuleInfos(int processId) { var modules = new List<ModuleInfo>(); // Process from the parsed maps file each entry representing a module foreach (Interop.procfs.ParsedMapsModule entry in Interop.procfs.ParseMapsModules(processId)) { int sizeOfImage = (int)(entry.AddressRange.Value - entry.AddressRange.Key); // A single module may be split across multiple map entries; consolidate based on // the name and address ranges of sequential entries. if (modules.Count > 0) { ModuleInfo mi = modules[modules.Count - 1]; if (mi._fileName == entry.FileName && ((long)mi._baseOfDll + mi._sizeOfImage == entry.AddressRange.Key)) { // Merge this entry with the previous one modules[modules.Count - 1]._sizeOfImage += sizeOfImage; continue; } } // It's not a continuation of a previous entry but a new one: add it. modules.Add(new ModuleInfo() { _fileName = entry.FileName, _baseName = Path.GetFileName(entry.FileName), _baseOfDll = new IntPtr(entry.AddressRange.Key), _sizeOfImage = sizeOfImage, _entryPoint = IntPtr.Zero // unknown }); } // Return the set of modules found return modules.ToArray(); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// Creates a ProcessInfo from the specified process ID. /// </summary> internal static ProcessInfo CreateProcessInfo(int pid, ReusableTextReader reusableReader = null) { if (reusableReader == null) { reusableReader = new ReusableTextReader(); } Interop.procfs.ParsedStat stat; return Interop.procfs.TryReadStatFile(pid, out stat, reusableReader) ? CreateProcessInfo(stat, reusableReader) : null; } /// <summary> /// Creates a ProcessInfo from the data parsed from a /proc/pid/stat file and the associated tasks directory. /// </summary> internal static ProcessInfo CreateProcessInfo(Interop.procfs.ParsedStat procFsStat, ReusableTextReader reusableReader) { int pid = procFsStat.pid; var pi = new ProcessInfo() { ProcessId = pid, ProcessName = procFsStat.comm, BasePriority = (int)procFsStat.nice, VirtualBytes = (long)procFsStat.vsize, WorkingSet = procFsStat.rss, SessionId = procFsStat.session, // We don't currently fill in the other values. // A few of these could probably be filled in from getrusage, // but only for the current process or its children, not for // arbitrary other processes. }; // Then read through /proc/pid/task/ to find each thread in the process... string tasksDir = Interop.procfs.GetTaskDirectoryPathForProcess(pid); try { foreach (string taskDir in Directory.EnumerateDirectories(tasksDir)) { // ...and read its associated /proc/pid/task/tid/stat file to create a ThreadInfo string dirName = Path.GetFileName(taskDir); int tid; Interop.procfs.ParsedStat stat; if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid) && Interop.procfs.TryReadStatFile(pid, tid, out stat, reusableReader)) { pi._threadInfoList.Add(new ThreadInfo() { _processId = pid, _threadId = (ulong)tid, _basePriority = pi.BasePriority, _currentPriority = (int)stat.nice, _startAddress = (IntPtr)stat.startstack, _threadState = ProcFsStateToThreadState(stat.state), _threadWaitReason = ThreadWaitReason.Unknown }); } } } catch (IOException) { // Between the time that we get an ID and the time that we try to read the associated // directories and files in procfs, the process could be gone. } // Finally return what we've built up return pi; } // ---------------------------------- // ---- Unix PAL layer ends here ---- // ---------------------------------- /// <summary>Enumerates the IDs of all processes on the current machine.</summary> internal static IEnumerable<int> EnumerateProcessIds() { // Parse /proc for any directory that's named with a number. Each such // directory represents a process. foreach (string procDir in Directory.EnumerateDirectories(Interop.procfs.RootPath)) { string dirName = Path.GetFileName(procDir); int pid; if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out pid)) { Debug.Assert(pid >= 0); yield return pid; } } } /// <summary>Gets a ThreadState to represent the value returned from the status field of /proc/pid/stat.</summary> /// <param name="c">The status field value.</param> /// <returns></returns> private static ThreadState ProcFsStateToThreadState(char c) { switch (c) { case 'R': return ThreadState.Running; case 'S': case 'D': case 'T': return ThreadState.Wait; case 'Z': return ThreadState.Terminated; case 'W': return ThreadState.Transition; default: Debug.Fail("Unexpected status character"); return ThreadState.Unknown; } } } }
/* * 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 Lucene.Net.Analysis.Tokenattributes; using NUnit.Framework; using Analyzer = Lucene.Net.Analysis.Analyzer; using TokenStream = Lucene.Net.Analysis.TokenStream; using Tokenizer = Lucene.Net.Analysis.Tokenizer; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search { [TestFixture] public class TestTermRangeQuery:LuceneTestCase { private int docCount = 0; private RAMDirectory dir; [SetUp] public override void SetUp() { base.SetUp(); dir = new RAMDirectory(); } [Test] public virtual void TestExclusive() { Query query = new TermRangeQuery("content", "A", "C", false, false); InitializeIndex(new System.String[]{"A", "B", "C", "D"}); IndexSearcher searcher = new IndexSearcher(dir, true); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length, "A,B,C,D, only B in range"); searcher.Close(); InitializeIndex(new System.String[]{"A", "B", "D"}); searcher = new IndexSearcher(dir, true); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length, "A,B,D, only B in range"); searcher.Close(); AddDoc("C"); searcher = new IndexSearcher(dir, true); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length, "C added, still only B in range"); searcher.Close(); } [Test] public virtual void TestInclusive() { Query query = new TermRangeQuery("content", "A", "C", true, true); InitializeIndex(new System.String[]{"A", "B", "C", "D"}); IndexSearcher searcher = new IndexSearcher(dir, true); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length, "A,B,C,D - A,B,C in range"); searcher.Close(); InitializeIndex(new System.String[]{"A", "B", "D"}); searcher = new IndexSearcher(dir, true); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length, "A,B,D - A and B in range"); searcher.Close(); AddDoc("C"); searcher = new IndexSearcher(dir, true); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length, "C added - A, B, C in range"); searcher.Close(); } [Test] public virtual void TestEqualsHashcode() { Query query = new TermRangeQuery("content", "A", "C", true, true); query.Boost = 1.0f; Query other = new TermRangeQuery("content", "A", "C", true, true); other.Boost = 1.0f; Assert.AreEqual(query, query, "query equals itself is true"); Assert.AreEqual(query, other, "equivalent queries are equal"); Assert.AreEqual(query.GetHashCode(), other.GetHashCode(), "hashcode must return same value when equals is true"); other.Boost = 2.0f; Assert.IsFalse(query.Equals(other), "Different boost queries are not equal"); other = new TermRangeQuery("notcontent", "A", "C", true, true); Assert.IsFalse(query.Equals(other), "Different fields are not equal"); other = new TermRangeQuery("content", "X", "C", true, true); Assert.IsFalse(query.Equals(other), "Different lower terms are not equal"); other = new TermRangeQuery("content", "A", "Z", true, true); Assert.IsFalse(query.Equals(other), "Different upper terms are not equal"); query = new TermRangeQuery("content", null, "C", true, true); other = new TermRangeQuery("content", null, "C", true, true); Assert.AreEqual(query, other, "equivalent queries with null lowerterms are equal()"); Assert.AreEqual(query.GetHashCode(), other.GetHashCode(), "hashcode must return same value when equals is true"); query = new TermRangeQuery("content", "C", null, true, true); other = new TermRangeQuery("content", "C", null, true, true); Assert.AreEqual(query, other, "equivalent queries with null upperterms are equal()"); Assert.AreEqual(query.GetHashCode(), other.GetHashCode(), "hashcode returns same value"); query = new TermRangeQuery("content", null, "C", true, true); other = new TermRangeQuery("content", "C", null, true, true); Assert.IsFalse(query.Equals(other), "queries with different upper and lower terms are not equal"); query = new TermRangeQuery("content", "A", "C", false, false); other = new TermRangeQuery("content", "A", "C", true, true); Assert.IsFalse(query.Equals(other), "queries with different inclusive are not equal"); query = new TermRangeQuery("content", "A", "C", false, false); other = new TermRangeQuery("content", "A", "C", false, false, System.Globalization.CultureInfo.CurrentCulture.CompareInfo); Assert.IsFalse(query.Equals(other), "a query with a collator is not equal to one without"); } [Test] public virtual void TestExclusiveCollating() { Query query = new TermRangeQuery("content", "A", "C", false, false, new System.Globalization.CultureInfo("en").CompareInfo); InitializeIndex(new System.String[]{"A", "B", "C", "D"}); IndexSearcher searcher = new IndexSearcher(dir, true); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length, "A,B,C,D, only B in range"); searcher.Close(); InitializeIndex(new System.String[]{"A", "B", "D"}); searcher = new IndexSearcher(dir, true); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length, "A,B,D, only B in range"); searcher.Close(); AddDoc("C"); searcher = new IndexSearcher(dir, true); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length, "C added, still only B in range"); searcher.Close(); } [Test] public virtual void TestInclusiveCollating() { Query query = new TermRangeQuery("content", "A", "C", true, true, new System.Globalization.CultureInfo("en").CompareInfo); InitializeIndex(new System.String[]{"A", "B", "C", "D"}); IndexSearcher searcher = new IndexSearcher(dir, true); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length, "A,B,C,D - A,B,C in range"); searcher.Close(); InitializeIndex(new System.String[]{"A", "B", "D"}); searcher = new IndexSearcher(dir, true); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length, "A,B,D - A and B in range"); searcher.Close(); AddDoc("C"); searcher = new IndexSearcher(dir, true); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length, "C added - A, B, C in range"); searcher.Close(); } [Test] public virtual void TestFarsi() { // Neither Java 1.4.2 nor 1.5.0 has Farsi Locale collation available in // RuleBasedCollator. However, the Arabic Locale seems to order the Farsi // characters properly. System.Globalization.CompareInfo collator = new System.Globalization.CultureInfo("ar").CompareInfo; Query query = new TermRangeQuery("content", "\u062F", "\u0698", true, true, collator); // Unicode order would include U+0633 in [ U+062F - U+0698 ], but Farsi // orders the U+0698 character before the U+0633 character, so the single // index Term below should NOT be returned by a TermRangeQuery with a Farsi // Collator (or an Arabic one for the case when Farsi is not supported). InitializeIndex(new System.String[]{"\u0633\u0627\u0628"}); IndexSearcher searcher = new IndexSearcher(dir, true); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length, "The index Term should not be included."); query = new TermRangeQuery("content", "\u0633", "\u0638", true, true, collator); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length, "The index Term should be included."); searcher.Close(); } [Test] public virtual void TestDanish() { System.Globalization.CompareInfo collator = new System.Globalization.CultureInfo("da" + "-" + "dk").CompareInfo; // Danish collation orders the words below in the given order (example taken // from TestSort.testInternationalSort() ). System.String[] words = new System.String[]{"H\u00D8T", "H\u00C5T", "MAND"}; Query query = new TermRangeQuery("content", "H\u00D8T", "MAND", false, false, collator); // Unicode order would not include "H\u00C5T" in [ "H\u00D8T", "MAND" ], // but Danish collation does. InitializeIndex(words); IndexSearcher searcher = new IndexSearcher(dir, true); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length, "The index Term should be included."); query = new TermRangeQuery("content", "H\u00C5T", "MAND", false, false, collator); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length, "The index Term should not be included."); searcher.Close(); } private class SingleCharAnalyzer:Analyzer { private class SingleCharTokenizer:Tokenizer { internal char[] buffer = new char[1]; internal bool done; internal ITermAttribute termAtt; public SingleCharTokenizer(System.IO.TextReader r):base(r) { termAtt = AddAttribute<ITermAttribute>(); } public override bool IncrementToken() { int count = input.Read(buffer, 0, buffer.Length); if (done) return false; else { ClearAttributes(); done = true; if (count == 1) { termAtt.TermBuffer()[0] = buffer[0]; termAtt.SetTermLength(1); } else termAtt.SetTermLength(0); return true; } } public override void Reset(System.IO.TextReader reader) { base.Reset(reader); done = false; } } public override TokenStream ReusableTokenStream(System.String fieldName, System.IO.TextReader reader) { Tokenizer tokenizer = (Tokenizer) PreviousTokenStream; if (tokenizer == null) { tokenizer = new SingleCharTokenizer(reader); PreviousTokenStream = tokenizer; } else tokenizer.Reset(reader); return tokenizer; } public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader) { return new SingleCharTokenizer(reader); } } private void InitializeIndex(System.String[] values) { InitializeIndex(values, new WhitespaceAnalyzer()); } private void InitializeIndex(System.String[] values, Analyzer analyzer) { IndexWriter writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED); for (int i = 0; i < values.Length; i++) { InsertDoc(writer, values[i]); } writer.Close(); } private void AddDoc(System.String content) { IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.LIMITED); InsertDoc(writer, content); writer.Close(); } private void InsertDoc(IndexWriter writer, System.String content) { Document doc = new Document(); doc.Add(new Field("id", "id" + docCount, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("content", content, Field.Store.NO, Field.Index.ANALYZED)); writer.AddDocument(doc); docCount++; } // LUCENE-38 [Test] public virtual void TestExclusiveLowerNull() { Analyzer analyzer = new SingleCharAnalyzer(); //http://issues.apache.org/jira/browse/LUCENE-38 Query query = new TermRangeQuery("content", null, "C", false, false); InitializeIndex(new System.String[]{"A", "B", "", "C", "D"}, analyzer); IndexSearcher searcher = new IndexSearcher(dir, true); int numHits = searcher.Search(query, null, 1000).TotalHits; // When Lucene-38 is fixed, use the assert on the next line: Assert.AreEqual(3, numHits, "A,B,<empty string>,C,D => A, B & <empty string> are in range"); // until Lucene-38 is fixed, use this assert: //Assert.AreEqual(2, hits.length(),"A,B,<empty string>,C,D => A, B & <empty string> are in range"); searcher.Close(); InitializeIndex(new System.String[]{"A", "B", "", "D"}, analyzer); searcher = new IndexSearcher(dir, true); numHits = searcher.Search(query, null, 1000).TotalHits; // When Lucene-38 is fixed, use the assert on the next line: Assert.AreEqual(3, numHits, "A,B,<empty string>,D => A, B & <empty string> are in range"); // until Lucene-38 is fixed, use this assert: //Assert.AreEqual(2, hits.length(), "A,B,<empty string>,D => A, B & <empty string> are in range"); searcher.Close(); AddDoc("C"); searcher = new IndexSearcher(dir, true); numHits = searcher.Search(query, null, 1000).TotalHits; // When Lucene-38 is fixed, use the assert on the next line: Assert.AreEqual(3, numHits, "C added, still A, B & <empty string> are in range"); // until Lucene-38 is fixed, use this assert //Assert.AreEqual(2, hits.length(), "C added, still A, B & <empty string> are in range"); searcher.Close(); } // LUCENE-38 [Test] public virtual void TestInclusiveLowerNull() { //http://issues.apache.org/jira/browse/LUCENE-38 Analyzer analyzer = new SingleCharAnalyzer(); Query query = new TermRangeQuery("content", null, "C", true, true); InitializeIndex(new System.String[]{"A", "B", "", "C", "D"}, analyzer); IndexSearcher searcher = new IndexSearcher(dir, true); int numHits = searcher.Search(query, null, 1000).TotalHits; // When Lucene-38 is fixed, use the assert on the next line: Assert.AreEqual(4, numHits, "A,B,<empty string>,C,D => A,B,<empty string>,C in range"); // until Lucene-38 is fixed, use this assert //Assert.AreEqual(3, hits.length(), "A,B,<empty string>,C,D => A,B,<empty string>,C in range"); searcher.Close(); InitializeIndex(new System.String[]{"A", "B", "", "D"}, analyzer); searcher = new IndexSearcher(dir, true); numHits = searcher.Search(query, null, 1000).TotalHits; // When Lucene-38 is fixed, use the assert on the next line: Assert.AreEqual(3, numHits, "A,B,<empty string>,D - A, B and <empty string> in range"); // until Lucene-38 is fixed, use this assert //Assert.AreEqual(2, hits.length(), "A,B,<empty string>,D => A, B and <empty string> in range"); searcher.Close(); AddDoc("C"); searcher = new IndexSearcher(dir, true); numHits = searcher.Search(query, null, 1000).TotalHits; // When Lucene-38 is fixed, use the assert on the next line: Assert.AreEqual(4, numHits, "C added => A,B,<empty string>,C in range"); // until Lucene-38 is fixed, use this assert //Assert.AreEqual(3, hits.length(), "C added => A,B,<empty string>,C in range"); searcher.Close(); } } }
/* * 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.Runtime.Remoting.Lifetime; using System.Threading; using System.Reflection; using System.Collections; using System.Collections.Generic; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass : MarshalByRefObject { public ILSL_Api m_LSL_Functions; public void ApiTypeLSL(IScriptApi api) { if (!(api is ILSL_Api)) return; m_LSL_Functions = (ILSL_Api)api; } public void state(string newState) { m_LSL_Functions.state(newState); } // // Script functions // public LSL_Integer llAbs(int i) { return m_LSL_Functions.llAbs(i); } public LSL_Float llAcos(double val) { return m_LSL_Functions.llAcos(val); } public void llAddToLandBanList(string avatar, double hours) { m_LSL_Functions.llAddToLandBanList(avatar, hours); } public void llAddToLandPassList(string avatar, double hours) { m_LSL_Functions.llAddToLandPassList(avatar, hours); } public void llAdjustSoundVolume(double volume) { m_LSL_Functions.llAdjustSoundVolume(volume); } public void llAllowInventoryDrop(int add) { m_LSL_Functions.llAllowInventoryDrop(add); } public LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b) { return m_LSL_Functions.llAngleBetween(a, b); } public void llApplyImpulse(LSL_Vector force, int local) { m_LSL_Functions.llApplyImpulse(force, local); } public void llApplyRotationalImpulse(LSL_Vector force, int local) { m_LSL_Functions.llApplyRotationalImpulse(force, local); } public LSL_Float llAsin(double val) { return m_LSL_Functions.llAsin(val); } public LSL_Float llAtan2(double x, double y) { return m_LSL_Functions.llAtan2(x, y); } public void llAttachToAvatar(int attachment) { m_LSL_Functions.llAttachToAvatar(attachment); } public LSL_Key llAvatarOnSitTarget() { return m_LSL_Functions.llAvatarOnSitTarget(); } public LSL_Key llAvatarOnLinkSitTarget(int linknum) { return m_LSL_Functions.llAvatarOnLinkSitTarget(linknum); } public LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up) { return m_LSL_Functions.llAxes2Rot(fwd, left, up); } public LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle) { return m_LSL_Functions.llAxisAngle2Rot(axis, angle); } public LSL_Integer llBase64ToInteger(string str) { return m_LSL_Functions.llBase64ToInteger(str); } public LSL_String llBase64ToString(string str) { return m_LSL_Functions.llBase64ToString(str); } public void llBreakAllLinks() { m_LSL_Functions.llBreakAllLinks(); } public void llBreakLink(int linknum) { m_LSL_Functions.llBreakLink(linknum); } public LSL_Integer llCeil(double f) { return m_LSL_Functions.llCeil(f); } public void llClearCameraParams() { m_LSL_Functions.llClearCameraParams(); } public void llCloseRemoteDataChannel(string channel) { m_LSL_Functions.llCloseRemoteDataChannel(channel); } public LSL_Float llCloud(LSL_Vector offset) { return m_LSL_Functions.llCloud(offset); } public void llCollisionFilter(string name, string id, int accept) { m_LSL_Functions.llCollisionFilter(name, id, accept); } public void llCollisionSound(string impact_sound, double impact_volume) { m_LSL_Functions.llCollisionSound(impact_sound, impact_volume); } public void llCollisionSprite(string impact_sprite) { m_LSL_Functions.llCollisionSprite(impact_sprite); } public LSL_Float llCos(double f) { return m_LSL_Functions.llCos(f); } public void llCreateLink(string target, int parent) { m_LSL_Functions.llCreateLink(target, parent); } public LSL_List llCSV2List(string src) { return m_LSL_Functions.llCSV2List(src); } public LSL_List llDeleteSubList(LSL_List src, int start, int end) { return m_LSL_Functions.llDeleteSubList(src, start, end); } public LSL_String llDeleteSubString(string src, int start, int end) { return m_LSL_Functions.llDeleteSubString(src, start, end); } public void llDetachFromAvatar() { m_LSL_Functions.llDetachFromAvatar(); } public LSL_Vector llDetectedGrab(int number) { return m_LSL_Functions.llDetectedGrab(number); } public LSL_Integer llDetectedGroup(int number) { return m_LSL_Functions.llDetectedGroup(number); } public LSL_Key llDetectedKey(int number) { return m_LSL_Functions.llDetectedKey(number); } public LSL_Integer llDetectedLinkNumber(int number) { return m_LSL_Functions.llDetectedLinkNumber(number); } public LSL_String llDetectedName(int number) { return m_LSL_Functions.llDetectedName(number); } public LSL_Key llDetectedOwner(int number) { return m_LSL_Functions.llDetectedOwner(number); } public LSL_Vector llDetectedPos(int number) { return m_LSL_Functions.llDetectedPos(number); } public LSL_Rotation llDetectedRot(int number) { return m_LSL_Functions.llDetectedRot(number); } public LSL_Integer llDetectedType(int number) { return m_LSL_Functions.llDetectedType(number); } public LSL_Vector llDetectedTouchBinormal(int index) { return m_LSL_Functions.llDetectedTouchBinormal(index); } public LSL_Integer llDetectedTouchFace(int index) { return m_LSL_Functions.llDetectedTouchFace(index); } public LSL_Vector llDetectedTouchNormal(int index) { return m_LSL_Functions.llDetectedTouchNormal(index); } public LSL_Vector llDetectedTouchPos(int index) { return m_LSL_Functions.llDetectedTouchPos(index); } public LSL_Vector llDetectedTouchST(int index) { return m_LSL_Functions.llDetectedTouchST(index); } public LSL_Vector llDetectedTouchUV(int index) { return m_LSL_Functions.llDetectedTouchUV(index); } public LSL_Vector llDetectedVel(int number) { return m_LSL_Functions.llDetectedVel(number); } public void llDialog(string avatar, string message, LSL_List buttons, int chat_channel) { m_LSL_Functions.llDialog(avatar, message, buttons, chat_channel); } public void llDie() { m_LSL_Functions.llDie(); } public LSL_String llDumpList2String(LSL_List src, string seperator) { return m_LSL_Functions.llDumpList2String(src, seperator); } public LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir) { return m_LSL_Functions.llEdgeOfWorld(pos, dir); } public void llEjectFromLand(string pest) { m_LSL_Functions.llEjectFromLand(pest); } public void llEmail(string address, string subject, string message) { m_LSL_Functions.llEmail(address, subject, message); } public LSL_String llEscapeURL(string url) { return m_LSL_Functions.llEscapeURL(url); } public LSL_Rotation llEuler2Rot(LSL_Vector v) { return m_LSL_Functions.llEuler2Rot(v); } public LSL_Float llFabs(double f) { return m_LSL_Functions.llFabs(f); } public LSL_Integer llFloor(double f) { return m_LSL_Functions.llFloor(f); } public void llForceMouselook(int mouselook) { m_LSL_Functions.llForceMouselook(mouselook); } public LSL_Float llFrand(double mag) { return m_LSL_Functions.llFrand(mag); } public LSL_Key llGenerateKey() { return m_LSL_Functions.llGenerateKey(); } public LSL_Vector llGetAccel() { return m_LSL_Functions.llGetAccel(); } public LSL_Integer llGetAgentInfo(string id) { return m_LSL_Functions.llGetAgentInfo(id); } public LSL_String llGetAgentLanguage(string id) { return m_LSL_Functions.llGetAgentLanguage(id); } public LSL_List llGetAgentList(LSL_Integer scope, LSL_List options) { return m_LSL_Functions.llGetAgentList(scope, options); } public LSL_Vector llGetAgentSize(string id) { return m_LSL_Functions.llGetAgentSize(id); } public LSL_Float llGetAlpha(int face) { return m_LSL_Functions.llGetAlpha(face); } public LSL_Float llGetAndResetTime() { return m_LSL_Functions.llGetAndResetTime(); } public LSL_String llGetAnimation(string id) { return m_LSL_Functions.llGetAnimation(id); } public LSL_List llGetAnimationList(string id) { return m_LSL_Functions.llGetAnimationList(id); } public LSL_Integer llGetAttached() { return m_LSL_Functions.llGetAttached(); } public LSL_List llGetBoundingBox(string obj) { return m_LSL_Functions.llGetBoundingBox(obj); } public LSL_Vector llGetCameraPos() { return m_LSL_Functions.llGetCameraPos(); } public LSL_Rotation llGetCameraRot() { return m_LSL_Functions.llGetCameraRot(); } public LSL_Vector llGetCenterOfMass() { return m_LSL_Functions.llGetCenterOfMass(); } public LSL_Vector llGetColor(int face) { return m_LSL_Functions.llGetColor(face); } public LSL_String llGetCreator() { return m_LSL_Functions.llGetCreator(); } public LSL_String llGetDate() { return m_LSL_Functions.llGetDate(); } public LSL_Float llGetEnergy() { return m_LSL_Functions.llGetEnergy(); } public LSL_Vector llGetForce() { return m_LSL_Functions.llGetForce(); } public LSL_Integer llGetFreeMemory() { return m_LSL_Functions.llGetFreeMemory(); } public LSL_Integer llGetFreeURLs() { return m_LSL_Functions.llGetFreeURLs(); } public LSL_Vector llGetGeometricCenter() { return m_LSL_Functions.llGetGeometricCenter(); } public LSL_Float llGetGMTclock() { return m_LSL_Functions.llGetGMTclock(); } public LSL_String llGetHTTPHeader(LSL_Key request_id, string header) { return m_LSL_Functions.llGetHTTPHeader(request_id, header); } public LSL_Key llGetInventoryCreator(string item) { return m_LSL_Functions.llGetInventoryCreator(item); } public LSL_Key llGetInventoryKey(string name) { return m_LSL_Functions.llGetInventoryKey(name); } public LSL_String llGetInventoryName(int type, int number) { return m_LSL_Functions.llGetInventoryName(type, number); } public LSL_Integer llGetInventoryNumber(int type) { return m_LSL_Functions.llGetInventoryNumber(type); } public LSL_Integer llGetInventoryPermMask(string item, int mask) { return m_LSL_Functions.llGetInventoryPermMask(item, mask); } public LSL_Integer llGetInventoryType(string name) { return m_LSL_Functions.llGetInventoryType(name); } public LSL_Key llGetKey() { return m_LSL_Functions.llGetKey(); } public LSL_Key llGetLandOwnerAt(LSL_Vector pos) { return m_LSL_Functions.llGetLandOwnerAt(pos); } public LSL_Key llGetLinkKey(int linknum) { return m_LSL_Functions.llGetLinkKey(linknum); } public LSL_String llGetLinkName(int linknum) { return m_LSL_Functions.llGetLinkName(linknum); } public LSL_Integer llGetLinkNumber() { return m_LSL_Functions.llGetLinkNumber(); } public LSL_Integer llGetLinkNumberOfSides(int link) { return m_LSL_Functions.llGetLinkNumberOfSides(link); } public LSL_Integer llGetListEntryType(LSL_List src, int index) { return m_LSL_Functions.llGetListEntryType(src, index); } public LSL_Integer llGetListLength(LSL_List src) { return m_LSL_Functions.llGetListLength(src); } public LSL_Vector llGetLocalPos() { return m_LSL_Functions.llGetLocalPos(); } public LSL_Rotation llGetLocalRot() { return m_LSL_Functions.llGetLocalRot(); } public LSL_Float llGetMass() { return m_LSL_Functions.llGetMass(); } public LSL_Integer llGetMemoryLimit() { return m_LSL_Functions.llGetMemoryLimit(); } public void llGetNextEmail(string address, string subject) { m_LSL_Functions.llGetNextEmail(address, subject); } public LSL_String llGetNotecardLine(string name, int line) { return m_LSL_Functions.llGetNotecardLine(name, line); } public LSL_Key llGetNumberOfNotecardLines(string name) { return m_LSL_Functions.llGetNumberOfNotecardLines(name); } public LSL_Integer llGetNumberOfPrims() { return m_LSL_Functions.llGetNumberOfPrims(); } public LSL_Integer llGetNumberOfSides() { return m_LSL_Functions.llGetNumberOfSides(); } public LSL_String llGetObjectDesc() { return m_LSL_Functions.llGetObjectDesc(); } public LSL_List llGetObjectDetails(string id, LSL_List args) { return m_LSL_Functions.llGetObjectDetails(id, args); } public LSL_Float llGetObjectMass(string id) { return m_LSL_Functions.llGetObjectMass(id); } public LSL_String llGetObjectName() { return m_LSL_Functions.llGetObjectName(); } public LSL_Integer llGetObjectPermMask(int mask) { return m_LSL_Functions.llGetObjectPermMask(mask); } public LSL_Integer llGetObjectPrimCount(string object_id) { return m_LSL_Functions.llGetObjectPrimCount(object_id); } public LSL_Vector llGetOmega() { return m_LSL_Functions.llGetOmega(); } public LSL_Key llGetOwner() { return m_LSL_Functions.llGetOwner(); } public LSL_Key llGetOwnerKey(string id) { return m_LSL_Functions.llGetOwnerKey(id); } public LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param) { return m_LSL_Functions.llGetParcelDetails(pos, param); } public LSL_Integer llGetParcelFlags(LSL_Vector pos) { return m_LSL_Functions.llGetParcelFlags(pos); } public LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide) { return m_LSL_Functions.llGetParcelMaxPrims(pos, sim_wide); } public LSL_String llGetParcelMusicURL() { return m_LSL_Functions.llGetParcelMusicURL(); } public LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide) { return m_LSL_Functions.llGetParcelPrimCount(pos, category, sim_wide); } public LSL_List llGetParcelPrimOwners(LSL_Vector pos) { return m_LSL_Functions.llGetParcelPrimOwners(pos); } public LSL_Integer llGetPermissions() { return m_LSL_Functions.llGetPermissions(); } public LSL_Key llGetPermissionsKey() { return m_LSL_Functions.llGetPermissionsKey(); } public LSL_Vector llGetPos() { return m_LSL_Functions.llGetPos(); } public LSL_List llGetPrimitiveParams(LSL_List rules) { return m_LSL_Functions.llGetPrimitiveParams(rules); } public LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules) { return m_LSL_Functions.llGetLinkPrimitiveParams(linknum, rules); } public LSL_Integer llGetRegionAgentCount() { return m_LSL_Functions.llGetRegionAgentCount(); } public LSL_Vector llGetRegionCorner() { return m_LSL_Functions.llGetRegionCorner(); } public LSL_Integer llGetRegionFlags() { return m_LSL_Functions.llGetRegionFlags(); } public LSL_Float llGetRegionFPS() { return m_LSL_Functions.llGetRegionFPS(); } public LSL_String llGetRegionName() { return m_LSL_Functions.llGetRegionName(); } public LSL_Float llGetRegionTimeDilation() { return m_LSL_Functions.llGetRegionTimeDilation(); } public LSL_Vector llGetRootPosition() { return m_LSL_Functions.llGetRootPosition(); } public LSL_Rotation llGetRootRotation() { return m_LSL_Functions.llGetRootRotation(); } public LSL_Rotation llGetRot() { return m_LSL_Functions.llGetRot(); } public LSL_Vector llGetScale() { return m_LSL_Functions.llGetScale(); } public LSL_String llGetScriptName() { return m_LSL_Functions.llGetScriptName(); } public LSL_Integer llGetScriptState(string name) { return m_LSL_Functions.llGetScriptState(name); } public LSL_String llGetSimulatorHostname() { return m_LSL_Functions.llGetSimulatorHostname(); } public LSL_Integer llGetSPMaxMemory() { return m_LSL_Functions.llGetSPMaxMemory(); } public LSL_Integer llGetStartParameter() { return m_LSL_Functions.llGetStartParameter(); } public LSL_Integer llGetStatus(int status) { return m_LSL_Functions.llGetStatus(status); } public LSL_String llGetSubString(string src, int start, int end) { return m_LSL_Functions.llGetSubString(src, start, end); } public LSL_Vector llGetSunDirection() { return m_LSL_Functions.llGetSunDirection(); } public LSL_String llGetTexture(int face) { return m_LSL_Functions.llGetTexture(face); } public LSL_Vector llGetTextureOffset(int face) { return m_LSL_Functions.llGetTextureOffset(face); } public LSL_Float llGetTextureRot(int side) { return m_LSL_Functions.llGetTextureRot(side); } public LSL_Vector llGetTextureScale(int side) { return m_LSL_Functions.llGetTextureScale(side); } public LSL_Float llGetTime() { return m_LSL_Functions.llGetTime(); } public LSL_Float llGetTimeOfDay() { return m_LSL_Functions.llGetTimeOfDay(); } public LSL_String llGetTimestamp() { return m_LSL_Functions.llGetTimestamp(); } public LSL_Vector llGetTorque() { return m_LSL_Functions.llGetTorque(); } public LSL_Integer llGetUnixTime() { return m_LSL_Functions.llGetUnixTime(); } public LSL_Integer llGetUsedMemory() { return m_LSL_Functions.llGetUsedMemory(); } public LSL_Vector llGetVel() { return m_LSL_Functions.llGetVel(); } public LSL_Float llGetWallclock() { return m_LSL_Functions.llGetWallclock(); } public void llGiveInventory(string destination, string inventory) { m_LSL_Functions.llGiveInventory(destination, inventory); } public void llGiveInventoryList(string destination, string category, LSL_List inventory) { m_LSL_Functions.llGiveInventoryList(destination, category, inventory); } public void llGiveMoney(string destination, int amount) { m_LSL_Functions.llGiveMoney(destination, amount); } public LSL_String llTransferLindenDollars(string destination, int amount) { return m_LSL_Functions.llTransferLindenDollars(destination, amount); } public void llGodLikeRezObject(string inventory, LSL_Vector pos) { m_LSL_Functions.llGodLikeRezObject(inventory, pos); } public LSL_Float llGround(LSL_Vector offset) { return m_LSL_Functions.llGround(offset); } public LSL_Vector llGroundContour(LSL_Vector offset) { return m_LSL_Functions.llGroundContour(offset); } public LSL_Vector llGroundNormal(LSL_Vector offset) { return m_LSL_Functions.llGroundNormal(offset); } public void llGroundRepel(double height, int water, double tau) { m_LSL_Functions.llGroundRepel(height, water, tau); } public LSL_Vector llGroundSlope(LSL_Vector offset) { return m_LSL_Functions.llGroundSlope(offset); } public LSL_String llHTTPRequest(string url, LSL_List parameters, string body) { return m_LSL_Functions.llHTTPRequest(url, parameters, body); } public void llHTTPResponse(LSL_Key id, int status, string body) { m_LSL_Functions.llHTTPResponse(id, status, body); } public LSL_String llInsertString(string dst, int position, string src) { return m_LSL_Functions.llInsertString(dst, position, src); } public void llInstantMessage(string user, string message) { m_LSL_Functions.llInstantMessage(user, message); } public LSL_String llIntegerToBase64(int number) { return m_LSL_Functions.llIntegerToBase64(number); } public LSL_String llKey2Name(string id) { return m_LSL_Functions.llKey2Name(id); } public LSL_String llGetUsername(string id) { return m_LSL_Functions.llGetUsername(id); } public LSL_String llRequestUsername(string id) { return m_LSL_Functions.llRequestUsername(id); } public LSL_String llGetDisplayName(string id) { return m_LSL_Functions.llGetDisplayName(id); } public LSL_String llRequestDisplayName(string id) { return m_LSL_Functions.llRequestDisplayName(id); } public LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options) { return m_LSL_Functions.llCastRay(start, end, options); } public void llLinkParticleSystem(int linknum, LSL_List rules) { m_LSL_Functions.llLinkParticleSystem(linknum, rules); } public LSL_String llList2CSV(LSL_List src) { return m_LSL_Functions.llList2CSV(src); } public LSL_Float llList2Float(LSL_List src, int index) { return m_LSL_Functions.llList2Float(src, index); } public LSL_Integer llList2Integer(LSL_List src, int index) { return m_LSL_Functions.llList2Integer(src, index); } public LSL_Key llList2Key(LSL_List src, int index) { return m_LSL_Functions.llList2Key(src, index); } public LSL_List llList2List(LSL_List src, int start, int end) { return m_LSL_Functions.llList2List(src, start, end); } public LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride) { return m_LSL_Functions.llList2ListStrided(src, start, end, stride); } public LSL_Rotation llList2Rot(LSL_List src, int index) { return m_LSL_Functions.llList2Rot(src, index); } public LSL_String llList2String(LSL_List src, int index) { return m_LSL_Functions.llList2String(src, index); } public LSL_Vector llList2Vector(LSL_List src, int index) { return m_LSL_Functions.llList2Vector(src, index); } public LSL_Integer llListen(int channelID, string name, string ID, string msg) { return m_LSL_Functions.llListen(channelID, name, ID, msg); } public void llListenControl(int number, int active) { m_LSL_Functions.llListenControl(number, active); } public void llListenRemove(int number) { m_LSL_Functions.llListenRemove(number); } public LSL_Integer llListFindList(LSL_List src, LSL_List test) { return m_LSL_Functions.llListFindList(src, test); } public LSL_List llListInsertList(LSL_List dest, LSL_List src, int start) { return m_LSL_Functions.llListInsertList(dest, src, start); } public LSL_List llListRandomize(LSL_List src, int stride) { return m_LSL_Functions.llListRandomize(src, stride); } public LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end) { return m_LSL_Functions.llListReplaceList(dest, src, start, end); } public LSL_List llListSort(LSL_List src, int stride, int ascending) { return m_LSL_Functions.llListSort(src, stride, ascending); } public LSL_Float llListStatistics(int operation, LSL_List src) { return m_LSL_Functions.llListStatistics(operation, src); } public void llLoadURL(string avatar_id, string message, string url) { m_LSL_Functions.llLoadURL(avatar_id, message, url); } public LSL_Float llLog(double val) { return m_LSL_Functions.llLog(val); } public LSL_Float llLog10(double val) { return m_LSL_Functions.llLog10(val); } public void llLookAt(LSL_Vector target, double strength, double damping) { m_LSL_Functions.llLookAt(target, strength, damping); } public void llLoopSound(string sound, double volume) { m_LSL_Functions.llLoopSound(sound, volume); } public void llLoopSoundMaster(string sound, double volume) { m_LSL_Functions.llLoopSoundMaster(sound, volume); } public void llLoopSoundSlave(string sound, double volume) { m_LSL_Functions.llLoopSoundSlave(sound, volume); } public LSL_Integer llManageEstateAccess(int action, string avatar) { return m_LSL_Functions.llManageEstateAccess(action, avatar); } public void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeExplosion(particles, scale, vel, lifetime, arc, texture, offset); } public void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeFire(particles, scale, vel, lifetime, arc, texture, offset); } public void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset) { m_LSL_Functions.llMakeFountain(particles, scale, vel, lifetime, arc, bounce, texture, offset, bounce_offset); } public void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeSmoke(particles, scale, vel, lifetime, arc, texture, offset); } public void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at) { m_LSL_Functions.llMapDestination(simname, pos, look_at); } public LSL_String llMD5String(string src, int nonce) { return m_LSL_Functions.llMD5String(src, nonce); } public LSL_String llSHA1String(string src) { return m_LSL_Functions.llSHA1String(src); } public void llMessageLinked(int linknum, int num, string str, string id) { m_LSL_Functions.llMessageLinked(linknum, num, str, id); } public void llMinEventDelay(double delay) { m_LSL_Functions.llMinEventDelay(delay); } public void llModifyLand(int action, int brush) { m_LSL_Functions.llModifyLand(action, brush); } public LSL_Integer llModPow(int a, int b, int c) { return m_LSL_Functions.llModPow(a, b, c); } public void llMoveToTarget(LSL_Vector target, double tau) { m_LSL_Functions.llMoveToTarget(target, tau); } public void llOffsetTexture(double u, double v, int face) { m_LSL_Functions.llOffsetTexture(u, v, face); } public void llOpenRemoteDataChannel() { m_LSL_Functions.llOpenRemoteDataChannel(); } public LSL_Integer llOverMyLand(string id) { return m_LSL_Functions.llOverMyLand(id); } public void llOwnerSay(string msg) { m_LSL_Functions.llOwnerSay(msg); } public void llParcelMediaCommandList(LSL_List commandList) { m_LSL_Functions.llParcelMediaCommandList(commandList); } public LSL_List llParcelMediaQuery(LSL_List aList) { return m_LSL_Functions.llParcelMediaQuery(aList); } public LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers) { return m_LSL_Functions.llParseString2List(str, separators, spacers); } public LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers) { return m_LSL_Functions.llParseStringKeepNulls(src, seperators, spacers); } public void llParticleSystem(LSL_List rules) { m_LSL_Functions.llParticleSystem(rules); } public void llPassCollisions(int pass) { m_LSL_Functions.llPassCollisions(pass); } public void llPassTouches(int pass) { m_LSL_Functions.llPassTouches(pass); } public void llPlaySound(string sound, double volume) { m_LSL_Functions.llPlaySound(sound, volume); } public void llPlaySoundSlave(string sound, double volume) { m_LSL_Functions.llPlaySoundSlave(sound, volume); } public void llPointAt(LSL_Vector pos) { m_LSL_Functions.llPointAt(pos); } public LSL_Float llPow(double fbase, double fexponent) { return m_LSL_Functions.llPow(fbase, fexponent); } public void llPreloadSound(string sound) { m_LSL_Functions.llPreloadSound(sound); } public void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local) { m_LSL_Functions.llPushObject(target, impulse, ang_impulse, local); } public void llRefreshPrimURL() { m_LSL_Functions.llRefreshPrimURL(); } public void llRegionSay(int channelID, string text) { m_LSL_Functions.llRegionSay(channelID, text); } public void llRegionSayTo(string key, int channelID, string text) { m_LSL_Functions.llRegionSayTo(key, channelID, text); } public void llReleaseCamera(string avatar) { m_LSL_Functions.llReleaseCamera(avatar); } public void llReleaseURL(string url) { m_LSL_Functions.llReleaseURL(url); } public void llReleaseControls() { m_LSL_Functions.llReleaseControls(); } public void llRemoteDataReply(string channel, string message_id, string sdata, int idata) { m_LSL_Functions.llRemoteDataReply(channel, message_id, sdata, idata); } public void llRemoteDataSetRegion() { m_LSL_Functions.llRemoteDataSetRegion(); } public void llRemoteLoadScript(string target, string name, int running, int start_param) { m_LSL_Functions.llRemoteLoadScript(target, name, running, start_param); } public void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param) { m_LSL_Functions.llRemoteLoadScriptPin(target, name, pin, running, start_param); } public void llRemoveFromLandBanList(string avatar) { m_LSL_Functions.llRemoveFromLandBanList(avatar); } public void llRemoveFromLandPassList(string avatar) { m_LSL_Functions.llRemoveFromLandPassList(avatar); } public void llRemoveInventory(string item) { m_LSL_Functions.llRemoveInventory(item); } public void llRemoveVehicleFlags(int flags) { m_LSL_Functions.llRemoveVehicleFlags(flags); } public LSL_Key llRequestAgentData(string id, int data) { return m_LSL_Functions.llRequestAgentData(id, data); } public LSL_Key llRequestInventoryData(string name) { return m_LSL_Functions.llRequestInventoryData(name); } public void llRequestPermissions(string agent, int perm) { m_LSL_Functions.llRequestPermissions(agent, perm); } public LSL_String llRequestSecureURL() { return m_LSL_Functions.llRequestSecureURL(); } public LSL_Key llRequestSimulatorData(string simulator, int data) { return m_LSL_Functions.llRequestSimulatorData(simulator, data); } public LSL_Key llRequestURL() { return m_LSL_Functions.llRequestURL(); } public void llResetLandBanList() { m_LSL_Functions.llResetLandBanList(); } public void llResetLandPassList() { m_LSL_Functions.llResetLandPassList(); } public void llResetOtherScript(string name) { m_LSL_Functions.llResetOtherScript(name); } public void llResetScript() { m_LSL_Functions.llResetScript(); } public void llResetTime() { m_LSL_Functions.llResetTime(); } public void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param) { m_LSL_Functions.llRezAtRoot(inventory, position, velocity, rot, param); } public void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param) { m_LSL_Functions.llRezObject(inventory, pos, vel, rot, param); } public LSL_Float llRot2Angle(LSL_Rotation rot) { return m_LSL_Functions.llRot2Angle(rot); } public LSL_Vector llRot2Axis(LSL_Rotation rot) { return m_LSL_Functions.llRot2Axis(rot); } public LSL_Vector llRot2Euler(LSL_Rotation r) { return m_LSL_Functions.llRot2Euler(r); } public LSL_Vector llRot2Fwd(LSL_Rotation r) { return m_LSL_Functions.llRot2Fwd(r); } public LSL_Vector llRot2Left(LSL_Rotation r) { return m_LSL_Functions.llRot2Left(r); } public LSL_Vector llRot2Up(LSL_Rotation r) { return m_LSL_Functions.llRot2Up(r); } public void llRotateTexture(double rotation, int face) { m_LSL_Functions.llRotateTexture(rotation, face); } public LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end) { return m_LSL_Functions.llRotBetween(start, end); } public void llRotLookAt(LSL_Rotation target, double strength, double damping) { m_LSL_Functions.llRotLookAt(target, strength, damping); } public LSL_Integer llRotTarget(LSL_Rotation rot, double error) { return m_LSL_Functions.llRotTarget(rot, error); } public void llRotTargetRemove(int number) { m_LSL_Functions.llRotTargetRemove(number); } public LSL_Integer llRound(double f) { return m_LSL_Functions.llRound(f); } public LSL_Integer llSameGroup(string agent) { return m_LSL_Functions.llSameGroup(agent); } public void llSay(int channelID, string text) { m_LSL_Functions.llSay(channelID, text); } public void llScaleTexture(double u, double v, int face) { m_LSL_Functions.llScaleTexture(u, v, face); } public LSL_Integer llScriptDanger(LSL_Vector pos) { return m_LSL_Functions.llScriptDanger(pos); } public void llScriptProfiler(LSL_Integer flags) { m_LSL_Functions.llScriptProfiler(flags); } public LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata) { return m_LSL_Functions.llSendRemoteData(channel, dest, idata, sdata); } public void llSensor(string name, string id, int type, double range, double arc) { m_LSL_Functions.llSensor(name, id, type, range, arc); } public void llSensorRemove() { m_LSL_Functions.llSensorRemove(); } public void llSensorRepeat(string name, string id, int type, double range, double arc, double rate) { m_LSL_Functions.llSensorRepeat(name, id, type, range, arc, rate); } public void llSetAlpha(double alpha, int face) { m_LSL_Functions.llSetAlpha(alpha, face); } public void llSetBuoyancy(double buoyancy) { m_LSL_Functions.llSetBuoyancy(buoyancy); } public void llSetCameraAtOffset(LSL_Vector offset) { m_LSL_Functions.llSetCameraAtOffset(offset); } public void llSetCameraEyeOffset(LSL_Vector offset) { m_LSL_Functions.llSetCameraEyeOffset(offset); } public void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at) { m_LSL_Functions.llSetLinkCamera(link, eye, at); } public void llSetCameraParams(LSL_List rules) { m_LSL_Functions.llSetCameraParams(rules); } public void llSetClickAction(int action) { m_LSL_Functions.llSetClickAction(action); } public void llSetColor(LSL_Vector color, int face) { m_LSL_Functions.llSetColor(color, face); } public void llSetDamage(double damage) { m_LSL_Functions.llSetDamage(damage); } public void llSetForce(LSL_Vector force, int local) { m_LSL_Functions.llSetForce(force, local); } public void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local) { m_LSL_Functions.llSetForceAndTorque(force, torque, local); } public void llSetHoverHeight(double height, int water, double tau) { m_LSL_Functions.llSetHoverHeight(height, water, tau); } public void llSetInventoryPermMask(string item, int mask, int value) { m_LSL_Functions.llSetInventoryPermMask(item, mask, value); } public void llSetLinkAlpha(int linknumber, double alpha, int face) { m_LSL_Functions.llSetLinkAlpha(linknumber, alpha, face); } public void llSetLinkColor(int linknumber, LSL_Vector color, int face) { m_LSL_Functions.llSetLinkColor(linknumber, color, face); } public void llSetLinkPrimitiveParams(int linknumber, LSL_List rules) { m_LSL_Functions.llSetLinkPrimitiveParams(linknumber, rules); } public void llSetLinkTexture(int linknumber, string texture, int face) { m_LSL_Functions.llSetLinkTexture(linknumber, texture, face); } public void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate) { m_LSL_Functions.llSetLinkTextureAnim(linknum, mode, face, sizex, sizey, start, length, rate); } public void llSetLocalRot(LSL_Rotation rot) { m_LSL_Functions.llSetLocalRot(rot); } public LSL_Integer llSetMemoryLimit(LSL_Integer limit) { return m_LSL_Functions.llSetMemoryLimit(limit); } public void llSetObjectDesc(string desc) { m_LSL_Functions.llSetObjectDesc(desc); } public void llSetObjectName(string name) { m_LSL_Functions.llSetObjectName(name); } public void llSetObjectPermMask(int mask, int value) { m_LSL_Functions.llSetObjectPermMask(mask, value); } public void llSetParcelMusicURL(string url) { m_LSL_Functions.llSetParcelMusicURL(url); } public void llSetPayPrice(int price, LSL_List quick_pay_buttons) { m_LSL_Functions.llSetPayPrice(price, quick_pay_buttons); } public void llSetPos(LSL_Vector pos) { m_LSL_Functions.llSetPos(pos); } public void llSetPrimitiveParams(LSL_List rules) { m_LSL_Functions.llSetPrimitiveParams(rules); } public void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules) { m_LSL_Functions.llSetLinkPrimitiveParamsFast(linknum, rules); } public void llSetPrimURL(string url) { m_LSL_Functions.llSetPrimURL(url); } public LSL_Integer llSetRegionPos(LSL_Vector pos) { return m_LSL_Functions.llSetRegionPos(pos); } public void llSetRemoteScriptAccessPin(int pin) { m_LSL_Functions.llSetRemoteScriptAccessPin(pin); } public void llSetRot(LSL_Rotation rot) { m_LSL_Functions.llSetRot(rot); } public void llSetScale(LSL_Vector scale) { m_LSL_Functions.llSetScale(scale); } public void llSetScriptState(string name, int run) { m_LSL_Functions.llSetScriptState(name, run); } public void llSetSitText(string text) { m_LSL_Functions.llSetSitText(text); } public void llSetSoundQueueing(int queue) { m_LSL_Functions.llSetSoundQueueing(queue); } public void llSetSoundRadius(double radius) { m_LSL_Functions.llSetSoundRadius(radius); } public void llSetStatus(int status, int value) { m_LSL_Functions.llSetStatus(status, value); } public void llSetText(string text, LSL_Vector color, double alpha) { m_LSL_Functions.llSetText(text, color, alpha); } public void llSetTexture(string texture, int face) { m_LSL_Functions.llSetTexture(texture, face); } public void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate) { m_LSL_Functions.llSetTextureAnim(mode, face, sizex, sizey, start, length, rate); } public void llSetTimerEvent(double sec) { m_LSL_Functions.llSetTimerEvent(sec); } public void llSetTorque(LSL_Vector torque, int local) { m_LSL_Functions.llSetTorque(torque, local); } public void llSetTouchText(string text) { m_LSL_Functions.llSetTouchText(text); } public void llSetVehicleFlags(int flags) { m_LSL_Functions.llSetVehicleFlags(flags); } public void llSetVehicleFloatParam(int param, LSL_Float value) { m_LSL_Functions.llSetVehicleFloatParam(param, value); } public void llSetVehicleRotationParam(int param, LSL_Rotation rot) { m_LSL_Functions.llSetVehicleRotationParam(param, rot); } public void llSetVehicleType(int type) { m_LSL_Functions.llSetVehicleType(type); } public void llSetVehicleVectorParam(int param, LSL_Vector vec) { m_LSL_Functions.llSetVehicleVectorParam(param, vec); } public void llShout(int channelID, string text) { m_LSL_Functions.llShout(channelID, text); } public LSL_Float llSin(double f) { return m_LSL_Functions.llSin(f); } public void llSitTarget(LSL_Vector offset, LSL_Rotation rot) { m_LSL_Functions.llSitTarget(offset, rot); } public void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot) { m_LSL_Functions.llLinkSitTarget(link, offset, rot); } public void llSleep(double sec) { m_LSL_Functions.llSleep(sec); } public void llSound(string sound, double volume, int queue, int loop) { m_LSL_Functions.llSound(sound, volume, queue, loop); } public void llSoundPreload(string sound) { m_LSL_Functions.llSoundPreload(sound); } public LSL_Float llSqrt(double f) { return m_LSL_Functions.llSqrt(f); } public void llStartAnimation(string anim) { m_LSL_Functions.llStartAnimation(anim); } public void llStopAnimation(string anim) { m_LSL_Functions.llStopAnimation(anim); } public void llStopHover() { m_LSL_Functions.llStopHover(); } public void llStopLookAt() { m_LSL_Functions.llStopLookAt(); } public void llStopMoveToTarget() { m_LSL_Functions.llStopMoveToTarget(); } public void llStopPointAt() { m_LSL_Functions.llStopPointAt(); } public void llStopSound() { m_LSL_Functions.llStopSound(); } public LSL_Integer llStringLength(string str) { return m_LSL_Functions.llStringLength(str); } public LSL_String llStringToBase64(string str) { return m_LSL_Functions.llStringToBase64(str); } public LSL_String llStringTrim(string src, int type) { return m_LSL_Functions.llStringTrim(src, type); } public LSL_Integer llSubStringIndex(string source, string pattern) { return m_LSL_Functions.llSubStringIndex(source, pattern); } public void llTakeCamera(string avatar) { m_LSL_Functions.llTakeCamera(avatar); } public void llTakeControls(int controls, int accept, int pass_on) { m_LSL_Functions.llTakeControls(controls, accept, pass_on); } public LSL_Float llTan(double f) { return m_LSL_Functions.llTan(f); } public LSL_Integer llTarget(LSL_Vector position, double range) { return m_LSL_Functions.llTarget(position, range); } public void llTargetOmega(LSL_Vector axis, double spinrate, double gain) { m_LSL_Functions.llTargetOmega(axis, spinrate, gain); } public void llTargetRemove(int number) { m_LSL_Functions.llTargetRemove(number); } public void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt) { m_LSL_Functions.llTeleportAgent(agent, simname, pos, lookAt); } public void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt) { m_LSL_Functions.llTeleportAgentGlobalCoords(agent, global, pos, lookAt); } public void llTeleportAgentHome(string agent) { m_LSL_Functions.llTeleportAgentHome(agent); } public void llTextBox(string avatar, string message, int chat_channel) { m_LSL_Functions.llTextBox(avatar, message, chat_channel); } public LSL_String llToLower(string source) { return m_LSL_Functions.llToLower(source); } public LSL_String llToUpper(string source) { return m_LSL_Functions.llToUpper(source); } public void llTriggerSound(string sound, double volume) { m_LSL_Functions.llTriggerSound(sound, volume); } public void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west) { m_LSL_Functions.llTriggerSoundLimited(sound, volume, top_north_east, bottom_south_west); } public LSL_String llUnescapeURL(string url) { return m_LSL_Functions.llUnescapeURL(url); } public void llUnSit(string id) { m_LSL_Functions.llUnSit(id); } public LSL_Float llVecDist(LSL_Vector a, LSL_Vector b) { return m_LSL_Functions.llVecDist(a, b); } public LSL_Float llVecMag(LSL_Vector v) { return m_LSL_Functions.llVecMag(v); } public LSL_Vector llVecNorm(LSL_Vector v) { return m_LSL_Functions.llVecNorm(v); } public void llVolumeDetect(int detect) { m_LSL_Functions.llVolumeDetect(detect); } public LSL_Float llWater(LSL_Vector offset) { return m_LSL_Functions.llWater(offset); } public void llWhisper(int channelID, string text) { m_LSL_Functions.llWhisper(channelID, text); } public LSL_Vector llWind(LSL_Vector offset) { return m_LSL_Functions.llWind(offset); } public LSL_String llXorBase64Strings(string str1, string str2) { return m_LSL_Functions.llXorBase64Strings(str1, str2); } public LSL_String llXorBase64StringsCorrect(string str1, string str2) { return m_LSL_Functions.llXorBase64StringsCorrect(str1, str2); } public LSL_List llGetPrimMediaParams(int face, LSL_List rules) { return m_LSL_Functions.llGetPrimMediaParams(face, rules); } public LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules) { return m_LSL_Functions.llGetLinkMedia(link, face, rules); } public LSL_Integer llSetPrimMediaParams(int face, LSL_List rules) { return m_LSL_Functions.llSetPrimMediaParams(face, rules); } public LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules) { return m_LSL_Functions.llSetLinkMedia(link, face, rules); } public LSL_Integer llClearPrimMedia(LSL_Integer face) { return m_LSL_Functions.llClearPrimMedia(face); } public LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face) { return m_LSL_Functions.llClearLinkMedia(link, face); } public void print(string str) { m_LSL_Functions.print(str); } } }
using System; /// <summary> /// Convert.ToChar(Int32) /// Converts the value of the specified 32-bit signed integer to its equivalent Unicode character. /// </summary> public class ConvertTochar { public static int Main() { ConvertTochar testObj = new ConvertTochar(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToChar(Int32)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string errorDesc; Int32 i; char expectedValue; char actualValue; i = TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1); TestLibrary.TestFramework.BeginScenario("PosTest1: Int32 value between 0 and UInt16.MaxValue."); try { actualValue = Convert.ToChar(i); expectedValue = (char)i; if (actualValue != expectedValue) { errorDesc = string.Format( "The character corresponding to Int32 value {0} is not \\u{1:x} as expected: actual(\\u{2:x})", i, (int)expectedValue, (int)actualValue); TestLibrary.TestFramework.LogError("001", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe Int32 value is " + i; TestLibrary.TestFramework.LogError("002", errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string errorDesc; Int32 i; char expectedValue; char actualValue; i = UInt16.MaxValue; TestLibrary.TestFramework.BeginScenario("PosTest2: Int32 value is UInt16.MaxValue."); try { actualValue = Convert.ToChar(i); expectedValue = (char)i; if (actualValue != expectedValue) { errorDesc = string.Format( "The character corresponding to Int32 value {0} is not \\u{1:x} as expected: actual(\\u{2:x})", i, (int)expectedValue, (int)actualValue); TestLibrary.TestFramework.LogError("003", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe Int32 value is " + i; TestLibrary.TestFramework.LogError("004", errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string errorDesc; Int32 i; char expectedValue; char actualValue; i = 0; TestLibrary.TestFramework.BeginScenario("PosTest3: Int32 value is zero."); try { actualValue = Convert.ToChar(i); expectedValue = (char)i; if (actualValue != expectedValue) { errorDesc = string.Format( "The character corresponding to Int32 value {0} is not \\u{1:x} as expected: actual(\\u{2:x})", i, (int)expectedValue, (int)actualValue); TestLibrary.TestFramework.LogError("005", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe Int32 value is " + i; TestLibrary.TestFramework.LogError("006", errorDesc); retVal = false; } return retVal; } #endregion #region Negative tests //OverflowException public bool NegTest1() { bool retVal = true; const string c_TEST_ID = "N001"; const string c_TEST_DESC = "NegTest1: Int32 value is a negative integer between Int32.MinValue and -1."; string errorDesc; Int32 i = (Int32)(-1 * TestLibrary.Generator.GetInt32(-55) - 1); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToChar(i); errorDesc = "OverflowException is not thrown as expected."; errorDesc += string.Format("\nThe Int32 value is {0}", i); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (OverflowException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe Int32 value is {0}", i); TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; const string c_TEST_ID = "N002"; const string c_TEST_DESC = "NegTest2: Int32 value is a integer between UInt16.MaxValue and Int32.MaxValue."; string errorDesc; Int32 i = TestLibrary.Generator.GetInt32(-55) % (Int32.MaxValue - UInt16.MaxValue) + UInt16.MaxValue + 1; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToChar(i); errorDesc = "OverflowException is not thrown as expected."; errorDesc += string.Format("\nThe Int32 value is {0}", i); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (OverflowException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe Int32 value is {0}", i); TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #endregion }
/* * Licensed to the Apache Software Foundation (ASF) Under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You Under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed Under the License is distributed on an "AS Is" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations Under the License. */ namespace NPOI.SS.Formula.Functions { using System; using NPOI.SS.Formula.Eval; using NPOI.SS.Formula; /* * Implementation for the Excel function SUMPRODUCT<p/> * * Syntax : <br/> * SUMPRODUCT ( array1[, array2[, array3[, ...]]]) * <table border="0" cellpAdding="1" cellspacing="0" summary="Parameter descriptions"> * <tr><th>array1, ... arrayN </th><td>typically area references, * possibly cell references or scalar values</td></tr> * </table><br/> * * Let A<b>n</b><sub>(<b>i</b>,<b>j</b>)</sub> represent the element in the <b>i</b>th row <b>j</b>th column * of the <b>n</b>th array<br/> * Assuming each array has the same dimensions (W, H), the result Is defined as:<br/> * SUMPRODUCT = &Sigma;<sub><b>i</b>: 1..H</sub> * ( &Sigma;<sub><b>j</b>: 1..W</sub> * ( &Pi;<sub><b>n</b>: 1..N</sub> * A<b>n</b><sub>(<b>i</b>,<b>j</b>)</sub> * ) * ) * * @author Josh Micich */ internal class Sumproduct : Function { [Serializable] private class EvalEx : Exception { private ErrorEval _error; public EvalEx(ErrorEval error) { _error = error; } public ErrorEval GetError() { return _error; } } public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) { int maxN = args.Length; if (maxN < 1) { return ErrorEval.VALUE_INVALID; } ValueEval firstArg = args[0]; try { if (firstArg is NumericValueEval) { return EvaluateSingleProduct(args); } if (firstArg is RefEval) { return EvaluateSingleProduct(args); } if (firstArg is TwoDEval) { TwoDEval ae = (TwoDEval)firstArg; if (ae.IsRow && ae.IsColumn) { return EvaluateSingleProduct(args); } return EvaluateAreaSumProduct(args); } } catch (EvalEx e) { return e.GetError(); } throw new Exception("Invalid arg type for SUMPRODUCT: (" + firstArg.GetType().Name + ")"); } private ValueEval EvaluateSingleProduct(ValueEval[] evalArgs) { int maxN = evalArgs.Length; double term = 1D; for (int n = 0; n < maxN; n++) { double val = GetScalarValue(evalArgs[n]); term *= val; } return new NumberEval(term); } private static double GetScalarValue(ValueEval arg) { ValueEval eval; if (arg is RefEval) { RefEval re = (RefEval)arg; eval = re.InnerValueEval; } else { eval = arg; } if (eval == null) { throw new ArgumentException("parameter may not be null"); } if (eval is AreaEval) { AreaEval ae = (AreaEval)eval; // an area ref can work as a scalar value if it is 1x1 if (!ae.IsColumn || !ae.IsRow) { throw new EvaluationException(ErrorEval.VALUE_INVALID); } eval = ae.GetRelativeValue(0, 0); } if (!(eval is ValueEval)) { throw new ArgumentException("Unexpected value eval class (" + eval.GetType().Name + ")"); } return GetProductTerm((ValueEval)eval, true); } private ValueEval EvaluateAreaSumProduct(ValueEval[] evalArgs) { int maxN = evalArgs.Length; AreaEval[] args = new AreaEval[maxN]; try { Array.Copy(evalArgs, 0, args, 0, maxN); } catch (Exception) { // one of the other args was not an AreaRef return ErrorEval.VALUE_INVALID; } AreaEval firstArg = args[0]; int height = firstArg.LastRow - firstArg.FirstRow + 1; int width = firstArg.LastColumn - firstArg.FirstColumn + 1; // TODO - junit // first check dimensions if (!AreasAllSameSize(args, height, width)) { // normally this results in #VALUE!, // but errors in individual cells take precedence for (int i = 1; i < args.Length; i++) { ThrowFirstError(args[i]); } return ErrorEval.VALUE_INVALID; } double acc = 0; for (int rrIx = 0; rrIx < height; rrIx++) { for (int rcIx = 0; rcIx < width; rcIx++) { double term = 1D; for (int n = 0; n < maxN; n++) { double val = GetProductTerm(args[n].GetRelativeValue(rrIx, rcIx), false); term *= val; } acc += term; } } return new NumberEval(acc); } private static void ThrowFirstError(TwoDEval areaEval) { int height = areaEval.Height; int width = areaEval.Width; for (int rrIx = 0; rrIx < height; rrIx++) { for (int rcIx = 0; rcIx < width; rcIx++) { ValueEval ve = areaEval.GetValue(rrIx, rcIx); if (ve is ErrorEval) { throw new EvaluationException((ErrorEval)ve); } } } } private static bool AreasAllSameSize(TwoDEval[] args, int height, int width) { for (int i = 0; i < args.Length; i++) { TwoDEval areaEval = args[i]; // check that height and width match if (areaEval.Height != height) { return false; } if (areaEval.Width != width) { return false; } } return true; } /** * Determines a <c>double</c> value for the specified <c>ValueEval</c>. * @param IsScalarProduct <c>false</c> for SUMPRODUCTs over area refs. * @throws EvalEx if <c>ve</c> represents an error value. * <p/> * Note - string values and empty cells are interpreted differently depending on * <c>isScalarProduct</c>. For scalar products, if any term Is blank or a string, the * error (#VALUE!) Is raised. For area (sum)products, if any term Is blank or a string, the * result Is zero. */ private static double GetProductTerm(ValueEval ve, bool IsScalarProduct) { if (ve is BlankEval || ve == null) { // TODO - shouldn't BlankEval.INSTANCE be used always instead of null? // null seems to occur when the blank cell Is part of an area ref (but not reliably) if (IsScalarProduct) { throw new EvalEx(ErrorEval.VALUE_INVALID); } return 0; } if (ve is ErrorEval) { throw new EvalEx((ErrorEval)ve); } if (ve is StringEval) { if (IsScalarProduct) { throw new EvalEx(ErrorEval.VALUE_INVALID); } // Note for area SUMPRODUCTs, string values are interpreted as zero // even if they would Parse as valid numeric values return 0; } if (ve is NumericValueEval) { NumericValueEval nve = (NumericValueEval)ve; return nve.NumberValue; } throw new Exception("Unexpected value eval class (" + ve.GetType().Name + ")"); } } }
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> /// Controller class for Rem_Formulario /// </summary> [System.ComponentModel.DataObject] public partial class RemFormularioController { // Preload our schema.. RemFormulario thisSchemaLoad = new RemFormulario(); private string userName = String.Empty; protected string UserName { get { if (userName.Length == 0) { if (System.Web.HttpContext.Current != null) { userName=System.Web.HttpContext.Current.User.Identity.Name; } else { userName=System.Threading.Thread.CurrentPrincipal.Identity.Name; } } return userName; } } [DataObjectMethod(DataObjectMethodType.Select, true)] public RemFormularioCollection FetchAll() { RemFormularioCollection coll = new RemFormularioCollection(); Query qry = new Query(RemFormulario.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public RemFormularioCollection FetchByID(object IdFormulario) { RemFormularioCollection coll = new RemFormularioCollection().Where("idFormulario", IdFormulario).Load(); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public RemFormularioCollection FetchByQuery(Query qry) { RemFormularioCollection coll = new RemFormularioCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(object IdFormulario) { return (RemFormulario.Delete(IdFormulario) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, false)] public bool Destroy(object IdFormulario) { return (RemFormulario.Destroy(IdFormulario) == 1); } /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Insert, true)] public void Insert(int IdEfector,int IdPaciente,int IdObraSocial,int NumeroFormulario,DateTime FechaEmpadronamiento,int? IdAgente,int IdMunicipio,int Sexo,int Edad,int Hta2,int Hta3,int Colesterol4,int Colesterol5,int Dtm26,int Dtm27,int Ecv8,int Tabaco9,int Sumatoria,bool PoseeFirma,int CreatedBy,DateTime CreatedOn,int ModifiedBy,DateTime ModifiedOn,string Centros,int VacunasCompletas,int Pap,int? IdProfesional) { RemFormulario item = new RemFormulario(); item.IdEfector = IdEfector; item.IdPaciente = IdPaciente; item.IdObraSocial = IdObraSocial; item.NumeroFormulario = NumeroFormulario; item.FechaEmpadronamiento = FechaEmpadronamiento; item.IdAgente = IdAgente; item.IdMunicipio = IdMunicipio; item.Sexo = Sexo; item.Edad = Edad; item.Hta2 = Hta2; item.Hta3 = Hta3; item.Colesterol4 = Colesterol4; item.Colesterol5 = Colesterol5; item.Dtm26 = Dtm26; item.Dtm27 = Dtm27; item.Ecv8 = Ecv8; item.Tabaco9 = Tabaco9; item.Sumatoria = Sumatoria; item.PoseeFirma = PoseeFirma; item.CreatedBy = CreatedBy; item.CreatedOn = CreatedOn; item.ModifiedBy = ModifiedBy; item.ModifiedOn = ModifiedOn; item.Centros = Centros; item.VacunasCompletas = VacunasCompletas; item.Pap = Pap; item.IdProfesional = IdProfesional; item.Save(UserName); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Update, true)] public void Update(int IdFormulario,int IdEfector,int IdPaciente,int IdObraSocial,int NumeroFormulario,DateTime FechaEmpadronamiento,int? IdAgente,int IdMunicipio,int Sexo,int Edad,int Hta2,int Hta3,int Colesterol4,int Colesterol5,int Dtm26,int Dtm27,int Ecv8,int Tabaco9,int Sumatoria,bool PoseeFirma,int CreatedBy,DateTime CreatedOn,int ModifiedBy,DateTime ModifiedOn,string Centros,int VacunasCompletas,int Pap,int? IdProfesional) { RemFormulario item = new RemFormulario(); item.MarkOld(); item.IsLoaded = true; item.IdFormulario = IdFormulario; item.IdEfector = IdEfector; item.IdPaciente = IdPaciente; item.IdObraSocial = IdObraSocial; item.NumeroFormulario = NumeroFormulario; item.FechaEmpadronamiento = FechaEmpadronamiento; item.IdAgente = IdAgente; item.IdMunicipio = IdMunicipio; item.Sexo = Sexo; item.Edad = Edad; item.Hta2 = Hta2; item.Hta3 = Hta3; item.Colesterol4 = Colesterol4; item.Colesterol5 = Colesterol5; item.Dtm26 = Dtm26; item.Dtm27 = Dtm27; item.Ecv8 = Ecv8; item.Tabaco9 = Tabaco9; item.Sumatoria = Sumatoria; item.PoseeFirma = PoseeFirma; item.CreatedBy = CreatedBy; item.CreatedOn = CreatedOn; item.ModifiedBy = ModifiedBy; item.ModifiedOn = ModifiedOn; item.Centros = Centros; item.VacunasCompletas = VacunasCompletas; item.Pap = Pap; item.IdProfesional = IdProfesional; item.Save(UserName); } } }
using Microsoft.EntityFrameworkCore; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Data; using SFA.DAS.CommitmentsV2.Models; using SFA.DAS.CommitmentsV2.Types; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoFixture; using SFA.DAS.UnitOfWork.Context; using SFA.DAS.CommitmentsV2.Application.Queries.GetProviderPaymentsPriority; using System.Collections; using Moq; using Microsoft.Extensions.Logging; namespace SFA.DAS.CommitmentsV2.UnitTests.Application.Queries.GetProviderPaymentsPriority { [TestFixture] [Parallelizable] public class GetProviderPaymentsPriorityQueryHandlerTests { [TestCaseSource(typeof(CreateProviderPaymentsDataCases))] public async Task Handle_WhenRequested_ThenItShouldReturnTheCurrentPriorityOrder(long accountId, CreateProviderPaymentsDataCases.Input[] inputs, CreateProviderPaymentsDataCases.ExpectedOutput[] expectedOutputs) { var fixture = new GetProviderPaymentsPriorityQueryHandlerTestFixtures(); foreach(var input in inputs) { fixture.SetCohort(input.ApprenticeshipId, input.AccountId, input.ProviderId, input.ProviderName, input.ApprenticeshipAgreedOn, input.CohortApprovedOn, input.CohortFullyApproved, input.PriorityOrder); } var results = await fixture.Handle(accountId); Assert.IsTrue(TestHelpers.CompareHelper.AreEqualIgnoringTypes(results.PriorityItems, expectedOutputs)); } } public class CreateProviderPaymentsDataCases : IEnumerable { public IEnumerator GetEnumerator() { var provider101 = new { ProviderId = 101, ProviderName = "Test101" }; var provider102 = new { ProviderId = 102, ProviderName = "Test102" }; var provider103 = new { ProviderId = 103, ProviderName = "Test103" }; var provider201 = new { ProviderId = 201, ProviderName = "Test201" }; // current custom provider payment priority ordered by P101, P102, P103 yield return new object[] { 111111, new Input[] { new Input { ApprenticeshipId = 1, AccountId = 111111, PriorityOrder = 1, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, new Input { ApprenticeshipId = 2, AccountId = 111111, PriorityOrder = 2, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 3, AccountId = 111111, PriorityOrder = 3, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true} }, new ExpectedOutput[] { new ExpectedOutput { ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, PriorityOrder = 1}, new ExpectedOutput { ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, PriorityOrder = 2}, new ExpectedOutput { ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, PriorityOrder = 3} } }; // no current custom provider payment priority ordered by P101, P102, P103 yield return new object[] { 222222, new Input[] { new Input { ApprenticeshipId = 4, AccountId = 222222, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true, PriorityOrder = null}, new Input { ApprenticeshipId = 5, AccountId = 222222, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true, PriorityOrder = null}, new Input { ApprenticeshipId = 6, AccountId = 222222, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true, PriorityOrder = null}, }, new ExpectedOutput[] { new ExpectedOutput { ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, PriorityOrder = 1}, new ExpectedOutput { ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, PriorityOrder = 2}, new ExpectedOutput { ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, PriorityOrder = 3} } }; // no current custom provider payment priority ordered by P102, P101, P103 yield return new object[] { 333333, new Input[] { new Input { ApprenticeshipId = 7, AccountId = 333333, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true, PriorityOrder = null}, new Input { ApprenticeshipId = 8, AccountId = 333333, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true, PriorityOrder = null}, new Input { ApprenticeshipId = 9, AccountId = 333333, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true, PriorityOrder = null}, }, new ExpectedOutput[] { new ExpectedOutput { ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, PriorityOrder = 1}, new ExpectedOutput { ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, PriorityOrder = 2}, new ExpectedOutput { ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, PriorityOrder = 3} } }; // no current custom provider payment priority ordered by P102, P101, P103 yield return new object[] { 444444, new Input[] { new Input { ApprenticeshipId = 10, AccountId = 444444, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = DateTime.Now.AddMonths(-2), CohortApprovedOn = null, CohortFullyApproved = true, PriorityOrder = null}, new Input { ApprenticeshipId = 11, AccountId = 444444, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true, PriorityOrder = null}, new Input { ApprenticeshipId = 12, AccountId = 444444, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = DateTime.Now.AddMonths(-1), CohortApprovedOn = null, CohortFullyApproved = true, PriorityOrder = null}, }, new ExpectedOutput[] { new ExpectedOutput { ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, PriorityOrder = 1}, new ExpectedOutput { ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, PriorityOrder = 2}, new ExpectedOutput { ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, PriorityOrder = 3} } }; // no current custom provider payment priority ordered by P102 (Not Approved), P101, P103 yield return new object[] { 555555, new Input[] { new Input { ApprenticeshipId = 13, AccountId = 555555, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true, PriorityOrder = null}, new Input { ApprenticeshipId = 14, AccountId = 555555, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = false, PriorityOrder = null}, new Input { ApprenticeshipId = 15, AccountId = 555555, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true, PriorityOrder = null}, }, new ExpectedOutput[] { new ExpectedOutput { ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, PriorityOrder = 1}, new ExpectedOutput { ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, PriorityOrder = 2} } }; // partial current custom provider payment priority ordered by P102, P101, P103 (With Existing Priority 1) yield return new object[] { 666666, new Input[] { new Input { ApprenticeshipId = 16, AccountId = 666666, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true, PriorityOrder = null}, new Input { ApprenticeshipId = 17, AccountId = 666666, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true, PriorityOrder = null}, new Input { ApprenticeshipId = 18, AccountId = 666666, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true, PriorityOrder = 1}, }, new ExpectedOutput[] { new ExpectedOutput { ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, PriorityOrder = 1}, new ExpectedOutput { ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, PriorityOrder = 2}, new ExpectedOutput { ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, PriorityOrder = 3} } }; // current custom provider payment priority ordered by P101, P102, P103 (With earlier date for multiple 103 which is ignored) yield return new object[] { 777777, new Input[] { new Input { ApprenticeshipId = 19, AccountId = 777777, PriorityOrder = 1, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, new Input { ApprenticeshipId = 20, AccountId = 777777, PriorityOrder = 2, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 21, AccountId = 777777, PriorityOrder = 3, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 22, AccountId = 777777, PriorityOrder = 3, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-4), CohortFullyApproved = true}, new Input { ApprenticeshipId = 23, AccountId = 888888, PriorityOrder = 1, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 24, AccountId = 888888, PriorityOrder = 2, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 25, AccountId = 999999, PriorityOrder = 1, ProviderId = provider201.ProviderId, ProviderName = provider201.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, }, new ExpectedOutput[] { new ExpectedOutput { ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, PriorityOrder = 1}, new ExpectedOutput { ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, PriorityOrder = 2}, new ExpectedOutput { ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, PriorityOrder = 3} } }; // no custom provider payment priority ordered by P103 (With earlier date for multiple 103 which is used), P101, P102, P103 (With later date for multiple 103 which is ignored) yield return new object[] { 888888, new Input[] { new Input { ApprenticeshipId = 26, AccountId = 888888, PriorityOrder = null, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, new Input { ApprenticeshipId = 27, AccountId = 888888, PriorityOrder = null, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 28, AccountId = 888888, PriorityOrder = null, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 29, AccountId = 888888, PriorityOrder = null, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-4), CohortFullyApproved = true}, new Input { ApprenticeshipId = 30, AccountId = 999999, PriorityOrder = 1, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 31, AccountId = 999999, PriorityOrder = 2, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 32, AccountId = 111111, PriorityOrder = 1, ProviderId = provider201.ProviderId, ProviderName = provider201.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, }, new ExpectedOutput[] { new ExpectedOutput { ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, PriorityOrder = 1}, new ExpectedOutput { ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, PriorityOrder = 2}, new ExpectedOutput { ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, PriorityOrder = 3}, } }; // partial custom provider payment priority ordered by P102, P201, P103 (With earlier date for multiple 103 which is used), P101, P103 (With later date for multiple 103 which is ignored) yield return new object[] { 999999, new Input[] { new Input { ApprenticeshipId = 33, AccountId = 999999, PriorityOrder = null, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, new Input { ApprenticeshipId = 34, AccountId = 999999, PriorityOrder = 1, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 35, AccountId = 999999, PriorityOrder = null, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 36, AccountId = 999999, PriorityOrder = null, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-4), CohortFullyApproved = true}, new Input { ApprenticeshipId = 37, AccountId = 999999, PriorityOrder = 2, ProviderId = provider201.ProviderId, ProviderName = provider201.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 38, AccountId = 111111, PriorityOrder = 1, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 39, AccountId = 111111, PriorityOrder = 2, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 40, AccountId = 222222, PriorityOrder = 1, ProviderId = provider201.ProviderId, ProviderName = provider201.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, }, new ExpectedOutput[] { new ExpectedOutput { ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, PriorityOrder = 1}, new ExpectedOutput { ProviderId = provider201.ProviderId, ProviderName = provider201.ProviderName, PriorityOrder = 2}, new ExpectedOutput { ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, PriorityOrder = 3}, new ExpectedOutput { ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, PriorityOrder = 4}, } }; // partial custom provider payment priority ordered by P102, P201, P103 (With earlier date for multiple 103 which is used), P101, P103 (With later date for multiple 103 which is ignored) yield return new object[] { 111222, new Input[] { new Input { ApprenticeshipId = 41, AccountId = 111222, PriorityOrder = null, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, new Input { ApprenticeshipId = 42, AccountId = 111222, PriorityOrder = null, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 43, AccountId = 111222, PriorityOrder = null, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 44, AccountId = 111222, PriorityOrder = 1, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 45, AccountId = 111222, PriorityOrder = null, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 46, AccountId = 111222, PriorityOrder = null, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-4), CohortFullyApproved = true}, new Input { ApprenticeshipId = 47, AccountId = 111222, PriorityOrder = null, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 48, AccountId = 111222, PriorityOrder = null, ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, new Input { ApprenticeshipId = 49, AccountId = 111222, PriorityOrder = 2, ProviderId = provider201.ProviderId, ProviderName = provider201.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 50, AccountId = 111222, PriorityOrder = 2, ProviderId = provider201.ProviderId, ProviderName = provider201.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 51, AccountId = 111222, PriorityOrder = 2, ProviderId = provider201.ProviderId, ProviderName = provider201.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, new Input { ApprenticeshipId = 52, AccountId = 888888, PriorityOrder = 1, ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-1), CohortFullyApproved = true}, new Input { ApprenticeshipId = 53, AccountId = 888888, PriorityOrder = 2, ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-2), CohortFullyApproved = true}, new Input { ApprenticeshipId = 54, AccountId = 999999, PriorityOrder = 1, ProviderId = provider201.ProviderId, ProviderName = provider201.ProviderName, ApprenticeshipAgreedOn = null, CohortApprovedOn = DateTime.Now.AddMonths(-3), CohortFullyApproved = true}, }, new ExpectedOutput[] { new ExpectedOutput { ProviderId = provider102.ProviderId, ProviderName = provider102.ProviderName, PriorityOrder = 1}, new ExpectedOutput { ProviderId = provider201.ProviderId, ProviderName = provider201.ProviderName, PriorityOrder = 2}, new ExpectedOutput { ProviderId = provider103.ProviderId, ProviderName = provider103.ProviderName, PriorityOrder = 3}, new ExpectedOutput { ProviderId = provider101.ProviderId, ProviderName = provider101.ProviderName, PriorityOrder = 4}, } }; } public class Input { public long ApprenticeshipId { get; set; } public long AccountId { get; set; } public long ProviderId { get; set; } public string ProviderName { get; set; } public DateTime? ApprenticeshipAgreedOn { get; set; } public DateTime? CohortApprovedOn { get; set; } public bool CohortFullyApproved { get; set; } public int? PriorityOrder { get; set; } } public class ExpectedOutput { public long ProviderId { get; set; } public string ProviderName { get; set; } public int PriorityOrder { get; set; } } } public class GetProviderPaymentsPriorityQueryHandlerTestFixtures { public ProviderCommitmentsDbContext Db { get; set; } public GetProviderPaymentsPriorityQueryHandler Handler { get; set; } public Mock<ILogger<GetProviderPaymentsPriorityQueryHandler>> Logger { get; set; } public GetProviderPaymentsPriorityQueryHandlerTestFixtures() { Db = new ProviderCommitmentsDbContext(new DbContextOptionsBuilder<ProviderCommitmentsDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); Logger = new Mock<ILogger<GetProviderPaymentsPriorityQueryHandler>>(); Handler = new GetProviderPaymentsPriorityQueryHandler( new Lazy<ProviderCommitmentsDbContext>(() => Db), Logger.Object); } public Task<GetProviderPaymentsPriorityQueryResult> Handle(long accountId) { var query = new GetProviderPaymentsPriorityQuery(accountId); return Handler.Handle(query, CancellationToken.None); } public void SetCohort(long apprenticeshipId, long accountId, long providerId, string providerName, DateTime? agreedOn, DateTime? approvedOn, bool cohortApproved, int? priorityOrder) { // This line is required. // ReSharper disable once ObjectCreationAsStatement new UnitOfWorkContext(); var autoFixture = new Fixture(); var commitment = new Cohort( providerId, accountId, autoFixture.Create<long>(), Party.Employer, new UserInfo()); commitment.EmployerAndProviderApprovedOn = approvedOn; Db.Cohorts.Add(commitment); Db.SaveChanges(); if (cohortApproved) { commitment.EditStatus = EditStatus.Both; commitment.TransferSenderId = null; commitment.TransferApprovalStatus = TransferApprovalStatus.Approved; Db.SaveChanges(); } var apprenticeship = new Apprenticeship { Id = apprenticeshipId, CommitmentId = commitment.Id, AgreedOn = agreedOn }; Db.Apprenticeships.Add(apprenticeship); Db.SaveChanges(); if (!Db.Providers.Any(p => p.UkPrn == providerId)) { var provider = new Provider() { UkPrn = providerId, Name = providerName }; Db.Providers.Add(provider); Db.SaveChanges(); } if (priorityOrder.HasValue) { if (!Db.CustomProviderPaymentPriorities.Any(p => p.EmployerAccountId == accountId && p.ProviderId == providerId)) { var customProviderPaymentPriority = new CustomProviderPaymentPriority { ProviderId = providerId, EmployerAccountId = accountId, PriorityOrder = priorityOrder.Value }; Db.CustomProviderPaymentPriorities.Add(customProviderPaymentPriority); Db.SaveChanges(); } } } } }
//#define DEBUG using System; using System.Collections.Generic; namespace ICSimulator { public class Controller_Rate : Controller_ClassicBLESS { double[] m_isThrottled = new double[Config.N]; IPrioPktPool[] m_injPools = new IPrioPktPool[Config.N]; bool[] m_starved = new bool[Config.N]; //This represent the round-robin turns int[] throttleTable = new int[Config.N]; bool isThrottling; //This tell which group are allowed to run in a certain epoch int currentAllow = 0; int injLimit = 150; public Controller_Rate() { isThrottling = false; Console.WriteLine("init: Global_RR"); for (int i = 0; i < Config.N; i++) { MPKI[i]=0.0; numInject[i]=0; num_ins_last_epoch[i]=0; m_isThrottled[i]=0.0; L1misses[i]=0; } } public override void resetStat() { #if DEBUG Console.WriteLine("Reset MPKIs and num_ins after throttling"); #endif for (int i = 0; i < Config.N; i++) { MPKI[i]=0.0; num_ins_last_epoch[i] = (ulong)Simulator.stats.insns_persrc[i].Count; numInject[i]=0; L1misses[i]=0; } } void setThrottleRate(int node, double cond) { m_isThrottled[node] = cond; } // true to allow injection, false to block (throttle) // RouterFlit uses this function to determine whether it can inject or not // TODO: put this in a node? public override bool tryInject(int node) { if(Simulator.rand.NextDouble()>m_isThrottled[node]) { Simulator.stats.throttled_counts_persrc[node].Add(); return true; } else return false; } public override void setInjPool(int node, IPrioPktPool pool) { m_injPools[node] = pool; } public override void reportStarve(int node) { m_starved[node] = true; } void doThrottling() { for(int i=0;i<Config.N;i++) { //if we want to enable interval based throttling //if(throttleTable[i]>0) //if we always throttle if(numInject[i]>30) { //maximum throttling rate if(((double)numInject[i]/(double)injLimit)>0.6) setThrottleRate(i,0.6); else setThrottleRate(i,((double)numInject[i]/(double)injLimit)); } else setThrottleRate(i,0); //if((throttleTable[i]==currentAllow)||(throttleTable[i]==0)) //{ // setThrottleRate(i,false); //} //else //{ // setThrottleRate(i, true); //TODO: hack to test the common ground //setThrottleRate(i,false); //} } currentAllow++; //interval based if(currentAllow > Config.num_epoch) { //wrap around here currentAllow=1; } } public override void doStep() { // for (int i = 0; i < Config.N; i++) // { // this is not needed. Can be uncommented if we want to consider the starvation // avg_MPKI[i].accumulate(m_starved[i]); // avg_qlen[i].accumulate(m_injPools[i].Count); // m_starved[i] = false; // } if (Simulator.CurrentRound > 20000 && (Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0) { setThrottling(); resetStat(); } if (isThrottling && Simulator.CurrentRound > 20000 && (Simulator.CurrentRound % (ulong)Config.interval_length) == 0) { doThrottling(); } } void setThrottling() { #if DEBUG Console.Write("\n:: cycle {0} ::", Simulator.CurrentRound); #endif //get the MPKI value for (int i = 0; i < Config.N; i++) { if(num_ins_last_epoch[i]==0) //NumInject gets incremented in RouterFlit.cs MPKI[i]=((double)(numInject[i]*1000))/(Simulator.stats.insns_persrc[i].Count); else { if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]!=0) MPKI[i]=((double)(numInject[i]*1000))/(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]); else MPKI[i]=0; } } if(isThrottling) { //see if we can un-throttle the netowork double avg = 0.0; //check if we can go back to FFA for (int i = 0; i < Config.N; i++) { #if DEBUG Console.Write("[{1}] {0} |",(int)MPKI[i],i); #endif avg = avg + MPKI[i]; } avg = avg/Config.N; #if DEBUG Console.WriteLine("Estimating MPKI, min_thresh {1}: avg MPKI {0}",avg,Config.MPKI_max_thresh); #endif if(avg < Config.MPKI_min_thresh) { #if DEBUG Console.WriteLine("\n****OFF****Transition from Throttle mode to FFA! with avg MPKI {0}\n",avg); #endif isThrottling = false; //un-throttle the network for(int i=0;i<Config.N;i++) setThrottleRate(i,0.0); } } else { double avg = 0.0; // determine whether any node is congested int total_high = 0; for (int i = 0; i < Config.N; i++) avg = avg + MPKI[i]; avg = avg/Config.N; #if DEBUG Console.WriteLine("Estimating MPKI, max_thresh {1}: avg MPKI {0}",avg,Config.MPKI_max_thresh); #endif //greater than the max threshold if (avg > Config.MPKI_max_thresh) // TODO: Change this to a dynamic scheme { #if DEBUG Console.Write("Throttle mode turned on: cycle {0} (", Simulator.CurrentRound); #endif for (int i = 0; i < Config.N; i++) if (MPKI[i] > Config.MPKI_high_node) { total_high++; //right now we randomly pick one epoch to run //TODO: make this more intelligent throttleTable[i] = Simulator.rand.Next(Config.num_epoch); //TODO: why set it here? setThrottleRate(i, 0.6); //TODO: hack to test the common ground //setThrottleRate(i,false); #if DEBUG Console.Write("#ON#:Node {0} with MPKI {1} ",i,MPKI[i]); #endif } else { throttleTable[i]=0; setThrottleRate(i, 0.0); #if DEBUG Console.Write("@OFF@:Node {0} with MPKI {1} ",i,MPKI[i]); #endif } #if DEBUG Console.WriteLine(")"); #endif isThrottling = true; currentAllow = 1; } } } } }
//------------------------------------------------------------------------------ // <copyright file="RuntimeConfig.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Collections; using System.Configuration; using System.Configuration.Internal; using System.Security; using System.Security.Permissions; using System.Web; using System.Web.Util; using System.Web.Hosting; using System.Web.Configuration; namespace System.Web.Configuration { // // Internal, read-only access to configuration settings. // internal class RuntimeConfig { // // GetConfig() - get configuration appropriate for the current thread. // // Looks up the HttpContext on the current thread if it is available, // otherwise it uses the config at the app path. // // Use GetConfig(context) if a context is available, as it will avoid // the lookup for contxt on the current thread. // // For config derived from ConfigurationSection, this will either // return a non-null object or throw an exception. // // For config implemented with IConfigurationSectionHandler, this // may return null, non-null, or throw an exception. // static internal RuntimeConfig GetConfig() { if (!HttpConfigurationSystem.UseHttpConfigurationSystem) { return GetClientRuntimeConfig(); } HttpContext context = HttpContext.Current; if (context != null) { return GetConfig(context); } else { return GetAppConfig(); } } // // GetConfig(context) - gets configuration appropriate for the HttpContext. // The most efficient way to get config. // // For config derived from ConfigurationSection, this will either // return a non-null object or throw an exception. // // For config implemented with IConfigurationSectionHandler, this // may return null, non-null, or throw an exception. // static internal RuntimeConfig GetConfig(HttpContext context) { if (!HttpConfigurationSystem.UseHttpConfigurationSystem) { return GetClientRuntimeConfig(); } return context.GetRuntimeConfig(); } // // GetConfig(context, path) - returns the config at 'path'. // // This method is more efficient than not using context, as // the config cached in the context is used if it matches the // context path. // // For config derived from ConfigurationSection, this will either // return a non-null object or throw an exception. // // For config implemented with IConfigurationSectionHandler, this // may return null, non-null, or throw an exception. // static internal RuntimeConfig GetConfig(HttpContext context, VirtualPath path) { if (!HttpConfigurationSystem.UseHttpConfigurationSystem) { return GetClientRuntimeConfig(); } return context.GetRuntimeConfig(path); } // // GetConfig(path) - returns the config at 'path'. // // If 'path' is null, or is outside of the application path, then it // returns the application config. // // For efficientcy, use GetConfig(context) instead of this method // where possible. // // For config derived from ConfigurationSection, this will either // return a non-null object or throw an exception. // // For config implemented with IConfigurationSectionHandler, this // may return null, non-null, or throw an exception. // static internal RuntimeConfig GetConfig(string path) { return GetConfig(VirtualPath.CreateNonRelativeAllowNull(path)); } static internal RuntimeConfig GetConfig(VirtualPath path) { if (!HttpConfigurationSystem.UseHttpConfigurationSystem) { return GetClientRuntimeConfig(); } return CachedPathData.GetVirtualPathData(path, true).RuntimeConfig; } // // GetAppConfig() - returns the application config. // // For config derived from ConfigurationSection, this will either // return a non-null object or throw an exception. // // For config implemented with IConfigurationSectionHandler, this // may return null, non-null, or throw an exception. // static internal RuntimeConfig GetAppConfig() { if (!HttpConfigurationSystem.UseHttpConfigurationSystem) { return GetClientRuntimeConfig(); } return CachedPathData.GetApplicationPathData().RuntimeConfig; } // // GetRootWebConfig() - returns the root web configuration. // // For config derived from ConfigurationSection, this will either // return a non-null object or throw an exception. // // For config implemented with IConfigurationSectionHandler, this // may return null, non-null, or throw an exception. // static internal RuntimeConfig GetRootWebConfig() { if (!HttpConfigurationSystem.UseHttpConfigurationSystem) { return GetClientRuntimeConfig(); } return CachedPathData.GetRootWebPathData().RuntimeConfig; } // // GetMachineConfig() - returns the machine configuration. // // For config derived from ConfigurationSection, this will either // return a non-null object or throw an exception. // // For config implemented with IConfigurationSectionHandler, this // may return null, non-null, or throw an exception. // static internal RuntimeConfig GetMachineConfig() { if (!HttpConfigurationSystem.UseHttpConfigurationSystem) { return GetClientRuntimeConfig(); } return CachedPathData.GetMachinePathData().RuntimeConfig; } // // GetLKGConfig(context) - gets the nearest configuration available. // // This method is to be used in the few instances where we // cannot throw an exception if a config file has an error. // // This method will never throw an exception. If no config // is available, a request for a section will return null. // static internal RuntimeConfig GetLKGConfig(HttpContext context) { RuntimeConfig config = null; bool success = false; try { config = GetConfig(context); success = true; } catch { } if (!success) { config = GetLKGRuntimeConfig(context.Request.FilePathObject); } return config.RuntimeConfigLKG; } // // GetAppLKGConfig(path) - gets the nearest configuration available, // starting from the application path. // // This method is to be used in the few instances where we // cannot throw an exception if a config file has an error. // // This method will never throw an exception. If no config // is available, a request for a section will return null. // static internal RuntimeConfig GetAppLKGConfig() { RuntimeConfig config = null; bool success = false; try { config = GetAppConfig(); success = true; } catch { } if (!success) { config = GetLKGRuntimeConfig(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPathObject); } return config.RuntimeConfigLKG; } // // WHIDBEY sections // internal ConnectionStringsSection ConnectionStrings { get { return (ConnectionStringsSection) GetSection("connectionStrings", typeof(ConnectionStringsSection), ResultsIndex.ConnectionStrings); } } internal System.Net.Configuration.SmtpSection Smtp { get { return (System.Net.Configuration.SmtpSection) GetSection("system.net/mailSettings/smtp", typeof(System.Net.Configuration.SmtpSection)); } } internal AnonymousIdentificationSection AnonymousIdentification { get { return (AnonymousIdentificationSection) GetSection("system.web/anonymousIdentification", typeof(AnonymousIdentificationSection)); } } internal ProtocolsSection Protocols { get { return (ProtocolsSection) GetSection("system.web/protocols", typeof(ProtocolsSection)); } } internal AuthenticationSection Authentication { get { return (AuthenticationSection) GetSection("system.web/authentication", typeof(AuthenticationSection), ResultsIndex.Authentication); } } internal AuthorizationSection Authorization { get { return (AuthorizationSection) GetSection("system.web/authorization", typeof(AuthorizationSection), ResultsIndex.Authorization); } } // may return null internal HttpCapabilitiesDefaultProvider BrowserCaps { get { return (HttpCapabilitiesDefaultProvider) GetHandlerSection("system.web/browserCaps", typeof(HttpCapabilitiesDefaultProvider), ResultsIndex.BrowserCaps); } } internal ClientTargetSection ClientTarget { get { return (ClientTargetSection) GetSection("system.web/clientTarget", typeof(ClientTargetSection), ResultsIndex.ClientTarget); } } internal CompilationSection Compilation { get { return (CompilationSection) GetSection("system.web/compilation", typeof(CompilationSection), ResultsIndex.Compilation); } } internal CustomErrorsSection CustomErrors { get { return (CustomErrorsSection) GetSection("system.web/customErrors", typeof(CustomErrorsSection)); } } internal GlobalizationSection Globalization { get { return (GlobalizationSection) GetSection("system.web/globalization", typeof(GlobalizationSection), ResultsIndex.Globalization); } } internal DeploymentSection Deployment { get { return (DeploymentSection) GetSection("system.web/deployment", typeof(DeploymentSection)); } } internal FullTrustAssembliesSection FullTrustAssemblies { get { return (FullTrustAssembliesSection)GetSection("system.web/fullTrustAssemblies", typeof(FullTrustAssembliesSection)); } } internal HealthMonitoringSection HealthMonitoring { get { return (HealthMonitoringSection) GetSection("system.web/healthMonitoring", typeof(HealthMonitoringSection)); } } internal HostingEnvironmentSection HostingEnvironment { get { return (HostingEnvironmentSection) GetSection("system.web/hostingEnvironment", typeof(HostingEnvironmentSection)); } } internal HttpCookiesSection HttpCookies { get { return (HttpCookiesSection) GetSection("system.web/httpCookies", typeof(HttpCookiesSection), ResultsIndex.HttpCookies); } } internal HttpHandlersSection HttpHandlers { get { return (HttpHandlersSection) GetSection("system.web/httpHandlers", typeof(HttpHandlersSection), ResultsIndex.HttpHandlers); } } internal HttpModulesSection HttpModules { get { return (HttpModulesSection) GetSection("system.web/httpModules", typeof(HttpModulesSection), ResultsIndex.HttpModules); } } internal HttpRuntimeSection HttpRuntime { get { return (HttpRuntimeSection) GetSection("system.web/httpRuntime", typeof(HttpRuntimeSection), ResultsIndex.HttpRuntime); } } internal IdentitySection Identity { get { return (IdentitySection) GetSection("system.web/identity", typeof(IdentitySection), ResultsIndex.Identity); } } internal MachineKeySection MachineKey { get { return (MachineKeySection) GetSection("system.web/machineKey", typeof(MachineKeySection), ResultsIndex.MachineKey); } } internal MembershipSection Membership { get { return (MembershipSection) GetSection("system.web/membership", typeof(MembershipSection), ResultsIndex.Membership); } } internal PagesSection Pages { get { return (PagesSection) GetSection("system.web/pages", typeof(PagesSection), ResultsIndex.Pages); } } internal PartialTrustVisibleAssembliesSection PartialTrustVisibleAssemblies { get { return (PartialTrustVisibleAssembliesSection)GetSection("system.web/partialTrustVisibleAssemblies", typeof(PartialTrustVisibleAssembliesSection)); } } internal ProcessModelSection ProcessModel { get { return (ProcessModelSection) GetSection("system.web/processModel", typeof(ProcessModelSection)); } } internal ProfileSection Profile { get { return (ProfileSection) GetSection("system.web/profile", typeof(ProfileSection), ResultsIndex.Profile); } } internal RoleManagerSection RoleManager { get { return (RoleManagerSection) GetSection("system.web/roleManager", typeof(RoleManagerSection)); } } internal SecurityPolicySection SecurityPolicy { get { return (SecurityPolicySection) GetSection("system.web/securityPolicy", typeof(SecurityPolicySection)); } } internal SessionPageStateSection SessionPageState { get { return (SessionPageStateSection) GetSection("system.web/sessionPageState", typeof(SessionPageStateSection), ResultsIndex.SessionPageState); } } internal SessionStateSection SessionState { get { return (SessionStateSection) GetSection("system.web/sessionState", typeof(SessionStateSection)); } } internal SiteMapSection SiteMap { get { return (SiteMapSection) GetSection("system.web/siteMap", typeof(SiteMapSection)); } } internal TraceSection Trace { get { return (TraceSection) GetSection("system.web/trace", typeof(TraceSection)); } } internal TrustSection Trust { get { return (TrustSection) GetSection("system.web/trust", typeof(TrustSection)); } } internal UrlMappingsSection UrlMappings { get { return (UrlMappingsSection) GetSection("system.web/urlMappings", typeof(UrlMappingsSection), ResultsIndex.UrlMappings); } } internal Hashtable WebControls { get { return (Hashtable)GetSection("system.web/webControls", typeof(Hashtable), ResultsIndex.WebControls); } } internal WebPartsSection WebParts { get { return (WebPartsSection) GetSection("system.web/webParts", typeof(WebPartsSection), ResultsIndex.WebParts); } } internal XhtmlConformanceSection XhtmlConformance { get { return (XhtmlConformanceSection) GetSection("system.web/xhtmlConformance", typeof(XhtmlConformanceSection), ResultsIndex.XhtmlConformance); } } internal CacheSection Cache { get { return (CacheSection) GetSection("system.web/caching/cache", typeof(CacheSection)); } } internal OutputCacheSection OutputCache { get { return (OutputCacheSection) GetSection("system.web/caching/outputCache", typeof(OutputCacheSection), ResultsIndex.OutputCache); } } internal OutputCacheSettingsSection OutputCacheSettings { get { return (OutputCacheSettingsSection) GetSection("system.web/caching/outputCacheSettings", typeof(OutputCacheSettingsSection), ResultsIndex.OutputCacheSettings); } } internal SqlCacheDependencySection SqlCacheDependency { get { return (SqlCacheDependencySection) GetSection("system.web/caching/sqlCacheDependency", typeof(SqlCacheDependencySection)); } } ////////////////////////////// // // IMPLEMENTATION // ////////////////////////////// // Wraps calls to RuntimeConfig.GetConfig() when // the web config system is not being used. private static RuntimeConfig s_clientRuntimeConfig; // Wraps calls to RuntimeConfig.GetConfig() when // we must return null. private static RuntimeConfig s_nullRuntimeConfig; // Wraps calls to RuntimeConfig.GetConfig() when // we must return an error because there was an // unrecoverable error creating the config record. private static RuntimeConfig s_errorRuntimeConfig; // object used to indicate that result has not been evaluated private static object s_unevaluatedResult; // Commonly used results on every request. We cache these by index // into an array so we don't need to do hash table lookups, // type comparisons, and handle a demand for ConfigurationPermission // to retreive the config. internal enum ResultsIndex { // a valid index into the results array that is always unevaluated UNUSED = 0, Authentication, Authorization, BrowserCaps, ClientTarget, Compilation, ConnectionStrings, Globalization, HttpCookies, HttpHandlers, HttpModules, HttpRuntime, Identity, MachineKey, Membership, OutputCache, OutputCacheSettings, Pages, Profile, SessionPageState, WebControls, WebParts, UrlMappings, XhtmlConformance, // size of the results array, must be last in list SIZE }; // cached results // Per-path caching for perf reason. Available only to internal components. private object[] _results; // LKG config private RuntimeConfigLKG _runtimeConfigLKG; // for http configuration, the ConfigurationRecord on which we call GetConfig protected IInternalConfigRecord _configRecord; // classes implementing LKG may return null from GetSectionObject private bool _permitNull; static RuntimeConfig() { s_unevaluatedResult = new object(); // Ensure that we have an error config record available if we // get an unrecoverable error situation. GetErrorRuntimeConfig(); } // ctor used by CachedPathData to wrap the ConfigurationRecord internal RuntimeConfig(IInternalConfigRecord configRecord) : this(configRecord, false) {} protected RuntimeConfig(IInternalConfigRecord configRecord, bool permitNull) { _configRecord = configRecord; _permitNull = permitNull; // initialize results cache _results = new object[(int)ResultsIndex.SIZE]; for (int i = 0; i < _results.Length; i++) { _results[i] = s_unevaluatedResult; } } private RuntimeConfigLKG RuntimeConfigLKG { get { if (_runtimeConfigLKG == null) { lock (this) { if (_runtimeConfigLKG == null) { _runtimeConfigLKG = new RuntimeConfigLKG(_configRecord); } } } return _runtimeConfigLKG; } } internal IInternalConfigRecord ConfigRecord { get { return _configRecord; } } // Create the single instance of the wrapper for ConfigurationManager configuration. static RuntimeConfig GetClientRuntimeConfig() { if (s_clientRuntimeConfig == null) { s_clientRuntimeConfig = new ClientRuntimeConfig(); } return s_clientRuntimeConfig; } // Create the single instance of the wrapper for null configuration. static RuntimeConfig GetNullRuntimeConfig() { if (s_nullRuntimeConfig == null) { s_nullRuntimeConfig = new NullRuntimeConfig(); } return s_nullRuntimeConfig; } // Create the single instance of the wrapper for error configuration. static internal RuntimeConfig GetErrorRuntimeConfig() { if (s_errorRuntimeConfig == null) { s_errorRuntimeConfig = new ErrorRuntimeConfig(); } return s_errorRuntimeConfig; } // Get the config object for a section [ConfigurationPermission(SecurityAction.Assert, Unrestricted=true)] protected virtual object GetSectionObject(string sectionName) { return _configRecord.GetSection(sectionName); } // // Return a config implemented by IConfigurationHandler, // and use the runtime cache to store it for quick retreival without // having to hit a config record and a demand for ConfigurationPermission. // private object GetHandlerSection(string sectionName, Type type, ResultsIndex index) { // check the results cache object result = _results[(int)index]; if (result != s_unevaluatedResult) { return result; } // Get the configuration object. // // Note that it is legal for an IConfigurationSectionHandler implementation // to return null. result = GetSectionObject(sectionName); // verify the object is of the expected type if (result != null && result.GetType() != type) { throw new ConfigurationErrorsException(SR.GetString(SR.Config_unable_to_get_section, sectionName)); } // store into results cache if (index != ResultsIndex.UNUSED) { _results[(int)index] = result; } return result; } // // Return a configuration section without checking the runtime cache. // private object GetSection(string sectionName, Type type) { return GetSection(sectionName, type, ResultsIndex.UNUSED); } // // Return a configuration section, and use the runtime cache to store it for // quick retreival without having to hit a config record and a demand for // ConfigurationPermission. // private object GetSection(string sectionName, Type type, ResultsIndex index) { // check the results cache object result = _results[(int)index]; if (result != s_unevaluatedResult) { return result; } // get the configuration object result = GetSectionObject(sectionName); if (result == null) { // A section implemented by ConfigurationSection may not return null, // but various error handling subclasses of RuntimeConfig may need it. // Throw an error if null is not permitted. if (!_permitNull) { throw new ConfigurationErrorsException(SR.GetString(SR.Config_unable_to_get_section, sectionName)); } } else { // verify the object is of the expected type if (result.GetType() != type) { throw new ConfigurationErrorsException(SR.GetString(SR.Config_unable_to_get_section, sectionName)); } } // store into results cache if (index != ResultsIndex.UNUSED) { _results[(int)index] = result; } return result; } // // There are extreme cases where we cannot even retreive the CachedPathData // for a path - such as when MapPath deems the path to be suspicious. // In these cases, walk the hierarchy upwards until we are able to retreive // a CachedPathData and its associated RuntimeConfig. // static private RuntimeConfig GetLKGRuntimeConfig(VirtualPath path) { try { // Start with the parent of the path. path = path.Parent; } catch { path = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPathObject; } // Walk the path hierarchy until we can succesfully get a RuntimeConfig. while (path != null) { try { return GetConfig(path); } catch { path = path.Parent; } } try { return GetRootWebConfig(); } catch { } try { return GetMachineConfig(); } catch { } return GetNullRuntimeConfig(); } } }
//----------------------------------------------------------------------- // <copyright file="SerializationTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.ComponentModel; using System.Diagnostics; using Csla.Serialization; using Csla.Configuration; using Csla.Test.ValidationRules; using UnitDriven; using System.Threading.Tasks; using System.Security.Claims; using Csla.TestHelpers; using Microsoft.Extensions.DependencyInjection; #if NUNIT using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; #else using Microsoft.VisualStudio.TestTools.UnitTesting; using Csla.Serialization.Mobile; using System.IO; #endif namespace Csla.Test.Serialization { [TestClass()] public class SerializationTests : TestBase { private static TestDIContext _testDIContext; [Serializable] private class TestCollection : BusinessBindingListBase<TestCollection, TestItem> { } [Serializable] private class TestItem : BusinessBase<TestItem> { protected override object GetIdValue() { return 0; } public TestItem() { MarkAsChild(); } } private static ClaimsPrincipal GetPrincipal(params string[] roles) { var identity = new ClaimsIdentity(); foreach (var item in roles) identity.AddClaim(new Claim(ClaimTypes.Role, item)); return new ClaimsPrincipal(identity); } [ClassInitialize] public static void ClassInitialize(TestContext context) { _testDIContext = TestDIContextFactory.CreateDefaultContext(); } [TestMethod] public void SerializeDataPortalException() { var obj = new Csla.Server.DataPortalException("test message", new Exception("inner message"), null); var applicationContext = _testDIContext.CreateTestApplicationContext(); var cloner = new Core.ObjectCloner(applicationContext); var obj2 = (Csla.Server.DataPortalException)cloner.Clone(obj); Assert.IsFalse(ReferenceEquals(obj, obj2)); Assert.AreEqual(obj.Message, obj2.Message); } [TestMethod] public void CorrectDefaultSerializer() { var serializer = ApplicationContext.SerializationFormatter; Assert.IsTrue(serializer == typeof(MobileFormatter)); } [TestMethod()] public void TestWithoutSerializableHandler() { IDataPortal<SerializationRoot> dataPortal = _testDIContext.CreateDataPortal<SerializationRoot>(); TestResults.Reinitialise(); UnitTestContext context = GetContext(); SerializationRoot root = SerializationRoot.NewSerializationRoot(dataPortal); nonSerializableEventHandler handler = new nonSerializableEventHandler(); handler.Reg(root); root.Data = "something"; context.Assert.AreEqual("1", TestResults.GetResult("PropertyChangedFiredCount")); root.Data = "something else"; context.Assert.AreEqual("2", TestResults.GetResult("PropertyChangedFiredCount")); //serialize an object with eventhandling objects that are nonserializable root = root.Clone(); root.Data = "something new"; //still at 2 even though we changed the property again //when the clone method performs serialization, the nonserializable //object containing an event handler for the propertyChanged event //is lost context.Assert.AreEqual("2", TestResults.GetResult("PropertyChangedFiredCount")); context.Assert.Success(); } [TestMethod()] public void Clone() { TestResults.Reinitialise(); UnitTestContext context = GetContext(); SerializationRoot root = new SerializationRoot(); root = (SerializationRoot)root.Clone(); context.Assert.AreEqual( "true", TestResults.GetResult("Deserialized"), "Deserialized not called"); context.Assert.Success(); } [TestMethod()] public void SerializableEvents() { IDataPortal<SerializationRoot> dataPortal = _testDIContext.CreateDataPortal<SerializationRoot>(); TestResults.Reinitialise(); UnitTestContext context = GetContext(); SerializationRoot root = SerializationRoot.NewSerializationRoot(dataPortal); TestEventSink handler = new TestEventSink(); root.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler (OnIsDirtyChanged); root.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler (StaticOnIsDirtyChanged); root.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler (PublicStaticOnIsDirtyChanged); root.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler (OnIsDirtyChanged); //will call this method twice since it is assigned twice handler.Reg(root); root.Data = "abc"; context.Assert.AreEqual("abc", root.Data, "Data value not set"); context.Assert.AreEqual( "OnIsDirtyChanged", TestResults.GetResult("OnIsDirtyChanged"), "Didn't call local handler"); context.Assert.AreEqual( "StaticOnIsDirtyChanged", TestResults.GetResult("StaticOnIsDirtyChanged"), "Didn't call static handler"); Assert.AreEqual( "PublicStaticOnIsDirtyChanged", TestResults.GetResult("PublicStaticOnIsDirtyChanged"), "Didn't call public static handler"); Assert.AreEqual( "Test.OnIsDirtyChanged", TestResults.GetResult("Test.OnIsDirtyChanged"), "Didn't call serializable handler"); Assert.AreEqual( "Test.PrivateOnIsDirtyChanged", TestResults.GetResult("Test.PrivateOnIsDirtyChanged"), "Didn't call serializable private handler"); root = (SerializationRoot)root.Clone(); TestResults.Reinitialise(); root.Data = "xyz"; context.Assert.AreEqual("xyz", root.Data, "Data value not set"); context.Assert.AreEqual("", TestResults.GetResult("OnIsDirtyChanged"), "Called local handler after clone"); context.Assert.AreEqual("", TestResults.GetResult("StaticOnIsDirtyChanged"), "Called static handler after clone"); context.Assert.AreEqual( "PublicStaticOnIsDirtyChanged", TestResults.GetResult("PublicStaticOnIsDirtyChanged"), "Didn't call public static handler after clone"); context.Assert.AreEqual( "Test.OnIsDirtyChanged", TestResults.GetResult("Test.OnIsDirtyChanged"), "Didn't call serializable handler after clone"); context.Assert.AreEqual("", TestResults.GetResult("Test.PrivateOnIsDirtyChanged"), "Called serializable private handler after clone"); context.Assert.Success(); } [TestMethod()] public void TestSerializableEventsActionFails() { IDataPortal<SerializationRoot> dataPortal = _testDIContext.CreateDataPortal<SerializationRoot>(); var root = SerializationRoot.NewSerializationRoot(dataPortal); var nonSerClass = new NonSerializedClass(); Action<object, PropertyChangedEventArgs> h = (sender, eventArgs) => { nonSerClass.Do(); }; var method = typeof(Action<object, PropertyChangedEventArgs>).GetMethod("Invoke"); var delgate = (PropertyChangedEventHandler)(object)method.CreateDelegate(typeof(PropertyChangedEventHandler), h); root.PropertyChanged += delgate; // TODO: Should this test target another formatter, or just be deleted? //var b = new BinaryFormatterWrapper(); //try //{ // b.Serialize(new MemoryStream(), root); // Assert.Fail("Serialization should have thrown an exception"); //} //catch (System.Runtime.Serialization.SerializationException) //{ // // serialization failed as expected //} } [TestMethod()] public void TestSerializableEventsActionSucceeds() { IDataPortal<OverrideSerializationRoot> dataPortal = _testDIContext.CreateDataPortal<OverrideSerializationRoot>(); var root = OverrideSerializationRoot.NewOverrideSerializationRoot(dataPortal); var nonSerClass = new NonSerializedClass(); Action<object, PropertyChangedEventArgs> h = (sender, eventArgs) => { nonSerClass.Do(); }; var method = typeof(Action<object, PropertyChangedEventArgs>).GetMethod("Invoke"); var delgate = (PropertyChangedEventHandler)(object)method.CreateDelegate(typeof(PropertyChangedEventHandler), h); root.PropertyChanged += delgate; Action<object, PropertyChangingEventArgs> h1 = (sender, eventArgs) => { nonSerClass.Do(); }; var method1 = typeof(Action<object, PropertyChangingEventArgs>).GetMethod("Invoke"); var delgate1 = (PropertyChangingEventHandler)(object)method1.CreateDelegate(typeof(PropertyChangingEventHandler), h1); root.PropertyChanging += delgate1; // TODO: Would this test make sense if upgraded to MobileFormatter? //var b = new BinaryFormatterWrapper(); //b.Serialize(new MemoryStream(), root); } [TestMethod()] [TestCategory("SkipWhenLiveUnitTesting")] public async Task TestValidationRulesAfterSerialization() { IDataPortal<HasRulesManager> dataPortal = _testDIContext.CreateDataPortal<HasRulesManager>(); UnitTestContext context = GetContext(); var root = await dataPortal.CreateAsync(new HasRulesManager.Criteria()); root.Name = ""; context.Assert.AreEqual(false, root.IsValid, "root should not start valid"); root = root.Clone(); context.Assert.AreEqual(false, root.IsValid, "root should not be valid after clone"); root.Name = "something"; context.Assert.AreEqual(true, root.IsValid, "root should be valid after property set"); root = root.Clone(); context.Assert.AreEqual(true, root.IsValid, "root should be valid after second clone"); context.Assert.Success(); context.Complete(); } [TestMethod()] public void TestSerializationCslaBinaryReaderWriterList() { IDataPortal<BinaryReaderWriterTestClassList> dataPortal = _testDIContext.CreateDataPortal<BinaryReaderWriterTestClassList>(); var test = BinaryReaderWriterTestClassList.NewBinaryReaderWriterTestClassList(dataPortal); BinaryReaderWriterTestClassList result; test.Setup(); var applicationContext = _testDIContext.CreateTestApplicationContext(); MobileFormatter formatter = new MobileFormatter(applicationContext); var serialized = formatter.SerializeToDTO(test); CslaBinaryWriter writer = new CslaBinaryWriter(applicationContext); byte[] data; using (var stream = new MemoryStream()) { writer.Write(stream, serialized); data = stream.ToArray(); } CslaBinaryReader reader = new CslaBinaryReader(applicationContext); using (var stream = new MemoryStream(data)) { var deserialized = reader.Read(stream); result = (BinaryReaderWriterTestClassList)formatter.DeserializeFromDTO(deserialized); } Assert.AreEqual(test.Count, result.Count); for (int i = 0; i < test.Count; i++) { Assert.AreEqual(test[i].CharTest, result[i].CharTest); Assert.AreEqual(test[i].DateTimeOffsetTest, result[i].DateTimeOffsetTest); Assert.AreEqual(test[i].DateTimeTest, result[i].DateTimeTest); Assert.AreEqual(test[i].DecimalTest, result[i].DecimalTest); Assert.AreEqual(test[i].DoubleTest, result[i].DoubleTest); Assert.AreEqual(test[i].EnumTest, result[i].EnumTest); Assert.AreEqual(test[i].GuidTest, result[i].GuidTest); Assert.AreEqual(test[i].Int16Test, result[i].Int16Test); Assert.AreEqual(test[i].Int32Test, result[i].Int32Test); Assert.AreEqual(test[i].Int64Test, result[i].Int64Test); Assert.AreEqual(test[i].SByteTest, result[i].SByteTest); Assert.AreEqual(test[i].SingleTest, result[i].SingleTest); Assert.AreEqual(test[i].StringTest, result[i].StringTest); Assert.AreEqual(test[i].TimeSpanTest, result[i].TimeSpanTest); Assert.AreEqual(test[i].UInt16Test, result[i].UInt16Test); Assert.AreEqual(test[i].UInt32Test, result[i].UInt32Test); Assert.AreEqual(test[i].UInt64Test, result[i].UInt64Test); Assert.AreEqual(test[i].EmptySmartDateTest, result[i].EmptySmartDateTest); Assert.AreEqual(test[i].EmptySmartDateTest.FormatString, result[i].EmptySmartDateTest.FormatString); Assert.AreEqual(test[i].EmptySmartDateTest.EmptyIsMin, result[i].EmptySmartDateTest.EmptyIsMin); Assert.AreEqual(test[i].EmptySmartDateTest.IsEmpty, result[i].EmptySmartDateTest.IsEmpty); Assert.AreEqual(test[i].EmptySmartDateTest.Date, result[i].EmptySmartDateTest.Date); Assert.AreEqual(test[i].FilledSmartDateTest, result[i].FilledSmartDateTest); Assert.AreEqual(test[i].FilledSmartDateTest.FormatString, result[i].FilledSmartDateTest.FormatString); Assert.AreEqual(test[i].FilledSmartDateTest.EmptyIsMin, result[i].FilledSmartDateTest.EmptyIsMin); Assert.AreEqual(test[i].FilledSmartDateTest.IsEmpty, result[i].FilledSmartDateTest.IsEmpty); Assert.AreEqual(test[i].FilledSmartDateTest.Date, result[i].FilledSmartDateTest.Date); } } [TestMethod()] public void TestSerializationCslaBinaryReaderWriter() { IDataPortal<BinaryReaderWriterTestClass> dataPortal = _testDIContext.CreateDataPortal<BinaryReaderWriterTestClass>(); var test = BinaryReaderWriterTestClass.NewBinaryReaderWriterTestClass(dataPortal); BinaryReaderWriterTestClass result; test.Setup(); ApplicationContext applicationContext = _testDIContext.CreateTestApplicationContext(); MobileFormatter formatter = new MobileFormatter(applicationContext); var serialized = formatter.SerializeToDTO(test); CslaBinaryWriter writer = new CslaBinaryWriter(applicationContext); byte[] data; using (var stream = new MemoryStream()) { writer.Write(stream, serialized); data = stream.ToArray(); } CslaBinaryReader reader = new CslaBinaryReader(applicationContext); using (var stream = new MemoryStream(data)) { var deserialized = reader.Read(stream); result = (BinaryReaderWriterTestClass)formatter.DeserializeFromDTO(deserialized); } Assert.AreEqual(test.BoolTest, result.BoolTest); Assert.AreEqual(test.ByteArrayTest.Length, result.ByteArrayTest.Length); for (int i = 0; i < test.ByteArrayTest.Length; i++) { Assert.AreEqual(test.ByteArrayTest[i], result.ByteArrayTest[i]); } Assert.AreEqual(test.ByteTest, result.ByteTest); Assert.AreEqual(test.CharArrayTest.Length, result.CharArrayTest.Length); for (int i = 0; i < test.CharArrayTest.Length; i++) { Assert.AreEqual(test.CharArrayTest[i], result.CharArrayTest[i]); } Assert.AreEqual(test.CharTest, result.CharTest); Assert.AreEqual(test.DateTimeOffsetTest, result.DateTimeOffsetTest); Assert.AreEqual(test.DateTimeTest, result.DateTimeTest); Assert.AreEqual(test.DecimalTest, result.DecimalTest); Assert.AreEqual(test.DoubleTest, result.DoubleTest); Assert.AreEqual(test.EnumTest, result.EnumTest); Assert.AreEqual(test.GuidTest, result.GuidTest); Assert.AreEqual(test.Int16Test, result.Int16Test); Assert.AreEqual(test.Int32Test, result.Int32Test); Assert.AreEqual(test.Int64Test, result.Int64Test); Assert.AreEqual(test.SByteTest, result.SByteTest); Assert.AreEqual(test.SingleTest, result.SingleTest); Assert.AreEqual(test.StringTest, result.StringTest); Assert.AreEqual(test.TimeSpanTest, result.TimeSpanTest); Assert.AreEqual(test.UInt16Test, result.UInt16Test); Assert.AreEqual(test.UInt32Test, result.UInt32Test); Assert.AreEqual(test.UInt64Test, result.UInt64Test); Assert.AreEqual(test.EmptySmartDateTest, result.EmptySmartDateTest); Assert.AreEqual(test.EmptySmartDateTest.FormatString, result.EmptySmartDateTest.FormatString); Assert.AreEqual(test.EmptySmartDateTest.EmptyIsMin, result.EmptySmartDateTest.EmptyIsMin); Assert.AreEqual(test.EmptySmartDateTest.IsEmpty, result.EmptySmartDateTest.IsEmpty); Assert.AreEqual(test.EmptySmartDateTest.Date, result.EmptySmartDateTest.Date); Assert.AreEqual(test.FilledSmartDateTest, result.FilledSmartDateTest); Assert.AreEqual(test.FilledSmartDateTest.FormatString, result.FilledSmartDateTest.FormatString); Assert.AreEqual(test.FilledSmartDateTest.EmptyIsMin, result.FilledSmartDateTest.EmptyIsMin); Assert.AreEqual(test.FilledSmartDateTest.IsEmpty, result.FilledSmartDateTest.IsEmpty); Assert.AreEqual(test.FilledSmartDateTest.Date, result.FilledSmartDateTest.Date); } [TestMethod()] public void TestAuthorizationRulesAfterSerialization() { TestDIContext adminDIContext = TestDIContextFactory.CreateContext(GetPrincipal("Admin")); IDataPortal<Security.PermissionsRoot> dataPortal = _testDIContext.CreateDataPortal<Security.PermissionsRoot>(); Security.PermissionsRoot root = dataPortal.Create(); try { root.FirstName = "something"; Assert.Fail("Exception didn't occur"); } catch (Csla.Security.SecurityException ex) { Assert.AreEqual("Property set not allowed", ex.Message); } dataPortal = adminDIContext.CreateDataPortal<Security.PermissionsRoot>(); root = dataPortal.Create(); try { root.FirstName = "something"; } catch (Csla.Security.SecurityException) { Assert.Fail("exception occurred"); } // TODO: Not sure how to recreate this test now; can't change context under the data portal mid flight //Csla.ApplicationContext.User = new ClaimsPrincipal(); Csla.Test.Security.PermissionsRoot rootClone = root.Clone(); try { rootClone.FirstName = "something else"; Assert.Fail("Exception didn't occur"); } catch (Csla.Security.SecurityException ex) { Assert.AreEqual("Property set not allowed", ex.Message); } // TODO: Not sure how to recreate this test now; can't change context under the data portal mid flight //Csla.ApplicationContext.User = GetPrincipal("Admin"); try { rootClone.FirstName = "something new"; } catch (Csla.Security.SecurityException) { Assert.Fail("exception occurred"); } } private void OnIsDirtyChanged(object sender, PropertyChangedEventArgs e) { TestResults.AddOrOverwrite("OnIsDirtyChanged", "OnIsDirtyChanged"); } private static void StaticOnIsDirtyChanged(object sender, PropertyChangedEventArgs e) { TestResults.AddOrOverwrite("StaticOnIsDirtyChanged", "StaticOnIsDirtyChanged"); } public static void PublicStaticOnIsDirtyChanged(object sender, PropertyChangedEventArgs e) { TestResults.AddOrOverwrite("PublicStaticOnIsDirtyChanged", "PublicStaticOnIsDirtyChanged"); } [TestMethod] [TestCategory("SkipWhenLiveUnitTesting")] public void DCClone() { IDataPortal<DCRoot> dataPortal = _testDIContext.CreateDataPortal<DCRoot>(); System.Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] = "NetDataContractSerializer"; // TODO: NDCS has been dropped I think; is there a way to replicate this test with another formatter? //Assert.AreEqual( // Csla.ApplicationContext.SerializationFormatters.NetDataContractSerializer, // Csla.ApplicationContext.SerializationFormatter, // "Formatter should be NetDataContractSerializer"); DCRoot root = DCRoot.NewDCRoot(dataPortal); root.Data = 123; DCRoot clone = root.Clone(); Assert.IsFalse(ReferenceEquals(root, clone), "Object instance should be different"); Assert.AreEqual(root.Data, clone.Data, "Data should match"); Assert.IsTrue(root.IsDirty, "Root IsDirty should be true"); Assert.IsTrue(clone.IsDirty, "Clone IsDirty should be true"); } [TestMethod] public void DCEditLevels() { IDataPortal<DCRoot> dataPortal = _testDIContext.CreateDataPortal<DCRoot>(); DCRoot root = DCRoot.NewDCRoot(dataPortal); root.BeginEdit(); root.Data = 123; root.CancelEdit(); Assert.AreEqual(0, root.Data, "Data should be 0"); root.BeginEdit(); root.Data = 123; root.ApplyEdit(); Assert.AreEqual(123, root.Data, "Data should be 123"); } [TestMethod] public void AsyncLoadManagerSerializationTest() { IDataPortal<Basic.Children> dataPortal = _testDIContext.CreateDataPortal<Basic.Children>(); IDataPortal<Basic.Child> childDataPortal = _testDIContext.CreateDataPortal<Basic.Child>(); Csla.Test.Basic.Children list = Csla.Test.Basic.Children.NewChildren(dataPortal); list.Add(childDataPortal, "1"); list.Add(childDataPortal, "2"); IEditableObject item = list[1] as IEditableObject; int editLevel = (int)item.GetType().GetProperty("EditLevel", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy).GetValue(item, null); object manager = item.GetType().GetProperty("LoadManager", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy).GetValue(item, null); item.BeginEdit(); int newEditLevel = (int)item.GetType().GetProperty("EditLevel", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy).GetValue(item, null); Assert.AreEqual(editLevel + 1, newEditLevel, "Edit level incorrect after begin edit"); } [TestMethod] public void SerializeCommand() { ApplicationContext applicationContext = _testDIContext.CreateTestApplicationContext(); var cmd = new TestCommand(); cmd.Name = "test data"; // TODO: Not sure how to replicate the object cloner in Csla 6 var buffer = new MemoryStream(); // var bf = (TestCommand)Csla.Core.ObjectCloner.Clone(cmd); // Assert.AreEqual(cmd.Name, bf.Name, "after BinaryFormatter"); // var ndcs = new System.Runtime.Serialization.NetDataContractSerializer(); // ndcs.Serialize(buffer, cmd); // buffer.Position = 0; // var n = (TestCommand)ndcs.Deserialize(buffer); // Assert.AreEqual(cmd.Name, n.Name, "after NDCS"); buffer = new MemoryStream(); var mf = new MobileFormatter(applicationContext); mf.Serialize(buffer, cmd); buffer.Position = 0; var m = (TestCommand)mf.Deserialize(buffer); Assert.AreEqual(cmd.Name, m.Name, "after MobileFormatter"); } [TestMethod] [TestCategory("SkipWhenLiveUnitTesting")] public void CommandOverDataPortal() { TestDIContext customDIContext = TestDIContextFactory.CreateDefaultContext(); // TODO: Get this custom proxy code included and working //TestDIContext customDIContext = TestDIContextFactory.CreateContext( //options => options //.Services.AddTransient<DataPortalClient.IDataPortalProxy, Csla.Testing.Business.TestProxies.AppDomainProxy>() //); IDataPortal<TestCommand> dataPortal = customDIContext.CreateDataPortal<TestCommand>(); var cmd = new TestCommand(); cmd.Name = "test data"; var result = dataPortal.Execute(cmd); Assert.IsFalse(ReferenceEquals(cmd, result), "References should not match"); Assert.AreEqual(cmd.Name + " server", result.Name); } #if NETFRAMEWORK [TestMethod] public void UseCustomSerializationFormatter() { TestDIContext customDIContext = TestDIContextFactory.CreateContext(options => options .Serialization(cfg => cfg .SerializationFormatter(typeof(NetDataContractSerializerWrapper)))); ApplicationContext applicationContext = customDIContext.CreateTestApplicationContext(); var formatter = SerializationFormatterFactory.GetFormatter(applicationContext); Assert.IsInstanceOfType(formatter, typeof(NetDataContractSerializerWrapper)); } // TODO: I don't think this test is relevant - NDCS has been dropped? //[TestMethod] //public void UseNetDataContractSerializer() //{ // System.Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] = "NetDataContractSerializer"; // try // { // var formatter = SerializationFormatterFactory.GetFormatter(); // Assert.AreEqual(ApplicationContext.SerializationFormatter, ApplicationContext.SerializationFormatters.NetDataContractSerializer); // Assert.IsInstanceOfType(formatter, typeof(NetDataContractSerializerWrapper)); // } // finally // { // System.Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] = null; // } //} #endif } [Serializable] public class TestCommand : CommandBase<TestCommand> { private static PropertyInfo<string> NameProperty = RegisterProperty<string>("Name"); public string Name { get { return ReadProperty(NameProperty); } set { LoadProperty(NameProperty, value); } } [Execute] protected void DataPortal_Execute() { Name = Name + " server"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Media; using LiveCharts; using LiveCharts.Configurations; using LiveCharts.Definitions.Series; using LiveCharts.Geared; using LiveCharts.Geared.Geometries; using LiveCharts.Wpf; using Monitor.Charting; using Monitor.Model.Charting; using NodaTime; using QuantConnect; using ScatterMarkerSymbol = Monitor.Model.Charting.ScatterMarkerSymbol; using Series = LiveCharts.Wpf.Series; using SeriesType = Monitor.Model.Charting.SeriesType; namespace Monitor.ViewModel.Charts { /// <summary> /// Chart component responsible for working with series /// </summary> public class SeriesChartComponent { private readonly IChartView _view; private readonly List<Color> _defaultColors = new List<Color> { Color.FromArgb(0, 0, 0, 0), Color.FromArgb(255, 0, 0, 0) }; private IPointEvaluator<OhlcInstantChartPoint> _ohlcChartPointEvaluator; private IPointEvaluator<InstantChartPoint> _chartPointEvaluator; private IPointEvaluator<InstantChartPoint> ChartPointEvaluator => _chartPointEvaluator ?? (_chartPointEvaluator = new InstantChartPointMapper(_view)); private IPointEvaluator<OhlcInstantChartPoint> OhlcChartPointEvaluator => _ohlcChartPointEvaluator ?? (_ohlcChartPointEvaluator = new OhlcInstantChartPointMapper(_view)); public SeriesChartComponent(IChartView view) { _view = view; } public static Resolution DetectResolution(SeriesDefinition series) { if (series.SeriesType == SeriesType.Candle) { // Candle data is supposed to be grouped. // Currently we group candle data by day. return Resolution.Daily; } var chartPoints = series.Values; // Check whether we have duplicates in day mode var dayDuplicates = chartPoints.GroupBy(cp => cp.X.ToUnixTimeTicks() / NodaConstants.TicksPerDay).Any(g => g.Count() > 1); if (!dayDuplicates) return Resolution.Daily; var hourDuplicates = chartPoints.GroupBy(cp => cp.X.ToUnixTimeTicks() / NodaConstants.TicksPerHour).Any(g => g.Count() > 1); if (!hourDuplicates) return Resolution.Hour; var minuteDuplicates = chartPoints.GroupBy(cp => cp.X.ToUnixTimeTicks() / NodaConstants.TicksPerMinute).Any(g => g.Count() > 1); if (!minuteDuplicates) return Resolution.Minute; var secondDuplicates = chartPoints.GroupBy(cp => cp.X.ToUnixTimeTicks() / NodaConstants.TicksPerSecond).Any(g => g.Count() > 1); if (!secondDuplicates) return Resolution.Second; return Resolution.Tick; } public Series BuildSeries(SeriesDefinition sourceSeries) { Series series; switch (sourceSeries.SeriesType) { case SeriesType.Line: series = new GLineSeries { Configuration = ChartPointEvaluator, Fill = Brushes.Transparent }; break; case SeriesType.Bar: series = new GColumnSeries { Configuration = ChartPointEvaluator, }; break; case SeriesType.Candle: series = new GCandleSeries { Configuration = OhlcChartPointEvaluator, IncreaseBrush = Brushes.Aquamarine, DecreaseBrush = Brushes.LightCoral, Fill = Brushes.Transparent }; break; case SeriesType.Scatter: series = new GScatterSeries { Configuration = ChartPointEvaluator, StrokeThickness = 1, GearedPointGeometry = GetGearedPointGeometry(sourceSeries.ScatterMarkerSymbol) }; break; default: throw new NotSupportedException(); } series.Title = sourceSeries.Name; series.PointGeometry = GetPointGeometry(sourceSeries.ScatterMarkerSymbol); // Check whether the series has a color configured if (_defaultColors.All(c => !sourceSeries.Color.Equals(c))) { // No default color present. use it for the stroke var brush = new SolidColorBrush(sourceSeries.Color); brush.Freeze(); switch (sourceSeries.SeriesType) { case SeriesType.Candle: series.Fill = brush; break; default: series.Stroke = brush; break; } } return series; } public void UpdateSeries(ISeriesView targetSeries, SeriesDefinition sourceSeries) { // Detect the data resolution of the source series. // Use it as chart resolution if needed. var detectedResolution = DetectResolution(sourceSeries); if (_view.Resolution > detectedResolution) _view.Resolution = detectedResolution; // QuantChart series are unix timestamp switch (sourceSeries.SeriesType) { case SeriesType.Scatter: case SeriesType.Bar: case SeriesType.Line: var existingCommonValues = (GearedValues<InstantChartPoint>)(targetSeries.Values ?? (targetSeries.Values = new GearedValues<InstantChartPoint>())); existingCommonValues.AddRange(sourceSeries.Values); break; case SeriesType.Candle: // Build daily candles var existingCandleValues = (ChartValues<OhlcInstantChartPoint>)(targetSeries.Values ?? (targetSeries.Values = new ChartValues<OhlcInstantChartPoint>())); var newValues = sourceSeries.Values.GroupBy(cp => Instant.MaxValue.Minus(cp.X).Days).Select( g => { return new OhlcInstantChartPoint { X = g.First().X, Open = (double)g.First().Y, Close = (double)g.Last().Y, Low = (double)g.Min(z => z.Y), High = (double)g.Max(z => z.Y) }; }).ToList(); // Update existing ohlc points. UpdateExistingOhlcPoints(existingCandleValues, newValues, Resolution.Daily); existingCandleValues.AddRange(newValues); break; default: throw new Exception($"SeriesType {sourceSeries.SeriesType} is not supported."); } } public void UpdateExistingOhlcPoints(IList<OhlcInstantChartPoint> existingPoints, IList<OhlcInstantChartPoint> updatedPoints, Resolution resolution) { // Check whether we are updating existing points if (existingPoints.Count <= 0) return; if (resolution != Resolution.Daily) { throw new ArgumentOutOfRangeException($"Resolution {resolution} is not supported. Only Day is supported."); } // Check whether we have new information for the last ohlc point var lastKnownDay = existingPoints.Last().X.ToUnixTimeSeconds() * 60 * 24; while (updatedPoints.Any() && (updatedPoints.First().X.ToUnixTimeSeconds() * 60 * 24 <= lastKnownDay)) // We assume we always show ohlc in day groups { // Update the last ohlc point with this inforrmation var refval = updatedPoints.First(); // find the value matching this day var ohlcEquityChartValue = existingPoints.Last(); // Update ohlc point with highest and lowest, and with the new closing price // Update the normal point with the new closing value ohlcEquityChartValue.High = Math.Max(refval.High, ohlcEquityChartValue.High); ohlcEquityChartValue.Low = Math.Min(refval.Low, ohlcEquityChartValue.Low); ohlcEquityChartValue.Close = refval.Close; // Remove this value, as it has been parsed into existing chart points updatedPoints.RemoveAt(0); } } private static GeometryShape GetGearedPointGeometry(ScatterMarkerSymbol symbol) { switch (symbol) { case ScatterMarkerSymbol.None: return null; case ScatterMarkerSymbol.Circle: return new Circle(); case ScatterMarkerSymbol.Square: return new Square(); case ScatterMarkerSymbol.Diamond: return new Diamond(); case ScatterMarkerSymbol.Triangle: return new Triangle(); case ScatterMarkerSymbol.TriangleDown: return new TriangleDown(); default: throw new ArgumentOutOfRangeException(nameof(symbol), symbol, null); } } private static Geometry GetPointGeometry(ScatterMarkerSymbol symbol) { switch (symbol) { case ScatterMarkerSymbol.None: return DefaultGeometries.None; case ScatterMarkerSymbol.Circle: return DefaultGeometries.Circle; case ScatterMarkerSymbol.Diamond: return DefaultGeometries.Diamond; case ScatterMarkerSymbol.Square: return DefaultGeometries.Square; case ScatterMarkerSymbol.Triangle: return DefaultGeometries.Triangle; case ScatterMarkerSymbol.TriangleDown: return Geometries.TriangleDown; default: return DefaultGeometries.Circle; } } } }
/* * 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 elasticbeanstalk-2010-12-01.normal.json service model. */ using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; namespace AWSSDK_DotNet35.UnitTests.TestTools { [TestClass] public class ElasticBeanstalkConstructorCustomizationsTests { [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void CheckDNSAvailabilityRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.CheckDNSAvailabilityRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void CreateApplicationRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.CreateApplicationRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void CreateApplicationVersionRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.CreateApplicationVersionRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void CreateConfigurationTemplateRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.CreateConfigurationTemplateRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void CreateEnvironmentRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.CreateEnvironmentRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DeleteApplicationRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.DeleteApplicationRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DeleteApplicationVersionRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.DeleteApplicationVersionRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DeleteConfigurationTemplateRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.DeleteConfigurationTemplateRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DeleteEnvironmentConfigurationRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.DeleteEnvironmentConfigurationRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DescribeApplicationsRequestConstructorTests() { } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DescribeApplicationVersionsRequestConstructorTests() { } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DescribeConfigurationOptionsRequestConstructorTests() { } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DescribeConfigurationSettingsRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.DescribeConfigurationSettingsRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DescribeEnvironmentResourcesRequestConstructorTests() { } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DescribeEnvironmentsRequestConstructorTests() { } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void DescribeEventsRequestConstructorTests() { } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void RebuildEnvironmentRequestConstructorTests() { } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void RequestEnvironmentInfoRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.RequestEnvironmentInfoRequest), new System.Type[] { typeof(EnvironmentInfoType), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void RestartAppServerRequestConstructorTests() { } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void RetrieveEnvironmentInfoRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.RetrieveEnvironmentInfoRequest), new System.Type[] { typeof(EnvironmentInfoType), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void TerminateEnvironmentRequestConstructorTests() { } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void UpdateApplicationRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.UpdateApplicationRequest), new System.Type[] { typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void UpdateApplicationVersionRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.UpdateApplicationVersionRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void UpdateConfigurationTemplateRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.UpdateConfigurationTemplateRequest), new System.Type[] { typeof(string), typeof(string), }); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void UpdateEnvironmentRequestConstructorTests() { } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Constructors"), TestCategory("ElasticBeanstalk")] public void ValidateConfigurationSettingsRequestConstructorTests() { EnsureConstructorExists(typeof(Amazon.ElasticBeanstalk.Model.ValidateConfigurationSettingsRequest), new System.Type[] { typeof(string), typeof(List<ConfigurationOptionSetting>), }); } void EnsureConstructorExists(System.Type type, System.Type[] constructorParams) { Assert.IsNotNull(type.GetConstructor(constructorParams)); } } }
//--------------------------------------------------------------------------- // <copyright file="AnnotationComponentManager.cs" company="Microsoft"> // Copyright(C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // AnnotationComponentManager // // History: // 04/01/2004 axelk: Created AnnotationComponentManager.cs // // Copyright(C) 2002 by Microsoft Corporation. All rights reserved. //--------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows; using System.Windows.Annotations; using System.Windows.Documents; using System.Windows.Media; namespace MS.Internal.Annotations.Component { /// <summary> /// Instances of this class manage listen for events from the annotation service and create/remove/modify annotation components in response. /// Annotation components are created via indirection through an AnnotationComponentChooser which is set in a DP on the app tree. /// Annotation components are hosted, wrapped inside AnnotationAdorners, in an AdornerLayer respective to the annotated element. /// Every time an annotation service is instantiated an instance of this class is created. /// </summary> internal class AnnotationComponentManager : DependencyObject { #region Constructors /// <summary> /// Return an annotation component manager. If an annotation service is passed in, manager will /// receive notification from the service. Otherwise it will expect to be called directly. /// </summary> /// <param name="service">optional, annotation service the annotation component manager will register on</param> internal AnnotationComponentManager(AnnotationService service) : base() { // Only register if a service was passed in. If no service was passed in, we will not receive events. // This means a client will be calling us directly. if (service != null) { service.AttachedAnnotationChanged += new AttachedAnnotationChangedEventHandler(AttachedAnnotationUpdateEventHandler); } } #endregion Constructors #region Internal Methods /// <summary> /// The given attached annotation was added by the annotation service /// Find annotation components for the given attached annotation, maintain /// mapping from attached annotation to annotation components, and add to the /// adorner layer if the annotation component is not already in a presentation context. /// </summary> /// <param name="attachedAnnotation">Attached annotation to add</param> /// <param name="reorder">If true - update components ZOrder after adding the component</param> internal void AddAttachedAnnotation(IAttachedAnnotation attachedAnnotation, bool reorder) { Debug.Assert(attachedAnnotation != null, "AttachedAnnotation should not be null"); IAnnotationComponent component = FindComponent(attachedAnnotation); if (component == null) return; AddComponent(attachedAnnotation, component, reorder); } /// <summary> /// The given attached annotation was removed by the annotation service. /// Find all annotation components and let them know. /// If an annotation component does not have any other attached annotations, remove it. /// Update the attachedAnnotations map. /// </summary> /// <param name="attachedAnnotation">Attached annotation to remove</param> /// <param name="reorder">If true - update components ZOrder after removing the component</param> internal void RemoveAttachedAnnotation(IAttachedAnnotation attachedAnnotation, bool reorder) { Debug.Assert(attachedAnnotation != null, "AttachedAnnotation should not be null"); if (!_attachedAnnotations.ContainsKey(attachedAnnotation)) { // note, this is not always a bug, since an annotation might have resolved, but no annotation component found // the tree traversal bug we have currently results in this failing even if annotation components were found, because // in certain cases annotationService.AttachedAnnotations returns wrong list. return; } IList<IAnnotationComponent> currentList = _attachedAnnotations[attachedAnnotation]; _attachedAnnotations.Remove(attachedAnnotation); // clean up the map foreach (IAnnotationComponent component in currentList) { component.RemoveAttachedAnnotation(attachedAnnotation); // let the annotation component know if (component.AttachedAnnotations.Count == 0) { // if it has no more attached annotations, remove it if (component.PresentationContext != null) component.PresentationContext.RemoveFromHost(component, reorder); } } } #endregion Internal Methods #region Private Methods /// <summary> /// Handle the notification coming from the service. Attached annotations can be added, removed, modified. /// Delegate to appropriate method /// </summary> /// <param name="sender">The sender of the event, an annotation service</param> /// <param name="e">The event arguments containing information on added/deleted/modified attached annotation.</param> private void AttachedAnnotationUpdateEventHandler(object sender, AttachedAnnotationChangedEventArgs e) { switch (e.Action) { case AttachedAnnotationAction.Added: this.AddAttachedAnnotation(e.AttachedAnnotation, true); break; case AttachedAnnotationAction.Deleted: this.RemoveAttachedAnnotation(e.AttachedAnnotation, true); break; case AttachedAnnotationAction.Loaded: this.AddAttachedAnnotation(e.AttachedAnnotation, false); break; case AttachedAnnotationAction.Unloaded: this.RemoveAttachedAnnotation(e.AttachedAnnotation, false); break; case AttachedAnnotationAction.AnchorModified: this.ModifyAttachedAnnotation(e.AttachedAnnotation, e.PreviousAttachedAnchor, e.PreviousAttachmentLevel); break; } } /// <summary> /// given an attachedAnnotation find the chooser attached at its parent /// and ask it to choose a component suitable to handle the attachedAnnotation /// </summary> /// <param name="attachedAnnotation">the attachedAnnotation we are to find a component for</param> /// <returns>an IAnnotationComponent that can handle the attachedAnnotation (or null)</returns> private IAnnotationComponent FindComponent(IAttachedAnnotation attachedAnnotation) { Debug.Assert(attachedAnnotation != null, "AttachedAnnotation should not be null"); UIElement annotatedElement = attachedAnnotation.Parent as UIElement; // casted from DependencyObject Debug.Assert(annotatedElement != null, "the annotatedElement should inherit from UIElement"); AnnotationComponentChooser chooser = AnnotationService.GetChooser(annotatedElement); // should we return a list instead? IAnnotationComponent component = chooser.ChooseAnnotationComponent(attachedAnnotation); return component; } /// <summary> /// Add an attached annotation to a component and add the component to the adorner layer /// if the annotation component is not already in a presentation context. /// </summary> /// <param name="attachedAnnotation">the attachedAnnotation we are to add to the component</param> /// <param name="component">the component we are to add to the adorner layer</param> /// <param name="reorder">if true - the z-order must be reevaluated</param> private void AddComponent(IAttachedAnnotation attachedAnnotation, IAnnotationComponent component, bool reorder) { UIElement annotatedElement = attachedAnnotation.Parent as UIElement; // casted from DependencyObject Debug.Assert(annotatedElement != null, "the annotatedElement should inherit from UIElement"); // if annotation component is already in presentation context, nothing else to do if (component.PresentationContext != null) return; // otherwise host in the appropriate adorner layer AdornerLayer layer = AdornerLayer.GetAdornerLayer(annotatedElement); // note, GetAdornerLayer requires UIElement if (layer == null) { if (PresentationSource.FromVisual(annotatedElement) == null) { // The annotated element is no longer part of the application tree. // This probably means we are out of [....] - trying to add an annotation // for an element that has already gone away. Bug # 1580288 tracks // the need to figure this out. return; } throw new InvalidOperationException(SR.Get(SRID.NoPresentationContextForGivenElement, annotatedElement)); } // add to the attachedAnnotations this.AddToAttachedAnnotations(attachedAnnotation, component); // let the annotation component know about the attached annotation // call add before adding to adorner layer so the component can be initialized component.AddAttachedAnnotation(attachedAnnotation); // this might cause recursion in modify if annotation component adds to annotation AdornerPresentationContext.HostComponent(layer, component, annotatedElement, reorder); } /// <summary> /// Service indicates attached annotation has changed. /// For now, take all annotation components maped from old attached annotation and map from new. /// Then iterate through annotation components to let them know. /// Note, this needs to change later. If modify is radical, existing component might not want it anymore, /// and new one might need to be found... /// </summary> /// <param name="attachedAnnotation">The modified attached annotation</param> /// <param name="previousAttachedAnchor">The previous attached anchor for the attached annotation</param> /// <param name="previousAttachmentLevel">The previous attachment level for the attached annotation</param> private void ModifyAttachedAnnotation(IAttachedAnnotation attachedAnnotation, object previousAttachedAnchor, AttachmentLevel previousAttachmentLevel) { Debug.Assert(attachedAnnotation != null, "attachedAnnotation should not be null"); Debug.Assert(previousAttachedAnchor != null, "previousAttachedAnchor should not be null"); // if there was no component found for this attached annotation // then we treat the modify case as an add if (!_attachedAnnotations.ContainsKey(attachedAnnotation)) { // this is not necessarily a bug, it can be that the old attached annotation does not have an // associated annotation component. this.AddAttachedAnnotation(attachedAnnotation, true); return; } // we have a previous component for this attached annotation // we find the chooser for the new attached annotation // and ask it to choose a component // 1- if it returned null then we just remove the attached annotation // 2- if it returned a different component, then we treat it as a remove/add // 3- if it returned the same component then we call ModifyAttachedAnnotation on the component IAnnotationComponent newComponent = FindComponent(attachedAnnotation); if (newComponent == null) { RemoveAttachedAnnotation(attachedAnnotation, true); } else { IList<IAnnotationComponent> currentList = _attachedAnnotations[attachedAnnotation]; //save the current list // if we found the new component in any of the list of components we already have for this // attached annotation if (currentList.Contains(newComponent)) { // ask the components to handle the anchor modification event foreach (IAnnotationComponent component in currentList) { component.ModifyAttachedAnnotation(attachedAnnotation, previousAttachedAnchor, previousAttachmentLevel); // let the annotation component know if (component.AttachedAnnotations.Count == 0) { // if component decides it can not handle it, remove it component.PresentationContext.RemoveFromHost(component, true); } } } else { // remove all components RemoveAttachedAnnotation(attachedAnnotation, true); // add the new component AddComponent(attachedAnnotation, newComponent, true); } } } /// <summary> /// Add to the map from attached annotations -> annotation components /// </summary> /// <param name="attachedAnnotation">The attached annotation to use as key</param> /// <param name="component">The component to add to list</param> private void AddToAttachedAnnotations(IAttachedAnnotation attachedAnnotation, IAnnotationComponent component) { Debug.Assert(attachedAnnotation != null, "attachedAnnotation should not be null"); Debug.Assert(component != null, "component should not be null"); IList<IAnnotationComponent> currentList; if (!_attachedAnnotations.TryGetValue(attachedAnnotation, out currentList)) { currentList = new List<IAnnotationComponent>(); _attachedAnnotations[attachedAnnotation] = currentList; } currentList.Add(component); } #endregion Private Methods #region Private Fields /// <summary> /// Map from attached annotation to list of annotation components. /// This map contains all attached anntotations the component manager currently knows. /// </summary> private Dictionary<IAttachedAnnotation, IList<IAnnotationComponent>> _attachedAnnotations = new Dictionary<IAttachedAnnotation, IList<IAnnotationComponent>>(); #endregion Private Fields } }
/* * 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 OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Terrain.PaintBrushes { /// <summary> /// Speed-Optimised Hybrid Erosion Brush /// /// As per Jacob Olsen's Paper /// http://www.oddlabs.com/download/terrain_generation.pdf /// </summary> public class OlsenSphere : ITerrainPaintableEffect { private const double nConst = 1024.0; private const NeighbourSystem type = NeighbourSystem.Moore; #region Supporting Functions private static int[] Neighbours(NeighbourSystem neighbourType, int index) { int[] coord = new int[2]; index++; switch (neighbourType) { case NeighbourSystem.Moore: switch (index) { case 1: coord[0] = -1; coord[1] = -1; break; case 2: coord[0] = -0; coord[1] = -1; break; case 3: coord[0] = +1; coord[1] = -1; break; case 4: coord[0] = -1; coord[1] = -0; break; case 5: coord[0] = -0; coord[1] = -0; break; case 6: coord[0] = +1; coord[1] = -0; break; case 7: coord[0] = -1; coord[1] = +1; break; case 8: coord[0] = -0; coord[1] = +1; break; case 9: coord[0] = +1; coord[1] = +1; break; default: break; } break; case NeighbourSystem.VonNeumann: switch (index) { case 1: coord[0] = 0; coord[1] = -1; break; case 2: coord[0] = -1; coord[1] = 0; break; case 3: coord[0] = +1; coord[1] = 0; break; case 4: coord[0] = 0; coord[1] = +1; break; case 5: coord[0] = -0; coord[1] = -0; break; default: break; } break; } return coord; } private enum NeighbourSystem { Moore, VonNeumann } ; #endregion #region ITerrainPaintableEffect Members public void PaintEffect(ITerrainChannel map, bool[,] mask, double rx, double ry, double rz, double strength, double duration, int startX, int endX, int startY, int endY) { strength = TerrainUtil.MetersToSphericalStrength(strength); int x, y; for (x = startX; x <= endX; x++) { for (y = startY; y <= endY; y++) { if (!mask[x, y]) continue; double z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength); if (z > 0) // add in non-zero amount { const int NEIGHBOUR_ME = 4; const int NEIGHBOUR_MAX = 9; double max = Double.MinValue; int loc = 0; for (int j = 0; j < NEIGHBOUR_MAX; j++) { if (j != NEIGHBOUR_ME) { int[] coords = Neighbours(type, j); coords[0] += x; coords[1] += y; if (coords[0] > map.Width - 1) continue; if (coords[1] > map.Height - 1) continue; if (coords[0] < 0) continue; if (coords[1] < 0) continue; double cellmax = map[x, y] - map[coords[0], coords[1]]; if (cellmax > max) { max = cellmax; loc = j; } } } double T = nConst / ((map.Width + map.Height) / 2.0); // Apply results if (0 < max && max <= T) { int[] maxCoords = Neighbours(type, loc); double heightDelta = 0.5 * max * z * duration; map[x, y] -= heightDelta; map[x + maxCoords[0], y + maxCoords[1]] += heightDelta; } } } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** Classes: NativeObjectSecurity class ** ** ===========================================================*/ using Microsoft.Win32; using System; using System.Collections; using System.Security.Principal; using System.Runtime.InteropServices; using System.Runtime.Versioning; using FileNotFoundException = System.IO.FileNotFoundException; using System.Globalization; using System.Diagnostics.Contracts; namespace System.Security.AccessControl { public abstract class NativeObjectSecurity : CommonObjectSecurity { #region Private Members private readonly ResourceType _resourceType; private ExceptionFromErrorCode _exceptionFromErrorCode = null; private object _exceptionContext = null; private readonly uint ProtectedDiscretionaryAcl = 0x80000000; private readonly uint ProtectedSystemAcl = 0x40000000; private readonly uint UnprotectedDiscretionaryAcl = 0x20000000; private readonly uint UnprotectedSystemAcl = 0x10000000; #endregion #region Delegates internal protected delegate System.Exception ExceptionFromErrorCode(int errorCode, string name, SafeHandle handle, object context); #endregion #region Constructors protected NativeObjectSecurity(bool isContainer, ResourceType resourceType) : base(isContainer) { _resourceType = resourceType; } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : this(isContainer, resourceType) { _exceptionContext = exceptionContext; _exceptionFromErrorCode = exceptionFromErrorCode; } internal NativeObjectSecurity(ResourceType resourceType, CommonSecurityDescriptor securityDescriptor) : this(resourceType, securityDescriptor, null) { } internal NativeObjectSecurity(ResourceType resourceType, CommonSecurityDescriptor securityDescriptor, ExceptionFromErrorCode exceptionFromErrorCode) : base(securityDescriptor) { _resourceType = resourceType; _exceptionFromErrorCode = exceptionFromErrorCode; } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : this(resourceType, CreateInternal(resourceType, isContainer, name, null, includeSections, true, exceptionFromErrorCode, exceptionContext), exceptionFromErrorCode) { } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections) : this(isContainer, resourceType, name, includeSections, null, null) { } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : this(resourceType, CreateInternal(resourceType, isContainer, null, handle, includeSections, false, exceptionFromErrorCode, exceptionContext), exceptionFromErrorCode) { } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections) : this(isContainer, resourceType, handle, includeSections, null, null) { } #endregion #region Private Methods private static CommonSecurityDescriptor CreateInternal(ResourceType resourceType, bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections, bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) { int error; RawSecurityDescriptor rawSD; if (createByName && name == null) { throw new ArgumentNullException(nameof(name)); } else if (!createByName && handle == null) { throw new ArgumentNullException(nameof(handle)); } error = Win32.GetSecurityInfo(resourceType, name, handle, includeSections, out rawSD); if (error != Interop.mincore.Errors.ERROR_SUCCESS) { System.Exception exception = null; if (exceptionFromErrorCode != null) { exception = exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.mincore.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.mincore.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.mincore.Errors.ERROR_INVALID_PARAMETER) { exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } else if (error == Interop.mincore.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException( SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) { exception = (name == null ? new FileNotFoundException() : new FileNotFoundException(name)); } else if (error == Interop.mincore.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else { Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32GetSecurityInfo() failed with unexpected error code {0}", error)); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } return new CommonSecurityDescriptor(isContainer, false /* isDS */, rawSD, true); } // // Attempts to persist the security descriptor onto the object // private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext) { WriteLock(); try { int error; SecurityInfos securityInfo = 0; SecurityIdentifier owner = null, group = null; SystemAcl sacl = null; DiscretionaryAcl dacl = null; if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null) { securityInfo |= SecurityInfos.Owner; owner = _securityDescriptor.Owner; } if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null) { securityInfo |= SecurityInfos.Group; group = _securityDescriptor.Group; } if ((includeSections & AccessControlSections.Audit) != 0) { securityInfo |= SecurityInfos.SystemAcl; if (_securityDescriptor.IsSystemAclPresent && _securityDescriptor.SystemAcl != null && _securityDescriptor.SystemAcl.Count > 0) { sacl = _securityDescriptor.SystemAcl; } else { sacl = null; } if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0) { securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl); } } if ((includeSections & AccessControlSections.Access) != 0 && _securityDescriptor.IsDiscretionaryAclPresent) { securityInfo |= SecurityInfos.DiscretionaryAcl; // if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl) { dacl = null; } else { dacl = _securityDescriptor.DiscretionaryAcl; } if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0) { securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl); } } if (securityInfo == 0) { // // Nothing to persist // return; } error = Win32.SetSecurityInfo(_resourceType, name, handle, securityInfo, owner, group, sacl, dacl); if (error != Interop.mincore.Errors.ERROR_SUCCESS) { System.Exception exception = null; if (_exceptionFromErrorCode != null) { exception = _exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.mincore.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.mincore.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.mincore.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException( SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.mincore.Errors.ERROR_INVALID_HANDLE) { exception = new NotSupportedException(SR.AccessControl_InvalidHandle); } else if (error == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) { exception = new FileNotFoundException(); } else if (error == Interop.mincore.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else { Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "Unexpected error code {0}", error)); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } // // Everything goes well, let us clean the modified flags. // We are in proper write lock, so just go ahead // this.OwnerModified = false; this.GroupModified = false; this.AccessRulesModified = false; this.AuditRulesModified = false; } finally { WriteUnlock(); } } #endregion #region Protected Methods // // Persists the changes made to the object // by calling the underlying Windows API // // This overloaded method takes a name of an existing object // protected sealed override void Persist(string name, AccessControlSections includeSections) { Persist(name, includeSections, _exceptionContext); } protected void Persist(string name, AccessControlSections includeSections, object exceptionContext) { if (name == null) { throw new ArgumentNullException(nameof(name)); } Contract.EndContractBlock(); Persist(name, null, includeSections, exceptionContext); } // // Persists the changes made to the object // by calling the underlying Windows API // // This overloaded method takes a handle to an existing object // protected sealed override void Persist(SafeHandle handle, AccessControlSections includeSections) { Persist(handle, includeSections, _exceptionContext); } protected void Persist(SafeHandle handle, AccessControlSections includeSections, object exceptionContext) { if (handle == null) { throw new ArgumentNullException(nameof(handle)); } Contract.EndContractBlock(); Persist(null, handle, includeSections, exceptionContext); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Loadi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace applicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for VirtualNetworkPeeringsOperations. /// </summary> public static partial class VirtualNetworkPeeringsOperationsExtensions { /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> public static void Delete(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName) { operations.DeleteAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> public static VirtualNetworkPeering Get(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName) { return operations.GetAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkPeering> GetAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> public static VirtualNetworkPeering CreateOrUpdate(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters) { return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkPeering> CreateOrUpdateAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> public static IPage<VirtualNetworkPeering> List(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName) { return operations.ListAsync(resourceGroupName, virtualNetworkName).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkPeering>> ListAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> public static void BeginDelete(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName) { operations.BeginDeleteAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> public static VirtualNetworkPeering BeginCreateOrUpdate(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkPeering> BeginCreateOrUpdateAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<VirtualNetworkPeering> ListNext(this IVirtualNetworkPeeringsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkPeering>> ListNextAsync(this IVirtualNetworkPeeringsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using SourceSafeTypeLib; using vsslib; namespace VssSvnConverter.Core { public class Options { public ILookup<string, string> Config; public bool Force; public bool Ask; public bool ImportUnimportantOnly; public string Prefix; public Regex FilterRx; public string SourceSafeIni; public string SourceSafeUser; public string SourceSafePassword; public Lazy<VSSDatabase> DB; // import public Func<string, bool> IncludePredicate; // cache public string CacheDir; public readonly HashSet<string> LatestOnly = new HashSet<string>(); public Regex[] LatestOnlyRx; // build commits public TimeSpan SilencioSpan; public bool MergeSameFileChanges; public bool UserMappingStrict; public string CombinedAuthor; public bool CommentAddVssFilesInfo; public bool CommentAddUserTime; public Regex[] UnimportantCheckinCommentRx; // import // git tfs svn public string ImportDriver; // GIT public string GitExe; public string GitDefaultAuthorDomain; public string GitRepoDir; public bool IsGitRepoDirExternal; public string GitStartAfterImport; public string GitStartAfterImportArgs; // TFS public string TfExe; public string TfsWorkTreeDir; public bool TfNoCheckStatusBeforeStartRevision; // SVN public string SvnRepoUrl; public string SvnWorkTreeDir; public bool IsSvnRepoDirExternal; // directories, which will be created as revision 1, before first import public string[] PreCreateDirs; // if specified, ss.exe will be used for retrieve files with known problems public string SSPath; // if specified, ss.exe will be used for retrieve files with known problems public List<Tuple<Regex, string>> MangleImportPath; public Options(string[] args) { Force = args.Any(a => a == "--force"); Ask = args.Any(a => a == "--ask"); ImportUnimportantOnly = args.Any(a => a == "--unimportant-only"); Prefix = args.Where(a => a.StartsWith("--prefix=")).Select(a => a.Substring("--prefix=".Length)).FirstOrDefault(); var filterRx = args.Where(a => a.StartsWith("--filter=")).Select(a => a.Substring("--filter=".Length)).FirstOrDefault(); if(filterRx != null) FilterRx = new Regex(filterRx, RegexOptions.IgnoreCase); } public void ReadConfig(string conf) { Config = File.ReadAllLines(conf) .Where(l => !string.IsNullOrEmpty(l)) .Select(l => l.Trim()) .Where(l => !l.StartsWith("#")) .Select(l => { var pos = l.IndexOf('='); if(pos == -1) { Console.WriteLine("Wrong line in config: {0}", l); Environment.Exit(-1); } return new { Key = l.Substring(0, pos).Trim(), Value = l.Substring(pos + 1).Trim()}; }) .ToLookup(p => p.Key, p => p.Value) ; SSPath = Config["ss.exe"].FirstOrDefault(); // cache CacheDir = Config["cache-dir"].DefaultIfEmpty(".cache").First(); LatestOnly.Clear(); foreach (var v in Config["latest-only"]) { LatestOnly.Add(v); } LatestOnlyRx = Config["latest-only-rx"].Select(rx => new Regex(rx, RegexOptions.IgnoreCase)).ToArray(); // commit setup // silent period SilencioSpan = Config["commit-silent-period"] .DefaultIfEmpty("120") .Select(Double.Parse) .Select(TimeSpan.FromMinutes) .First() ; // merge changes MergeSameFileChanges = Config["merge-changes"] .DefaultIfEmpty("false") .Select(bool.Parse) .First() ; CombinedAuthor = Config["combined-author"].FirstOrDefault(); UnimportantCheckinCommentRx = Config["unimportant-checkin-comment-rx"] .Select(s => new Regex(s, RegexOptions.IgnoreCase)) .ToArray() ; UserMappingStrict = Config["user-mapping-strict"] .DefaultIfEmpty("false") .Select(bool.Parse) .First() ; CommentAddVssFilesInfo = Config["comment-add-vss-files-info"] .DefaultIfEmpty("false") .Select(bool.Parse) .First() ; CommentAddUserTime = Config["comment-add-user-time"] .DefaultIfEmpty("false") .Select(bool.Parse) .First() ; ImportDriver = Config["import-driver"] .DefaultIfEmpty("svn") .First() .ToLowerInvariant() ; if (ImportDriver == "git") { GitExe = Config["git-exe"] .DefaultIfEmpty("git.exe") .First() ; GitRepoDir = Config["git-repo-dir"] .Select(p => Path.Combine(Environment.CurrentDirectory, p)) .FirstOrDefault() ; if (string.IsNullOrWhiteSpace(GitRepoDir)) { GitRepoDir = Path.Combine(Environment.CurrentDirectory, "_git_repo"); } else { IsGitRepoDirExternal = true; } GitDefaultAuthorDomain = Config["git-default-author-domain"] .DefaultIfEmpty("@dummy-email.org") .First() ; GitStartAfterImport = Config["git-start-after-import"] .FirstOrDefault() ; GitStartAfterImportArgs = Config["git-start-after-import-args"] .FirstOrDefault() ?? "" ; } if (ImportDriver == "tfs") { TfExe = Config["tf-exe"] .DefaultIfEmpty("tf.exe") .First() ; TfsWorkTreeDir = Config["tfs-worktree-dir"] .Select(p => Path.Combine(Environment.CurrentDirectory, p)) .FirstOrDefault() ; TfNoCheckStatusBeforeStartRevision = Config["tfs-no-check-status-every-revision"] .Select(p => p.ToLowerInvariant()) .Select(p => p == "1" || p == "yes" || p == "true") .FirstOrDefault() ; } if (ImportDriver == "svn") { SvnRepoUrl = Config["svn-repo-url"] .FirstOrDefault() ; if (string.IsNullOrWhiteSpace(SvnRepoUrl)) { SvnRepoUrl = Path.Combine(Environment.CurrentDirectory, "_svn_repo"); } else { IsSvnRepoDirExternal = true; } SvnWorkTreeDir = Config["svn-worktree-dir"] .Select(p => Path.Combine(Environment.CurrentDirectory, p)) .FirstOrDefault() ; if (string.IsNullOrWhiteSpace(SvnWorkTreeDir)) { SvnWorkTreeDir = Path.Combine(Environment.CurrentDirectory, "_svn_wc"); } } MangleImportPath = Config["mangle-import-path"] .Select(p => Tuple.Create(new Regex(p.Split(':')[0], RegexOptions.IgnoreCase), p.Split(':')[1])) .ToList() ; // open VSS DB if (DB != null && DB.IsValueCreated) { DB.Value.Close(); DB = null; } SourceSafeIni = Config["source-safe-ini"].DefaultIfEmpty("srcsafe.ini").First(); SourceSafeUser = Config["source-safe-user"].DefaultIfEmpty("").First(); SourceSafePassword = Config["source-safe-password"].DefaultIfEmpty("").First(); DB = new Lazy<VSSDatabase>(() => { Console.WriteLine("Initialize VSS driver...."); var db = new VSSDatabase(); db.Open(SourceSafeIni, SourceSafeUser, SourceSafePassword); Console.WriteLine("VSS driver initialized"); return db; }); SSExeHelper.SetupSS(SourceSafeIni, SourceSafeUser, SourceSafePassword); // include/exclude checks var checks = Config["import-pattern"] .Select(pat => new { Rx = new Regex(pat.Substring(1), RegexOptions.IgnoreCase), Exclude = pat.StartsWith("-") }) .ToArray() ; IncludePredicate = path => { var m = checks.FirstOrDefault(c => c.Rx.IsMatch(path)); if (m == null) return true; return !m.Exclude; }; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Printing; using System.Text; using System.Windows.Forms; using SPD.BL; using SPD.CommonObjects; using System.Threading; using SPD.CommonUtilities; using SPD.BL.Interfaces; using SPD.GUI.BLFactory; using System.Diagnostics; using System.IO; using System.Net; using System.Security.Principal; using System.Reflection; namespace SPD.GUI { /// <summary> /// Defined the Next Screen /// </summary> public enum NextScreen { /// <summary> /// Undefiend /// </summary> Undefined, /// <summary> /// NExt Action /// </summary> NextAction, /// <summary> /// Operation /// </summary> Operation, /// <summary> /// Visit /// </summary> Visit, /// <summary> /// Plan Operation /// </summary> planOperation, /// <summary> /// Next Action and Plan OP /// </summary> NextActionAndPlanOP, /// <summary> /// Change Patient /// </summary> ChagePatient, /// <summary> /// AddWaitingList /// </summary> AddWaitingList } /// <summary> /// /// </summary> public partial class MainForm : Form { #region members private NewPatientControl newPatientControl; private NewVisit newVisit; private PatientSearchControl patientSearchControl; private ISPDBL patComp; private VisitsControl visitsControl; private PatientData currentPatient; private OPControl newOperation; private FinalReportControl furtherTreatmentControl; private StoneReportControl stoneReportControl; private ShowOperationsControl showOperationsControl; private ImagesControl imagesControl; private PrintMorePatientsControl printMorePatientsControl; private BarDiagram barDiagramm; private BackupForm backupForm; private NextActionControl nextActionControl; private NextActionOverviewControl nextActionOverviewControl; private ImportControl importControl; private OverviewControl overviewControl; private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //protected internal System.Timers.Timer tmrFade; #endregion #region constructor /// <summary> /// Initializes a new instance of the <see cref="MainForm"/> class. /// </summary> public MainForm() { //this.tmrFade = new System.Timers.Timer(); //((System.ComponentModel.ISupportInitialize)(this.tmrFade)).BeginInit(); InitializeComponent(); //((System.ComponentModel.ISupportInitialize)(this.tmrFade)).EndInit(); ////Shows Dialog for BL selection //ServerSelectionForm serverSelectionForm = new ServerSelectionForm(); //serverSelectionForm.TopMost = true; //serverSelectionForm.ShowDialog(); ////Generate the Selected BusinessLogic //patComp = SPDLFactory.GetBussinessLogicObject(ServerSelectionForm.GetEndPointData());//new SPDBL(); patComp = new SPDBL(); this.newOperation = new OPControl(this.patComp); this.newOperation.Store += new NewOperationStoreEventHandler(newOperation_Store); this.newPatientControl = new NewPatientControl(this.patComp); this.newPatientControl.Store += new NewPatientStoreEventHandler(this.patientStore); this.patientSearchControl = new PatientSearchControl(); this.patientSearchControl.AddVisit += new AddVisitEventHandler(patientSearchControl_AddVisit); this.patientSearchControl.ChangePatientData += new ChangePatientDataEventHandler(patientSearchControl_ChangePatientData); this.patientSearchControl.ShowPatientData += new ShowPatientDataEventHandler(patientSearchControl_ShowPatientData); this.patientSearchControl.ShowVisits += new ShowVisitsEventHandler(patientSearchControl_ShowVisits); this.patientSearchControl.AddOperation += new AddOperationEventHandler(patientSearchControl_AddOperation); this.patientSearchControl.AddFurtherTreatment += new AddFurtherTreatmentEventHandler(patientSearchControl_AddFurtherTreatment); this.patientSearchControl.AddStoneReport += new AddStoneReportEventHandler(patientSearchControl_AddStoneReport); this.patientSearchControl.ShowOperations += new ShowOperationsEventHandler(patientSearchControl_ShowOperations); this.patientSearchControl.AddImages += new ImagesEventHandler(patientSearchControl_AddImages); this.patientSearchControl.SelectionChange += new SelectionChangeEventHandler(patientSearchControl_SelectionChange); this.patientSearchControl.PlanOP += new PlanOPEventHandler(patientSearchControl_PlanOP); this.patientSearchControl.NextAction += new NextActionEventHandler(patientSearchControl_NextAction); this.imagesControl = new ImagesControl(); this.imagesControl.Store += new PhotoStoreEventHandler(imagesControl_Store); this.imagesControl.Delete += new DeleteImageEventHandler(imagesControl_Delete); this.showOperationsControl = new ShowOperationsControl(); this.showOperationsControl.ChangeOP += new ChangeOPEventHandler(showOperationsControl_ChangeOP); this.newVisit = new NewVisit(this.patComp); this.visitsControl = new VisitsControl(); this.visitsControl.Change += new VisitChangeEventHandler(visitControl_VisitChange); this.newVisit.Store +=new NewVisitStoreEventHandler(this.visitStore); this.furtherTreatmentControl = new FinalReportControl(); this.furtherTreatmentControl.Store += new NewFinalReportStoreEventHandler(furtherTreatmentControl_Store); this.stoneReportControl = new StoneReportControl(); this.stoneReportControl.Store += new NewStoneReportStoreEventHandler(stoneReportControl_Store); this.printMorePatientsControl = new PrintMorePatientsControl(); this.barDiagramm = new BarDiagram(); this.backupForm = new BackupForm(); this.nextActionControl = new NextActionControl(this.patComp); this.nextActionOverviewControl = new NextActionOverviewControl(this.patComp); this.importControl = new ImportControl(this.patComp); this.overviewControl = new OverviewControl(this.patComp); Bitmap img; img = SPD.GUI.Properties.Resources.logogross; PictureBox picBox = new PictureBox(); picBox.Image = img; picBox.Size = new Size(591, 383); picBox.Location = new System.Drawing.Point(200, 10); this.Controls.Add(picBox); img = SPD.GUI.Properties.Resources.KinderurologieLogo; picBox = new PictureBox(); picBox.Image = img; picBox.Size = new Size(482, 323); picBox.Location = new System.Drawing.Point(259, 435); this.Controls.Add(picBox); // // tmrFade // //this.tmrFade.Interval = 10; //this.tmrFade.SynchronizingObject = this; //this.tmrFade.Elapsed += new System.Timers.ElapsedEventHandler(this.tmrFade_Elapsed); //this.Opacity = 0; //this.Show(); //tmrFade.Enabled = true; this.Text = Application.ProductName + " - " + Application.ProductVersion; // + " - Development Version!!"; this.menuStrip.Items["backupToolStripMenuItem"].Enabled = patComp.SupportsBackup(); ((ToolStripMenuItem)this.menuStrip.Items["settingsToolStripMenuItem"]).DropDownItems["databaseSettingsToolStripMenuItem"].Enabled = patComp.SupportDatabaseManagement(); } #endregion #region handler /////////// Find Patient Sub Events BEGIN void imagesControl_Store(object sender, PhotoStoreEventArgs e) { ImageData idata = e.Image; if (idata.PhotoID == 0) { // new Image idata.PatientID = currentPatient.Id; patComp.InsertImage(e.Image); } else { // change Image //patComp.UpdateImage(e.Image); } IList<ImageData> imageList = patComp.GetImagesByPatientID(currentPatient.Id); this.imagesControl.Initt(imageList); } void furtherTreatmentControl_Store(object sender, NewFinalReportStoreEventArgs e) { string ft = e.FinalReport; patComp.InsertFinalReport(ft,currentPatient.Id); } void stoneReportControl_Store(object sender, NewStoneReportStoreEventArgs e) { string sr = e.StoneReport; patComp.InsertStoneReport(sr, currentPatient.Id); } void imagesControl_Delete(object sender, DeleteImageEventArgs e) { ImageData idata = e.Image; patComp.DeleteImage(e.Image); IList<ImageData> imageList = patComp.GetImagesByPatientID(currentPatient.Id); this.imagesControl.Initt(imageList); } private void visitControl_VisitChange(object sender, VisitChangeEventArgs e) { this.Clear(patientSearchControl); this.activatePatientSearchControl(currentPatient); this.newVisit.Location = getPatientSearchSubMaskLocation(); this.newVisit.CurrentPatient = currentPatient; this.newVisit.Init(e.Visit); this.Controls.Add(this.newVisit); } void showOperationsControl_ChangeOP(object sender, ChangeOPEventArgs e) { this.Clear(patientSearchControl); this.activatePatientSearchControl(e.Patient); currentPatient = e.Patient; this.newOperation.Enabled = true; this.newOperation.Location = getPatientSearchSubMaskLocation(); this.newOperation.Init(e.Operation, currentPatient); this.Controls.Add(this.newOperation); this.newOperation.TextBoxOPTeam.Focus(); } /////////// Find Patient Sub Events END void newOperation_Store(object sender, NewOperationStoreEventArgs e) { OperationData odata = e.Operation; if (odata.OperationId == 0) { // new Operation odata.PatientId = currentPatient.Id; patComp.InsertOperation(e.Operation); } else { // change Visit patComp.UpdateOperation(e.Operation); } this.Controls.Remove(newOperation); putPatientSearchControl(currentPatient); this.patientSearchControl.ListViewPatients.Focus(); } private void putPatientSearchControl(PatientData currentPatient){ this.patientSearchControl.Location = getTopMaskLocation(); bool containsPatiensSearchControl = false; foreach (Control control in this.Controls) { if (control.GetType().Equals(patientSearchControl.GetType())) { containsPatiensSearchControl = true; } } if (!containsPatiensSearchControl) { this.Controls.Add(patientSearchControl); } activatePatientSearchControl(currentPatient); } private void activatePatientSearchControl(PatientData currentPatient) { this.currentPatient = currentPatient; this.patientSearchControl.Init(currentPatient, this.patComp); this.patientSearchControl.TextBoxFindName.Focus(); } ///////// newPatientControl Handler BEGIN ///////// newPatientControl Handler END /////////// patientSearchContro Events BEGIN void patientSearchControl_SelectionChange(object sender, SelectionChangeEventArgs e) { this.Clear(patientSearchControl); } void patientSearchControl_AddVisit(object sender, AddVisitEventArgs e) { preparePatientSearchSubControlChange(e.Patient); this.newVisit.Clear(); this.newVisit.Enabled = true; this.newVisit.Location = getPatientSearchSubMaskLocation(); this.newVisit.CurrentPatient = currentPatient; this.newVisit.Init(null); this.Controls.Add(this.newVisit); VisitData lastVisit = patComp.GetLastVisitByPatientID(currentPatient.Id); if (lastVisit != null) { this.newVisit.TextBoxDiagnosis.Text = lastVisit.ExtraDiagnosis; } this.newVisit.TextBoxCauseOfVisit.Focus(); } void patientSearchControl_ShowVisits(object sender, ShowVisitsEventArgs e) { this.preparePatientSearchSubControlChange(e.Patient); this.visitsControl.Clear(true); this.visitsControl.Location = getPatientSearchSubMaskLocation(); this.visitsControl.Init(currentPatient, patComp.GetVisitsByPatientID(currentPatient.Id)); this.Controls.Add(this.visitsControl); this.visitsControl.ListViewVisits.Focus(); } void patientSearchControl_AddOperation(object sender, AddOperationEventArgs e) { this.preparePatientSearchSubControlChange(e.Patient); this.newOperation.Clear(); this.newOperation.Enabled = true; this.newOperation.Location = getPatientSearchSubMaskLocation(); this.newOperation.Init(null, currentPatient); this.Controls.Add(this.newOperation); this.newOperation.TextBoxOPTeam.Focus(); } void patientSearchControl_ShowOperations(object sender, ShowOperationsEventArgs e) { this.preparePatientSearchSubControlChange(e.Patient); this.showOperationsControl.Clear(); this.showOperationsControl.Enabled = true; this.showOperationsControl.Location = getPatientSearchSubMaskLocation(); this.showOperationsControl.Init(currentPatient, this.patComp); this.Controls.Add(this.showOperationsControl); this.showOperationsControl.ListViewOperations.Focus(); } void patientSearchControl_PlanOP(object sender, PlanOPEventArgs e) { doPlanOperation(e.Patient); } private void doPlanOperation(PatientData patient) { Plan_OP planOP = new Plan_OP(); string lastDiagnosis = patComp.GetDiagnoseByPatientOfLastVisit(patient.Id); VisitData visit = patComp.GetLastVisitByPatientID(patient.Id); string lastTherapy = visit == null ? "" : visit.ExtraTherapy; planOP.init(patient, lastDiagnosis, lastTherapy); planOP.TopMost = this.TopMost; planOP.ShowDialog(); } void patientSearchControl_ShowPatientData(object sender, ShowPatientDataEventArgs e) { this.preparePatientSearchSubControlChange(e.Patient); this.newPatientControl.Enabled = false; this.newPatientControl.Location = getPatientSearchSubMaskLocation(); this.newPatientControl.Init(currentPatient); this.Controls.Add(this.newPatientControl); } void patientSearchControl_ChangePatientData(object sender, ChangePatientDataEventArgs e) { this.preparePatientSearchSubControlChange(e.Patient); this.newPatientControl.Enabled = true; this.newPatientControl.Location = getPatientSearchSubMaskLocation(); this.newPatientControl.Init(currentPatient); this.Controls.Add(this.newPatientControl); this.newPatientControl.TextBoxSurname.Focus(); this.newPatientControl.TextBoxSurname.Select(0, 0); } void patientSearchControl_AddFurtherTreatment(object sender, AddFurtherTreatmentEventArgs e) { this.preparePatientSearchSubControlChange(e.Patient); this.furtherTreatmentControl.Clear(); string ft = patComp.GetFinalReportByPatientId(currentPatient.Id); this.furtherTreatmentControl.Enabled = true; this.furtherTreatmentControl.Location = getPatientSearchSubMaskLocation(); this.furtherTreatmentControl.CurrentPatient = currentPatient; this.furtherTreatmentControl.Init(ft, this.patComp); this.Controls.Add(this.furtherTreatmentControl); this.furtherTreatmentControl.TextBoxFinalReport.Focus(); this.furtherTreatmentControl.TextBoxFinalReport.Select(50000, 0); } void patientSearchControl_AddStoneReport(object sender, AddStoneReportEventArgs e) { this.preparePatientSearchSubControlChange(e.Patient); this.stoneReportControl.Clear(); string sr = patComp.GetStoneReportByPatientId(currentPatient.Id); this.stoneReportControl.Enabled = true; this.stoneReportControl.Location = getPatientSearchSubMaskLocation(); this.stoneReportControl.CurrentPatient = currentPatient; this.stoneReportControl.Init(sr, this.patComp); this.Controls.Add(this.stoneReportControl); this.stoneReportControl.TextBoxStoneReport.Focus(); this.stoneReportControl.TextBoxStoneReport.Select(50000, 0); } void patientSearchControl_AddImages(object sender, ImagesEventArgs e) { this.preparePatientSearchSubControlChange(e.Patient); this.imagesControl.Clear(); this.imagesControl.Enabled = true; this.imagesControl.Location = getPatientSearchSubMaskLocation(); this.imagesControl.CurrentPatient = currentPatient; IList<ImageData> imageList = patComp.GetImagesByPatientID(currentPatient.Id); this.imagesControl.Initt(imageList); this.Controls.Add(this.imagesControl); this.imagesControl.ListViewImages.Focus(); } void patientSearchControl_NextAction(object sender, NextActionEventArgs e) { this.preparePatientSearchSubControlChange(e.Patient); this.nextActionControl.Location = getPatientSearchSubMaskLocation(); this.Controls.Add(this.nextActionControl); this.nextActionControl.init(e.Patient); } /////////// patientSearchContro Events END /////////// menu Events BEGIN private void newPatientToolStripMenuItem_Click(object sender, EventArgs e) { this.Clear(null); this.currentPatient = null; this.newPatientControl.Enabled = true; this.newPatientControl.Location = getTopMaskLocation(); this.newPatientControl.Init(null); this.newPatientControl.ButtonPrintIdCard.Enabled = false; this.Controls.Add(this.newPatientControl); this.newPatientControl.TextBoxSurname.Focus(); } private void overviewToolStripMenuItem_Click(object sender, EventArgs e) { this.Clear(null); this.currentPatient = null; this.overviewControl.Enabled = true; this.overviewControl.Location = getTopMaskLocation(); this.overviewControl.Init(); this.Controls.Add(this.overviewControl); } private void findPatientToolStripMenuItem_Click(object sender, EventArgs e) { this.Clear(null); putPatientSearchControl(null); } private void nextActionsToolStripMenuItem_Click(object sender, EventArgs e) { this.Clear(null); this.nextActionOverviewControl.Location = getTopMaskLocation(); this.Controls.Add(nextActionOverviewControl); this.nextActionOverviewControl.Init(this.patComp); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutBoxSPD about = new AboutBoxSPD(); about.TopMost = this.TopMost; about.ShowDialog(); } private void topMostToolStripMenuItem_Click(object sender, EventArgs e) { this.TopMost = !this.TopMost; } private void printToolStripMenuItem_Click(object sender, EventArgs e) { this.Clear(null); this.printMorePatientsControl.Enabled = true; this.printMorePatientsControl.Location = getTopMaskLocation(); this.Controls.Add(this.printMorePatientsControl); this.printMorePatientsControl.Init(this.patComp); } private void shortcutsToolStripMenuItem_Click(object sender, EventArgs e) { ShortcutsForm scf = new ShortcutsForm(); scf.TopMost = this.TopMost; scf.ShowDialog(); } private void sexToolStripMenuItem_Click(object sender, EventArgs e) { this.Clear(null); this.barDiagramm.Enabled = true; this.barDiagramm.Location = getTopMaskLocation(); this.barDiagramm.Width = this.Width; IList<BardiagramElement> barElements = new List<BardiagramElement>(); int malecount = 0; int femalecount = 0; foreach (PatientData patient in this.patComp.GetAllPatients()) { if (patient.Sex == Sex.male) { malecount++; } else { femalecount++; } } barElements.Add(new BardiagramElement("male", malecount)); barElements.Add(new BardiagramElement("female", femalecount)); this.barDiagramm.Init(barElements, "Sex of patients"); this.Controls.Add(this.barDiagramm); } private void yearOfBirthToolStripMenuItem_Click(object sender, EventArgs e) { this.Clear(null); this.barDiagramm.Enabled = true; this.barDiagramm.Location = getTopMaskLocation(); this.barDiagramm.Width = this.Width; IList<BardiagramElement> barElements = new List<BardiagramElement>(); IDictionary<string, int> map = new Dictionary<string, int>(); foreach (PatientData patient in this.patComp.GetAllPatients()) { if (!map.ContainsKey(patient.DateOfBirth.Year.ToString())) { map.Add(patient.DateOfBirth.Year.ToString(), 1); } else { map[patient.DateOfBirth.Year.ToString()]++; } } foreach (KeyValuePair<string, int> kvp in map) { barElements.Add(new BardiagramElement(kvp.Key, kvp.Value)); } barElements = BarDiagram.BarDiagrammElementsByValue(barElements); this.barDiagramm.Init(barElements, "Year of Birth of Patients"); this.Controls.Add(this.barDiagramm); } private void weightToolStripMenuItem_Click(object sender, EventArgs e) { this.Clear(null); this.barDiagramm.Enabled = true; this.barDiagramm.Location = getTopMaskLocation(); this.barDiagramm.Width = this.Width; IList<BardiagramElement> barElements = new List<BardiagramElement>(); IDictionary<string, int> map = new Dictionary<string, int>(); foreach (PatientData patient in this.patComp.GetAllPatients()) { if (!map.ContainsKey(patient.Weight.ToString("00") + "kg")) { map.Add(patient.Weight.ToString("00") + "kg", 1); } else { map[patient.Weight.ToString("00") + "kg"]++; } } foreach (KeyValuePair<string, int> kvp in map) { barElements.Add(new BardiagramElement(kvp.Key, kvp.Value)); } barElements = BarDiagram.BarDiagrammElementsByValue(barElements); IEnumerator<BardiagramElement> iter = barElements.GetEnumerator(); while (iter.MoveNext()) { BardiagramElement bde = iter.Current; bde.Name = iter.Current.Name + "kg"; } this.barDiagramm.Init(barElements, "Weight of Patients"); this.Controls.Add(this.barDiagramm); } private void dateOfMissionToolStripMenuItem_Click(object sender, EventArgs e) { this.Clear(null); this.barDiagramm.Enabled = true; this.barDiagramm.Location = getTopMaskLocation(); this.barDiagramm.Width = this.Width; IList<BardiagramElement> barElements = new List<BardiagramElement>(); IList<VisitData> visits = patComp.getallVisits(); foreach (VisitData visit in visits) { BardiagramElement elementx = null; foreach (BardiagramElement element in barElements) { if ((Int64.Parse(element.Name) > (visit.VisitDate.Ticks - (12096000000000 * 2))) && (Int64.Parse(element.Name) < (visit.VisitDate.Ticks + (12096000000000 * 2)))) { elementx = element; } } if (elementx == null) { barElements.Add(new BardiagramElement(visit.VisitDate.Ticks.ToString(), 1)); } else { elementx.Value++; } } barElements = BarDiagram.BarDiagrammElementsByValue(barElements); foreach (BardiagramElement element in barElements) { DateTime date = new DateTime(Int64.Parse(element.Name)); element.Name = new System.Globalization.DateTimeFormatInfo().GetMonthName(date.Month).Substring(0, 3) + ". " + date.Year.ToString(); } this.barDiagramm.Init(barElements, "Date of Visits per Mission"); this.Controls.Add(this.barDiagramm); } private void dateOfMissionToolStripMenuItem1_Click(object sender, EventArgs e) { this.Clear(null); this.barDiagramm.Enabled = true; this.barDiagramm.Location = getTopMaskLocation(); this.barDiagramm.Width = this.Width; IList<BardiagramElement> barElements = new List<BardiagramElement>(); IList<OperationData> operations = patComp.getallOperations(); foreach (OperationData operation in operations) { BardiagramElement elementx = null; foreach (BardiagramElement element in barElements) { if ((Int64.Parse(element.Name) > (operation.Date.Ticks - (12096000000000 * 2))) && (Int64.Parse(element.Name) < (operation.Date.Ticks + (12096000000000 * 2)))) { //12096000000000 are 2 Weeks in DateTime Ticks the *2 means the doubeling to 4 weeks elementx = element; } } if (elementx == null) { barElements.Add(new BardiagramElement(operation.Date.Ticks.ToString(), 1)); } else { elementx.Value++; } } barElements = BarDiagram.BarDiagrammElementsByValue(barElements); foreach (BardiagramElement element in barElements) { DateTime date = new DateTime(Int64.Parse(element.Name)); element.Name = new System.Globalization.DateTimeFormatInfo().GetMonthName(date.Month).Substring(0, 3) + ". " + date.Year.ToString(); } this.barDiagramm.Init(barElements, "Date of Visits per Mission"); this.Controls.Add(this.barDiagramm); } private void backupToolStripMenuItem_Click(object sender, EventArgs e) { backupForm.Init(this.patComp); backupForm.TopMost = this.TopMost; backupForm.ShowDialog(); } /////////// menu Events END /////////// Helper Methods BEGIN private Point getPatientSearchSubMaskLocation() { return new System.Drawing.Point(2, 260); } private Point getTopMaskLocation() { return new System.Drawing.Point(2, 28); } private void preparePatientSearchSubControlChange(PatientData patient) { this.Clear(patientSearchControl); this.activatePatientSearchControl(patient); this.currentPatient = patient; } private void Clear(Control exceptControl) { IList<Control> controlsToRemove = new List<Control>(); foreach (Control control in this.Controls) { bool isMenuStrip = control is MenuStrip; bool isStatusStrip = control is StatusStrip; bool isExceptControl = (exceptControl != null && exceptControl.GetType().Equals(control.GetType())); if (!isMenuStrip && !isStatusStrip && !isExceptControl) { controlsToRemove.Add(control); } } foreach (Control controlRemove in controlsToRemove) { this.Controls.Remove(controlRemove); } } private void ClearData() { this.currentPatient = null; } /////////// Helper Methods END private void patientStore(object sender, NewPatientStoreEventArgs e) { if (e.Patient.Id == 0) { //new Patient this.currentPatient = patComp.InsertPatient(e.Patient); Clear(null); this.newVisit.Location = getTopMaskLocation(); this.newVisit.CurrentPatient = this.currentPatient; this.newVisit.Init(null); this.Controls.Add(this.newVisit); this.newVisit.TextBoxCauseOfVisit.Focus(); } else { //update Patient currentPatient = e.Patient; patComp.UpdatePatient(e.Patient); this.newPatientControl.Enabled = false; } IList<DiagnoseGroupData> oldAssignedDiagnoseGroups = patComp.FindDiagnoseGroupIdByPatientId(currentPatient.Id); foreach(DiagnoseGroupData dgd in oldAssignedDiagnoseGroups) { if (!e.DiagnoseGroups.Contains(dgd)) { patComp.RemovePatientFromDiagnoseGroup(currentPatient.Id, dgd.DiagnoseGroupDataID); } } foreach (DiagnoseGroupData dgd in e.DiagnoseGroups) { if (!oldAssignedDiagnoseGroups.Contains(dgd)) { patComp.AssignPatientToDiagnoseGroup(currentPatient.Id, dgd.DiagnoseGroupDataID); } } } private void visitStore(object sender, NewVisitStoreEventArgs e) { VisitData vdata = e.Visit; if (vdata.Id == 0) { // new Visit vdata.PatientId = currentPatient.Id; patComp.InsertVisit(e.Visit); } else { // change Visit patComp.UpdateVisit(e.Visit); } this.Controls.Remove(newVisit); putPatientSearchControl(currentPatient); switch (e.NextScreen) { case NextScreen.NextAction: //this.preparePatientSearchSubControlChange(); this.nextActionControl.Location = getPatientSearchSubMaskLocation(); this.Controls.Add(this.nextActionControl); this.nextActionControl.init(currentPatient); break; case NextScreen.NextActionAndPlanOP: this.nextActionControl.Location = getPatientSearchSubMaskLocation(); this.Controls.Add(this.nextActionControl); this.nextActionControl.init(currentPatient); doPlanOperation(currentPatient); break; case NextScreen.ChagePatient: this.newPatientControl.Enabled = true; this.newPatientControl.Location = getPatientSearchSubMaskLocation(); this.newPatientControl.Init(currentPatient); this.Controls.Add(this.newPatientControl); this.newPatientControl.TextBoxSurname.Focus(); this.newPatientControl.TextBoxSurname.Select(0, 0); break; case NextScreen.Undefined: this.patientSearchControl.ListViewPatients.Focus(); break; case NextScreen.AddWaitingList: PatientData patient = this.patComp.FindPatientById(e.Visit.PatientId); patient.WaitListStartDate = DateTime.Now; this.patComp.UpdatePatient(patient); this.patientSearchControl.ListViewPatients.Focus(); break; default: break; } } private void databaseSettingsToolStripMenuItem_Click(object sender, EventArgs e) { DatabaseSettingsForm dbSettings = new DatabaseSettingsForm(this.patComp); dbSettings.TopMost = this.TopMost; dbSettings.ShowDialog(); } private void toolStripMenuItemGeneralSettings_Click(object sender, EventArgs e) { SettingsForm settingsForm = new SettingsForm(); settingsForm.TopMost = this.TopMost; settingsForm.ShowDialog(); } private void diagnoseGroupSettingsToolStripMenuItem_Click(object sender, EventArgs e) { DiagnoseGroupSettingsForm digGrouForm = new DiagnoseGroupSettingsForm(this.patComp); digGrouForm.TopMost = true; digGrouForm.ShowDialog(); } private void importToolStripMenuItem_Click(object sender, EventArgs e) { this.Clear(null); this.currentPatient = null; this.importControl.Enabled = true; this.importControl.Location = getTopMaskLocation(); this.importControl.Init(); this.Controls.Add(this.importControl); //this.importControl.TextBoxSurname.Focus(); } private void clearCachesToolStripMenuItem_Click(object sender, EventArgs e) { this.patComp.ClearCaches(); } #endregion } }
/* * nMQTT, a .Net MQTT v3 client implementation. * http://wiki.github.com/markallanson/nmqtt * * Copyright (c) 2009 Mark Allanson (mark@markallanson.net) & Contributors * * Licensed under the MIT License. You may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.opensource.org/licenses/mit-license.php */ namespace nMqtt.SampleApp.Views { partial class SubscriptionView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 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.subscriptionsGroupBox = new System.Windows.Forms.GroupBox(); this.button4 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.unsubscribeButton = new System.Windows.Forms.Button(); this.subscribeButton = new System.Windows.Forms.Button(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.receivedTopicTextbox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.qosNumeric = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.topicsComboBox = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.messageHistory = new System.Windows.Forms.TextBox(); this.subscriptionsGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.qosNumeric)).BeginInit(); this.SuspendLayout(); // // subscriptionsGroupBox // this.subscriptionsGroupBox.Controls.Add(this.messageHistory); this.subscriptionsGroupBox.Controls.Add(this.button4); this.subscriptionsGroupBox.Controls.Add(this.button3); this.subscriptionsGroupBox.Controls.Add(this.unsubscribeButton); this.subscriptionsGroupBox.Controls.Add(this.subscribeButton); this.subscriptionsGroupBox.Controls.Add(this.checkBox1); this.subscriptionsGroupBox.Controls.Add(this.textBox2); this.subscriptionsGroupBox.Controls.Add(this.label4); this.subscriptionsGroupBox.Controls.Add(this.receivedTopicTextbox); this.subscriptionsGroupBox.Controls.Add(this.label3); this.subscriptionsGroupBox.Controls.Add(this.qosNumeric); this.subscriptionsGroupBox.Controls.Add(this.label2); this.subscriptionsGroupBox.Controls.Add(this.topicsComboBox); this.subscriptionsGroupBox.Controls.Add(this.label1); this.subscriptionsGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.subscriptionsGroupBox.Location = new System.Drawing.Point(0, 0); this.subscriptionsGroupBox.Name = "subscriptionsGroupBox"; this.subscriptionsGroupBox.Size = new System.Drawing.Size(478, 282); this.subscriptionsGroupBox.TabIndex = 0; this.subscriptionsGroupBox.TabStop = false; this.subscriptionsGroupBox.Text = "Subscriptions"; // // button4 // this.button4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button4.Location = new System.Drawing.Point(393, 158); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(75, 23); this.button4.TabIndex = 13; this.button4.Text = "Hex"; this.button4.UseVisualStyleBackColor = true; // // button3 // this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button3.Location = new System.Drawing.Point(393, 129); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(75, 23); this.button3.TabIndex = 12; this.button3.Text = "Save..."; this.button3.UseVisualStyleBackColor = true; // // unsubscribeButton // this.unsubscribeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.unsubscribeButton.Location = new System.Drawing.Point(393, 100); this.unsubscribeButton.Name = "unsubscribeButton"; this.unsubscribeButton.Size = new System.Drawing.Size(75, 23); this.unsubscribeButton.TabIndex = 11; this.unsubscribeButton.Text = "Unsubscribe"; this.unsubscribeButton.UseVisualStyleBackColor = true; // // subscribeButton // this.subscribeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.subscribeButton.Location = new System.Drawing.Point(393, 71); this.subscribeButton.Name = "subscribeButton"; this.subscribeButton.Size = new System.Drawing.Size(75, 23); this.subscribeButton.TabIndex = 10; this.subscribeButton.Text = "Subscribe"; this.subscribeButton.UseVisualStyleBackColor = true; // // checkBox1 // this.checkBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.checkBox1.AutoSize = true; this.checkBox1.Location = new System.Drawing.Point(396, 48); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(69, 17); this.checkBox1.TabIndex = 8; this.checkBox1.Text = "Retained"; this.checkBox1.UseVisualStyleBackColor = true; // // textBox2 // this.textBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.textBox2.Location = new System.Drawing.Point(365, 45); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(22, 20); this.textBox2.TabIndex = 7; // // label4 // this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(330, 48); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(29, 13); this.label4.TabIndex = 6; this.label4.Text = "Qos:"; // // textBox1 // this.receivedTopicTextbox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.receivedTopicTextbox.Location = new System.Drawing.Point(100, 45); this.receivedTopicTextbox.Name = "receivedTopicTextbox"; this.receivedTopicTextbox.Size = new System.Drawing.Size(224, 20); this.receivedTopicTextbox.TabIndex = 5; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(7, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(86, 13); this.label3.TabIndex = 4; this.label3.Text = "Received Topic:"; // // qosNumeric // this.qosNumeric.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.qosNumeric.Location = new System.Drawing.Point(437, 18); this.qosNumeric.Name = "qosNumeric"; this.qosNumeric.Size = new System.Drawing.Size(31, 20); this.qosNumeric.TabIndex = 3; // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(393, 20); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(42, 13); this.label2.TabIndex = 2; this.label2.Text = "At Qos:"; // // topicsComboBox // this.topicsComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.topicsComboBox.FormattingEnabled = true; this.topicsComboBox.Location = new System.Drawing.Point(100, 17); this.topicsComboBox.Name = "topicsComboBox"; this.topicsComboBox.Size = new System.Drawing.Size(287, 21); this.topicsComboBox.TabIndex = 1; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(7, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(87, 13); this.label1.TabIndex = 0; this.label1.Text = "Subscribe Topic:"; // // textBox3 // this.messageHistory.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.messageHistory.Location = new System.Drawing.Point(10, 71); this.messageHistory.Multiline = true; this.messageHistory.Name = "textBox3"; this.messageHistory.Size = new System.Drawing.Size(377, 205); this.messageHistory.TabIndex = 14; // // SubscriptionView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.subscriptionsGroupBox); this.Name = "SubscriptionView"; this.Size = new System.Drawing.Size(478, 282); this.subscriptionsGroupBox.ResumeLayout(false); this.subscriptionsGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.qosNumeric)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox subscriptionsGroupBox; private System.Windows.Forms.NumericUpDown qosNumeric; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox topicsComboBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.CheckBox checkBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox receivedTopicTextbox; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button4; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button unsubscribeButton; private System.Windows.Forms.Button subscribeButton; private System.Windows.Forms.TextBox messageHistory; } }
#pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d { public class UTools : global::haxe.lang.HxObject { public UTools(global::haxe.lang.EmptyObject empty) { unchecked { #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" { } } #line default } public UTools() { unchecked { #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" global::pony.unity3d.UTools.__hx_ctor_pony_unity3d_UTools(this); } #line default } public static void __hx_ctor_pony_unity3d_UTools(global::pony.unity3d.UTools __temp_me127) { unchecked { #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" { } } #line default } public static bool init(string key, string camera, global::haxe.lang.Null<int> defWidth, global::haxe.lang.Null<int> defHeight, global::haxe.lang.Null<bool> fs) { unchecked { #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" bool __temp_fs126 = ( (global::haxe.lang.Runtime.eq((fs).toDynamic(), (default(global::haxe.lang.Null<bool>)).toDynamic())) ? (((bool) (true) )) : (fs.@value) ); #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" int __temp_defHeight125 = ( (global::haxe.lang.Runtime.eq((defHeight).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (600) )) : (defHeight.@value) ); #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" int __temp_defWidth124 = ( (global::haxe.lang.Runtime.eq((defWidth).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (800) )) : (defWidth.@value) ); #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" if (string.Equals(camera, default(string))) { #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" camera = "/Camera"; } #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" if (string.Equals(key, default(string))) { #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" key = ""; } object args = global::pony.unity3d.UTools.getArgs(new global::Array<object>(new object[]{"quality", "width", "height"}), ( (string.Equals(key, "")) ? (new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{}), new global::Array<object>(new object[]{}), new global::Array<int>(new int[]{}), new global::Array<double>(new double[]{}))) : (new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{5691732}), new global::Array<object>(new object[]{key}), new global::Array<int>(new int[]{}), new global::Array<double>(new double[]{}))) )); if (( ! (((bool) (global::haxe.lang.Runtime.getField(args, "reg", 5691732, true)) )) )) { #line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" return false; } #line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" global::haxe.lang.Null<int> cfg_quality = global::Std.parseInt(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(args, "quality", 1145832639, true))); #line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" global::haxe.lang.Null<int> cfg_width = global::Std.parseInt(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(args, "width", 1247983110, true))); #line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" global::haxe.lang.Null<int> cfg_height = global::Std.parseInt(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(args, "height", 38537191, true))); global::UnityEngine.QualitySettings.SetQualityLevel(cfg_quality.@value); #line 52 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" if (( ( cfg_width.@value > 0 ) && ( cfg_height.@value > 0 ) )) { global::UnityEngine.Screen.SetResolution(cfg_width.@value, cfg_height.@value, ((bool) (__temp_fs126) )); } else { #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" global::UnityEngine.Screen.SetResolution(((int) (__temp_defWidth124) ), ((int) (__temp_defHeight125) ), ((bool) (false) )); } #line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" if (string.Equals(camera, default(string))) { #line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" return true; } global::UnityEngine.GameObject cam = global::UnityEngine.GameObject.Find(camera); if (( cam == default(global::UnityEngine.GameObject) )) { #line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" return true; } global::pony.unity3d.UTools.compEnabled(cam, "AntialiasingAsPostEffect", ( cfg_quality.@value >= 1 )); global::pony.unity3d.UTools.compEnabled(cam, "NoiseAndGrain", global::pony.unity3d.UTools.compEnabled(cam, "DepthOfFieldScatter", global::pony.unity3d.UTools.compEnabled(cam, "BloomAndLensFlares", global::pony.unity3d.UTools.compEnabled(cam, "NoiseAndGrain", global::pony.unity3d.UTools.compEnabled(cam, "DepthOfFieldScatter", global::pony.unity3d.UTools.compEnabled(cam, "SSAOEffect", global::haxe.lang.Runtime.eq((cfg_quality).toDynamic(), 2))))))); return true; } #line default } public static object getArgs(global::Array<object> vs, object ks) { unchecked { #line 67 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" object r = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{}), new global::Array<object>(new object[]{}), new global::Array<int>(new int[]{}), new global::Array<double>(new double[]{})); global::haxe.ds.StringMap<object> vls = new global::haxe.ds.StringMap<object>(); if (( ! (global::haxe.lang.Runtime.eq(ks, default(object))) )) { #line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" int _g = 0; #line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" global::Array<object> _g1 = global::Reflect.fields(ks); #line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" while (( _g < _g1.length )) { #line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" string f = global::haxe.lang.Runtime.toString(_g1[_g]); #line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" ++ _g; global::Reflect.setField(r, f, false); { #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" string key = global::haxe.lang.Runtime.concat("-", global::Std.@string(global::Reflect.field(ks, f))); #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" vls.@set(key, f); } } } #line 73 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" global::Array<object> pvs = new global::Array<object>(new object[]{}); if (( vs != default(global::Array<object>) )) { int _g2 = 0; #line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" while (( _g2 < vs.length )) { #line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" string v = global::haxe.lang.Runtime.toString(vs[_g2]); #line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" ++ _g2; global::Reflect.setField(r, v, default(object)); pvs.push(global::haxe.lang.Runtime.concat("-", v)); } } #line 80 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" string[] a = global::System.Environment.GetCommandLineArgs(); bool skip = true; { #line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" int _g11 = 0; #line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" int _g3 = ( a as global::System.Array ).Length; #line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" while (( _g11 < _g3 )) { #line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" int i = _g11++; #line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" if (skip) { #line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" skip = false; } else { if (( global::Lambda.indexOf<object>(pvs, a[i]) != -1 )) { global::Reflect.setField(r, global::haxe.lang.StringExt.substr(a[i], 1, default(global::haxe.lang.Null<int>)), a[( i + 1 )]); skip = true; } else { if (vls.exists(a[i])) { global::Reflect.setField(r, global::haxe.lang.Runtime.toString(vls.@get(a[i]).@value), true); } } } } } #line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" return r; } #line default } public static bool compEnabled(global::UnityEngine.GameObject g, string name, bool enabled) { unchecked { #line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" global::UnityEngine.Behaviour c = default(global::UnityEngine.Behaviour); #line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" c = ((global::UnityEngine.Behaviour) (g.GetComponent(global::haxe.lang.Runtime.toString(name))) ); if (( c != default(global::UnityEngine.Behaviour) )) { #line 95 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" c.enabled = enabled; } return enabled; } #line default } public static new object __hx_createEmpty() { unchecked { #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" return new global::pony.unity3d.UTools(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 40 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/UTools.hx" return new global::pony.unity3d.UTools(); } #line default } } }
// 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.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; [StructLayout(LayoutKind.Sequential, Pack = 8, Size = 8)] struct MyVector64<T> where T : struct { } [StructLayout(LayoutKind.Sequential, Pack = 16, Size = 16)] struct MyVector128<T> where T : struct { } [StructLayout(LayoutKind.Sequential, Pack = 32, Size = 32)] struct MyVector256<T> where T : struct { } interface ITestStructure { int Size { get; } int OffsetOfByte { get; } int OffsetOfValue { get; } } struct DefaultLayoutDefaultPacking<T> : ITestStructure { public byte _byte; public T _value; public int Size => Unsafe.SizeOf<DefaultLayoutDefaultPacking<T>>(); public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte); public int OffsetOfValue => Program.OffsetOf(ref this, ref _value); } [StructLayout(LayoutKind.Sequential)] struct SequentialLayoutDefaultPacking<T> : ITestStructure { public byte _byte; public T _value; public int Size => Unsafe.SizeOf<SequentialLayoutDefaultPacking<T>>(); public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte); public int OffsetOfValue => Program.OffsetOf(ref this, ref _value); } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct SequentialLayoutMinPacking<T> : ITestStructure { public byte _byte; public T _value; public int Size => Unsafe.SizeOf<SequentialLayoutMinPacking<T>>(); public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte); public int OffsetOfValue => Program.OffsetOf(ref this, ref _value); } [StructLayout(LayoutKind.Sequential, Pack = 128)] struct SequentialLayoutMaxPacking<T> : ITestStructure { public byte _byte; public T _value; public int Size => Unsafe.SizeOf<SequentialLayoutMaxPacking<T>>(); public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte); public int OffsetOfValue => Program.OffsetOf(ref this, ref _value); } [StructLayout(LayoutKind.Auto)] struct AutoLayoutDefaultPacking<T> : ITestStructure { public byte _byte; public T _value; public int Size => Unsafe.SizeOf<AutoLayoutDefaultPacking<T>>(); public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte); public int OffsetOfValue => Program.OffsetOf(ref this, ref _value); } [StructLayout(LayoutKind.Auto, Pack = 1)] struct AutoLayoutMinPacking<T> : ITestStructure { public byte _byte; public T _value; public int Size => Unsafe.SizeOf<AutoLayoutMinPacking<T>>(); public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte); public int OffsetOfValue => Program.OffsetOf(ref this, ref _value); } [StructLayout(LayoutKind.Auto, Pack = 128)] struct AutoLayoutMaxPacking<T> : ITestStructure { public byte _byte; public T _value; public int Size => Unsafe.SizeOf<AutoLayoutMaxPacking<T>>(); public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte); public int OffsetOfValue => Program.OffsetOf(ref this, ref _value); } unsafe class Program { const int Pass = 100; const int Fail = 0; static int Main(string[] args) { bool succeeded = true; // Test fundamental data types succeeded &= TestBoolean(); succeeded &= TestByte(); succeeded &= TestChar(); succeeded &= TestDouble(); succeeded &= TestInt16(); succeeded &= TestInt32(); succeeded &= TestInt64(); succeeded &= TestIntPtr(); succeeded &= TestSByte(); succeeded &= TestSingle(); succeeded &= TestUInt16(); succeeded &= TestUInt32(); succeeded &= TestUInt64(); succeeded &= TestUIntPtr(); succeeded &= TestVector64(); succeeded &= TestVector128(); succeeded &= TestVector256(); // Test custom data types with explicit size/packing succeeded &= TestMyVector64(); succeeded &= TestMyVector128(); succeeded &= TestMyVector256(); return succeeded ? Pass : Fail; } static bool TestBoolean() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<bool>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutDefaultPacking<bool>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMinPacking<bool>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<bool>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<AutoLayoutDefaultPacking<bool>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<AutoLayoutMinPacking<bool>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<AutoLayoutMaxPacking<bool>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); return succeeded; } static bool TestByte() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<byte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutDefaultPacking<byte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMinPacking<byte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<byte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<AutoLayoutDefaultPacking<byte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<AutoLayoutMinPacking<byte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<AutoLayoutMaxPacking<byte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); return succeeded; } static bool TestChar() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<char>>( expectedSize: 4, expectedOffsetByte: 0, expectedOffsetValue: 2 ); succeeded &= Test<SequentialLayoutDefaultPacking<char>>( expectedSize: 4, expectedOffsetByte: 0, expectedOffsetValue: 2 ); succeeded &= Test<SequentialLayoutMinPacking<char>>( expectedSize: 3, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<char>>( expectedSize: 4, expectedOffsetByte: 0, expectedOffsetValue: 2 ); succeeded &= Test<AutoLayoutDefaultPacking<char>>( expectedSize: 4, expectedOffsetByte: 2, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<char>>( expectedSize: 4, expectedOffsetByte: 2, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<char>>( expectedSize: 4, expectedOffsetByte: 2, expectedOffsetValue: 0 ); return succeeded; } static bool TestDouble() { bool succeeded = true; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (RuntimeInformation.ProcessArchitecture != Architecture.X86)) { succeeded &= Test<DefaultLayoutDefaultPacking<double>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutDefaultPacking<double>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutMinPacking<double>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<double>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); if (RuntimeInformation.ProcessArchitecture != Architecture.X86) { succeeded &= Test<AutoLayoutDefaultPacking<double>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<double>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<double>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } else { succeeded &= Test<AutoLayoutDefaultPacking<double>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<double>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<double>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } } else { // The System V ABI for i386 defines this type as having 4-byte alignment succeeded &= Test<DefaultLayoutDefaultPacking<double>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutDefaultPacking<double>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutMinPacking<double>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<double>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutDefaultPacking<double>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<double>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<double>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } return succeeded; } static bool TestInt16() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<short>>( expectedSize: 4, expectedOffsetByte: 0, expectedOffsetValue: 2 ); succeeded &= Test<SequentialLayoutDefaultPacking<short>>( expectedSize: 4, expectedOffsetByte: 0, expectedOffsetValue: 2 ); succeeded &= Test<SequentialLayoutMinPacking<short>>( expectedSize: 3, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<short>>( expectedSize: 4, expectedOffsetByte: 0, expectedOffsetValue: 2 ); succeeded &= Test<AutoLayoutDefaultPacking<short>>( expectedSize: 4, expectedOffsetByte: 2, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<short>>( expectedSize: 4, expectedOffsetByte: 2, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<short>>( expectedSize: 4, expectedOffsetByte: 2, expectedOffsetValue: 0 ); return succeeded; } static bool TestInt32() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<int>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutDefaultPacking<int>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutMinPacking<int>>( expectedSize: 5, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<int>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutDefaultPacking<int>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<int>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<int>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); return succeeded; } static bool TestInt64() { bool succeeded = true; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (RuntimeInformation.ProcessArchitecture != Architecture.X86)) { succeeded &= Test<DefaultLayoutDefaultPacking<long>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutDefaultPacking<long>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutMinPacking<long>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<long>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); if (RuntimeInformation.ProcessArchitecture != Architecture.X86) { succeeded &= Test<AutoLayoutDefaultPacking<long>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<long>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<long>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } else { succeeded &= Test<AutoLayoutDefaultPacking<long>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<long>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<long>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } } else { // The System V ABI for i386 defines this type as having 4-byte alignment succeeded &= Test<DefaultLayoutDefaultPacking<long>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutDefaultPacking<long>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutMinPacking<long>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<long>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutDefaultPacking<long>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<long>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<long>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } return succeeded; } static bool TestIntPtr() { bool succeeded = true; if (Environment.Is64BitProcess) { succeeded &= Test<DefaultLayoutDefaultPacking<IntPtr>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutDefaultPacking<IntPtr>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutMinPacking<IntPtr>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<IntPtr>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutDefaultPacking<IntPtr>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<IntPtr>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<IntPtr>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } else { succeeded &= Test<DefaultLayoutDefaultPacking<IntPtr>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutDefaultPacking<IntPtr>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutMinPacking<IntPtr>>( expectedSize: 5, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<IntPtr>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutDefaultPacking<IntPtr>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<IntPtr>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<IntPtr>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); } return succeeded; } static bool TestSByte() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<sbyte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutDefaultPacking<sbyte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMinPacking<sbyte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<sbyte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<AutoLayoutDefaultPacking<sbyte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<AutoLayoutMinPacking<sbyte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<AutoLayoutMaxPacking<sbyte>>( expectedSize: 2, expectedOffsetByte: 0, expectedOffsetValue: 1 ); return succeeded; } static bool TestSingle() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<float>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutDefaultPacking<float>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutMinPacking<float>>( expectedSize: 5, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<float>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutDefaultPacking<float>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<float>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<float>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); return succeeded; } static bool TestUInt16() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<ushort>>( expectedSize: 4, expectedOffsetByte: 0, expectedOffsetValue: 2 ); succeeded &= Test<SequentialLayoutDefaultPacking<ushort>>( expectedSize: 4, expectedOffsetByte: 0, expectedOffsetValue: 2 ); succeeded &= Test<SequentialLayoutMinPacking<ushort>>( expectedSize: 3, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<ushort>>( expectedSize: 4, expectedOffsetByte: 0, expectedOffsetValue: 2 ); succeeded &= Test<AutoLayoutDefaultPacking<ushort>>( expectedSize: 4, expectedOffsetByte: 2, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<ushort>>( expectedSize: 4, expectedOffsetByte: 2, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<ushort>>( expectedSize: 4, expectedOffsetByte: 2, expectedOffsetValue: 0 ); return succeeded; } static bool TestUInt32() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<uint>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutDefaultPacking<uint>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutMinPacking<uint>>( expectedSize: 5, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<uint>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutDefaultPacking<uint>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<uint>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<uint>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); return succeeded; } static bool TestUInt64() { bool succeeded = true; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (RuntimeInformation.ProcessArchitecture != Architecture.X86)) { succeeded &= Test<DefaultLayoutDefaultPacking<ulong>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutDefaultPacking<ulong>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutMinPacking<ulong>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<ulong>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); if (RuntimeInformation.ProcessArchitecture != Architecture.X86) { succeeded &= Test<AutoLayoutDefaultPacking<ulong>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<ulong>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<ulong>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } else { succeeded &= Test<AutoLayoutDefaultPacking<ulong>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<ulong>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<ulong>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } } else { // The System V ABI for i386 defines this type as having 4-byte alignment succeeded &= Test<DefaultLayoutDefaultPacking<ulong>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutDefaultPacking<ulong>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutMinPacking<ulong>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<ulong>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutDefaultPacking<ulong>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<ulong>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<ulong>>( expectedSize: 12, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } return succeeded; } static bool TestUIntPtr() { bool succeeded = true; if (Environment.Is64BitProcess) { succeeded &= Test<DefaultLayoutDefaultPacking<UIntPtr>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutDefaultPacking<UIntPtr>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutMinPacking<UIntPtr>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<UIntPtr>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutDefaultPacking<UIntPtr>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<UIntPtr>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<UIntPtr>>( expectedSize: 16, expectedOffsetByte: 8, expectedOffsetValue: 0 ); } else { succeeded &= Test<DefaultLayoutDefaultPacking<UIntPtr>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutDefaultPacking<UIntPtr>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<SequentialLayoutMinPacking<UIntPtr>>( expectedSize: 5, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<UIntPtr>>( expectedSize: 8, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutDefaultPacking<UIntPtr>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMinPacking<UIntPtr>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); succeeded &= Test<AutoLayoutMaxPacking<UIntPtr>>( expectedSize: 8, expectedOffsetByte: 4, expectedOffsetValue: 0 ); } return succeeded; } static bool TestVector64() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<Vector64<byte>>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutDefaultPacking<Vector64<byte>>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutMinPacking<Vector64<byte>>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<Vector64<byte>>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); if (RuntimeInformation.ProcessArchitecture != Architecture.X86) { succeeded &= Test<AutoLayoutDefaultPacking<Vector64<byte>>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMinPacking<Vector64<byte>>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMaxPacking<Vector64<byte>>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); } else { succeeded &= Test<AutoLayoutDefaultPacking<Vector64<byte>>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMinPacking<Vector64<byte>>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMaxPacking<Vector64<byte>>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); } return succeeded; } static bool TestVector128() { bool succeeded = true; if (RuntimeInformation.ProcessArchitecture == Architecture.Arm) { // The Procedure Call Standard for ARM defines this type as having 8-byte alignment succeeded &= Test<DefaultLayoutDefaultPacking<Vector128<byte>>>( expectedSize: 24, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutDefaultPacking<Vector128<byte>>>( expectedSize: 24, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutMaxPacking<Vector128<byte>>>( expectedSize: 24, expectedOffsetByte: 0, expectedOffsetValue: 8 ); } else { succeeded &= Test<DefaultLayoutDefaultPacking<Vector128<byte>>>( expectedSize: 32, expectedOffsetByte: 0, expectedOffsetValue: 16 ); succeeded &= Test<SequentialLayoutDefaultPacking<Vector128<byte>>>( expectedSize: 32, expectedOffsetByte: 0, expectedOffsetValue: 16 ); succeeded &= Test<SequentialLayoutMaxPacking<Vector128<byte>>>( expectedSize: 32, expectedOffsetByte: 0, expectedOffsetValue: 16 ); } succeeded &= Test<SequentialLayoutMinPacking<Vector128<byte>>>( expectedSize: 17, expectedOffsetByte: 0, expectedOffsetValue: 1 ); if (RuntimeInformation.ProcessArchitecture != Architecture.X86) { succeeded &= Test<AutoLayoutDefaultPacking<Vector128<byte>>>( expectedSize: 24, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMinPacking<Vector128<byte>>>( expectedSize: 24, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMaxPacking<Vector128<byte>>>( expectedSize: 24, expectedOffsetByte: 0, expectedOffsetValue: 8 ); } else { succeeded &= Test<AutoLayoutDefaultPacking<Vector128<byte>>>( expectedSize: 20, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMinPacking<Vector128<byte>>>( expectedSize: 20, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMaxPacking<Vector128<byte>>>( expectedSize: 20, expectedOffsetByte: 0, expectedOffsetValue: 4 ); } return succeeded; } static bool TestVector256() { bool succeeded = true; if (RuntimeInformation.ProcessArchitecture == Architecture.Arm) { // The Procedure Call Standard for ARM defines this type as having 8-byte alignment succeeded &= Test<DefaultLayoutDefaultPacking<Vector256<byte>>>( expectedSize: 40, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutDefaultPacking<Vector256<byte>>>( expectedSize: 40, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<SequentialLayoutMaxPacking<Vector256<byte>>>( expectedSize: 40, expectedOffsetByte: 0, expectedOffsetValue: 8 ); } else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64) { // The Procedure Call Standard for ARM64 defines this type as having 16-byte alignment succeeded &= Test<DefaultLayoutDefaultPacking<Vector256<byte>>>( expectedSize: 48, expectedOffsetByte: 0, expectedOffsetValue: 16 ); succeeded &= Test<SequentialLayoutDefaultPacking<Vector256<byte>>>( expectedSize: 48, expectedOffsetByte: 0, expectedOffsetValue: 16 ); succeeded &= Test<SequentialLayoutMaxPacking<Vector256<byte>>>( expectedSize: 48, expectedOffsetByte: 0, expectedOffsetValue: 16 ); } else { succeeded &= Test<DefaultLayoutDefaultPacking<Vector256<byte>>>( expectedSize: 64, expectedOffsetByte: 0, expectedOffsetValue: 32 ); succeeded &= Test<SequentialLayoutDefaultPacking<Vector256<byte>>>( expectedSize: 64, expectedOffsetByte: 0, expectedOffsetValue: 32 ); succeeded &= Test<SequentialLayoutMaxPacking<Vector256<byte>>>( expectedSize: 64, expectedOffsetByte: 0, expectedOffsetValue: 32 ); } succeeded &= Test<SequentialLayoutMinPacking<Vector256<byte>>>( expectedSize: 33, expectedOffsetByte: 0, expectedOffsetValue: 1 ); if (RuntimeInformation.ProcessArchitecture != Architecture.X86) { succeeded &= Test<AutoLayoutDefaultPacking<Vector256<byte>>>( expectedSize: 40, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMinPacking<Vector256<byte>>>( expectedSize: 40, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMaxPacking<Vector256<byte>>>( expectedSize: 40, expectedOffsetByte: 0, expectedOffsetValue: 8 ); } else { succeeded &= Test<AutoLayoutDefaultPacking<Vector256<byte>>>( expectedSize: 36, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMinPacking<Vector256<byte>>>( expectedSize: 36, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMaxPacking<Vector256<byte>>>( expectedSize: 36, expectedOffsetByte: 0, expectedOffsetValue: 4 ); } return succeeded; } static bool TestMyVector64() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<MyVector64<byte>>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutDefaultPacking<MyVector64<byte>>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMinPacking<MyVector64<byte>>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<MyVector64<byte>>>( expectedSize: 9, expectedOffsetByte: 0, expectedOffsetValue: 1 ); if (Environment.Is64BitProcess) { succeeded &= Test<AutoLayoutDefaultPacking<MyVector64<byte>>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMinPacking<MyVector64<byte>>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMaxPacking<MyVector64<byte>>>( expectedSize: 16, expectedOffsetByte: 0, expectedOffsetValue: 8 ); } else { succeeded &= Test<AutoLayoutDefaultPacking<MyVector64<byte>>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMinPacking<MyVector64<byte>>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMaxPacking<MyVector64<byte>>>( expectedSize: 12, expectedOffsetByte: 0, expectedOffsetValue: 4 ); } return succeeded; } static bool TestMyVector128() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<MyVector128<byte>>>( expectedSize: 17, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutDefaultPacking<MyVector128<byte>>>( expectedSize: 17, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMinPacking<MyVector128<byte>>>( expectedSize: 17, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<MyVector128<byte>>>( expectedSize: 17, expectedOffsetByte: 0, expectedOffsetValue: 1 ); if (Environment.Is64BitProcess) { succeeded &= Test<AutoLayoutDefaultPacking<MyVector128<byte>>>( expectedSize: 24, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMinPacking<MyVector128<byte>>>( expectedSize: 24, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMaxPacking<MyVector128<byte>>>( expectedSize: 24, expectedOffsetByte: 0, expectedOffsetValue: 8 ); } else { succeeded &= Test<AutoLayoutDefaultPacking<MyVector128<byte>>>( expectedSize: 20, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMinPacking<MyVector128<byte>>>( expectedSize: 20, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMaxPacking<MyVector128<byte>>>( expectedSize: 20, expectedOffsetByte: 0, expectedOffsetValue: 4 ); } return succeeded; } static bool TestMyVector256() { bool succeeded = true; succeeded &= Test<DefaultLayoutDefaultPacking<MyVector256<byte>>>( expectedSize: 33, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutDefaultPacking<MyVector256<byte>>>( expectedSize: 33, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMinPacking<MyVector256<byte>>>( expectedSize: 33, expectedOffsetByte: 0, expectedOffsetValue: 1 ); succeeded &= Test<SequentialLayoutMaxPacking<MyVector256<byte>>>( expectedSize: 33, expectedOffsetByte: 0, expectedOffsetValue: 1 ); if (Environment.Is64BitProcess) { succeeded &= Test<AutoLayoutDefaultPacking<MyVector256<byte>>>( expectedSize: 40, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMinPacking<MyVector256<byte>>>( expectedSize: 40, expectedOffsetByte: 0, expectedOffsetValue: 8 ); succeeded &= Test<AutoLayoutMaxPacking<MyVector256<byte>>>( expectedSize: 40, expectedOffsetByte: 0, expectedOffsetValue: 8 ); } else { succeeded &= Test<AutoLayoutDefaultPacking<MyVector256<byte>>>( expectedSize: 36, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMinPacking<MyVector256<byte>>>( expectedSize: 36, expectedOffsetByte: 0, expectedOffsetValue: 4 ); succeeded &= Test<AutoLayoutMaxPacking<MyVector256<byte>>>( expectedSize: 36, expectedOffsetByte: 0, expectedOffsetValue: 4 ); } return succeeded; } static bool Test<T>(int expectedSize, int expectedOffsetByte, int expectedOffsetValue) where T : ITestStructure { bool succeeded = true; var testStructure = default(T); int size = testStructure.Size; if (size != expectedSize) { Console.WriteLine($"Unexpected Size for {testStructure.GetType()}."); Console.WriteLine($" Expected: {expectedSize}; Actual: {size}"); succeeded = false; } int offsetByte = testStructure.OffsetOfByte; if (offsetByte != expectedOffsetByte) { Console.WriteLine($"Unexpected Offset for {testStructure.GetType()}.Byte."); Console.WriteLine($" Expected: {expectedOffsetByte}; Actual: {offsetByte}"); succeeded = false; } int offsetValue = testStructure.OffsetOfValue; if (offsetValue != expectedOffsetValue) { Console.WriteLine($"Unexpected Offset for {testStructure.GetType()}.Value."); Console.WriteLine($" Expected: {expectedOffsetValue}; Actual: {offsetValue}"); succeeded = false; } if (!succeeded) { Console.WriteLine(); } return succeeded; } internal static int OffsetOf<T, U>(ref T origin, ref U target) { return Unsafe.ByteOffset(ref origin, ref Unsafe.As<U, T>(ref target)).ToInt32(); } }
/// <summary>************************************************************************** /// /// $Id: PalettizedColorSpaceMapper.java,v 1.2 2002/08/08 14:07:16 grosbois Exp $ /// /// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 /// $Date $ /// *************************************************************************** /// </summary> using System; using CSJ2K.j2k.image; using CSJ2K.j2k.util; using CSJ2K.Color.Boxes; namespace CSJ2K.Color { /// <summary> This class provides decoding of images with palettized colorspaces. /// Here each sample in the input is treated as an index into a color /// palette of triplet sRGB output values. /// /// </summary> /// <seealso cref="jj2000.j2k.colorspace.ColorSpace"> /// </seealso> /// <version> 1.0 /// </version> /// <author> Bruce A. Kern /// </author> public class PalettizedColorSpaceMapper:ColorSpaceMapper { /// <summary> Returns the number of components in the image. /// /// </summary> /// <returns> The number of components in the image. /// </returns> override public int NumComps { get { return pbox == null?src.NumComps:pbox.NumColumns; } } internal int[] outShiftValueArray; internal int srcChannel = 0; /// <summary>Access to the palette box information. </summary> private PaletteBox pbox; /// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> PalettizedColorSpaceMapper instance /// </returns> public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) { return new PalettizedColorSpaceMapper(src, csMap); } /// <summary> Ctor which creates an ICCProfile for the image and initializes /// all data objects (input, working, and output). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// </param> protected internal PalettizedColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap):base(src, csMap) { pbox = csMap.PaletteBox; initialize(); } /// <summary>General utility used by ctors </summary> private void initialize() { if (ncomps != 1 && ncomps != 3) throw new ColorSpaceException("wrong number of components (" + ncomps + ") for palettized image"); int outComps = NumComps; outShiftValueArray = new int[outComps]; for (int i = 0; i < outComps; i++) { outShiftValueArray[i] = 1 << (getNomRangeBits(i) - 1); } } /// <summary> Returns, in the blk argument, a block of image data containing the /// specifed rectangular area, in the specified component. The data is /// returned, as a copy of the internal data, therefore the returned data /// can be modified "in place". /// /// <P>The rectangular area to return is specified by the 'ulx', 'uly', 'w' /// and 'h' members of the 'blk' argument, relative to the current /// tile. These members are not modified by this method. The 'offset' of /// the returned data is 0, and the 'scanw' is the same as the block's /// width. See the 'DataBlk' class. /// /// <P>If the data array in 'blk' is 'null', then a new one is created. If /// the data array is not 'null' then it is reused, and it must be large /// enough to contain the block's data. Otherwise an 'ArrayStoreException' /// or an 'IndexOutOfBoundsException' is thrown by the Java system. /// /// <P>The returned data has its 'progressive' attribute set to that of the /// input data. /// /// </summary> /// <param name="blk">Its coordinates and dimensions specify the area to /// return. If it contains a non-null data array, then it must have the /// correct dimensions. If it contains a null data array a new one is /// created. The fields in this object are modified to return the data. /// /// </param> /// <param name="c">The index of the component from which to get the data. Only 0 /// and 3 are valid. /// /// </param> /// <returns> The requested DataBlk /// /// </returns> /// <seealso cref="getInternCompData"> /// /// </seealso> public override DataBlk getCompData(DataBlk out_Renamed, int c) { if (pbox == null) return src.getCompData(out_Renamed, c); if (ncomps != 1) { System.String msg = "PalettizedColorSpaceMapper: color palette " + "_not_ applied, incorrect number (" + System.Convert.ToString(ncomps) + ") of components"; FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, msg); return src.getCompData(out_Renamed, c); } // Initialize general input and output indexes int leftedgeOut = - 1; // offset to the start of the output scanline int rightedgeOut = - 1; // offset to the end of the output // scanline + 1 int leftedgeIn = - 1; // offset to the start of the input scanline int rightedgeIn = - 1; // offset to the end of the input // scanline + 1 int kOut = - 1; int kIn = - 1; // Assure a properly sized data buffer for output. InternalBuffer = out_Renamed; switch (out_Renamed.DataType) { // Int and Float data only case DataBlk.TYPE_INT: copyGeometry(inInt[0], out_Renamed); // Request data from the source. inInt[0] = (DataBlkInt) src.getInternCompData(inInt[0], 0); dataInt[0] = (int[]) inInt[0].Data; int[] outdataInt = ((DataBlkInt) out_Renamed).DataInt; // The nitty-gritty. for (int row = 0; row < out_Renamed.h; ++row) { leftedgeIn = inInt[0].offset + row * inInt[0].scanw; rightedgeIn = leftedgeIn + inInt[0].w; leftedgeOut = out_Renamed.offset + row * out_Renamed.scanw; rightedgeOut = leftedgeOut + out_Renamed.w; for (kOut = leftedgeOut, kIn = leftedgeIn; kIn < rightedgeIn; ++kIn, ++kOut) { outdataInt[kOut] = pbox.getEntry(c, dataInt[0][kIn] + shiftValueArray[0]) - outShiftValueArray[c]; } } out_Renamed.progressive = inInt[0].progressive; break; case DataBlk.TYPE_FLOAT: copyGeometry(inFloat[0], out_Renamed); // Request data from the source. inFloat[0] = (DataBlkFloat) src.getInternCompData(inFloat[0], 0); dataFloat[0] = (float[]) inFloat[0].Data; float[] outdataFloat = ((DataBlkFloat) out_Renamed).DataFloat; // The nitty-gritty. for (int row = 0; row < out_Renamed.h; ++row) { leftedgeIn = inFloat[0].offset + row * inFloat[0].scanw; rightedgeIn = leftedgeIn + inFloat[0].w; leftedgeOut = out_Renamed.offset + row * out_Renamed.scanw; rightedgeOut = leftedgeOut + out_Renamed.w; for (kOut = leftedgeOut, kIn = leftedgeIn; kIn < rightedgeIn; ++kIn, ++kOut) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" outdataFloat[kOut] = pbox.getEntry(c, (int) dataFloat[0][kIn] + shiftValueArray[0]) - outShiftValueArray[c]; } } out_Renamed.progressive = inFloat[0].progressive; break; case DataBlk.TYPE_SHORT: case DataBlk.TYPE_BYTE: default: // Unsupported output type. throw new System.ArgumentException("invalid source datablock" + " type"); } // Initialize the output block geometry and set the profiled // data into the output block. out_Renamed.offset = 0; out_Renamed.scanw = out_Renamed.w; return out_Renamed; } /// <summary>Return a suitable String representation of the class instance, e.g. /// <p> /// [PalettizedColorSpaceMapper /// ncomps= 3, scomp= 1, nentries= 1024 /// column=0, 7 bit signed entry /// column=1, 7 bit unsigned entry /// column=2, 7 bit signed entry] /// <p> /// /// </summary> public override System.String ToString() { int c; System.Text.StringBuilder rep = new System.Text.StringBuilder("[PalettizedColorSpaceMapper "); System.Text.StringBuilder body = new System.Text.StringBuilder(" " + eol); if (pbox != null) { body.Append("ncomps= ").Append(NumComps).Append(", scomp= ").Append(srcChannel); for (c = 0; c < NumComps; ++c) { body.Append(eol).Append("column= ").Append(c).Append(", ").Append(pbox.getBitDepth(c)).Append(" bit ").Append(pbox.isSigned(c)?"signed entry":"unsigned entry"); } } else { body.Append("image does not contain a palette box"); } rep.Append(ColorSpace.indent(" ", body)); return rep.Append("]").ToString(); } /// <summary> Returns, in the blk argument, a block of image data containing the /// specifed rectangular area, in the specified component. The data is /// returned, as a reference to the internal data, if any, instead of as a /// copy, therefore the returned data should not be modified. /// /// <P>The rectangular area to return is specified by the 'ulx', 'uly', 'w' /// and 'h' members of the 'blk' argument, relative to the current /// tile. These members are not modified by this method. The 'offset' and /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. /// /// <P>This method, in general, is more efficient than the 'getCompData()' /// method since it may not copy the data. However if the array of returned /// data is to be modified by the caller then the other method is probably /// preferable. /// /// <P>If possible, the data in the returned 'DataBlk' should be the /// internal data itself, instead of a copy, in order to increase the data /// transfer efficiency. However, this depends on the particular /// implementation (it may be more convenient to just return a copy of the /// data). This is the reason why the returned data should not be modified. /// /// <P>If the data array in <tt>blk</tt> is <tt>null</tt>, then a new one /// is created if necessary. The implementation of this interface may /// choose to return the same array or a new one, depending on what is more /// efficient. Therefore, the data array in <tt>blk</tt> prior to the /// method call should not be considered to contain the returned data, a /// new array may have been created. Instead, get the array from /// <tt>blk</tt> after the method has returned. /// /// <P>The returned data may have its 'progressive' attribute set. In this /// case the returned data is only an approximation of the "final" data. /// /// </summary> /// <param name="blk">Its coordinates and dimensions specify the area to return, /// relative to the current tile. Some fields in this object are modified /// to return the data. /// /// </param> /// <param name="c">The index of the component from which to get the data. /// /// </param> /// <returns> The requested DataBlk /// /// </returns> /// <seealso cref="getCompData"> /// </seealso> public override DataBlk getInternCompData(DataBlk out_Renamed, int c) { return getCompData(out_Renamed, c); } /// <summary> Returns the number of bits, referred to as the "range bits", /// corresponding to the nominal range of the image data in the specified /// component. If this number is <i>n</b> then for unsigned data the /// nominal range is between 0 and 2^b-1, and for signed data it is between /// -2^(b-1) and 2^(b-1)-1. In the case of transformed data which is not in /// the image domain (e.g., wavelet coefficients), this method returns the /// "range bits" of the image data that generated the coefficients. /// /// </summary> /// <param name="c">The index of the component. /// /// </param> /// <returns> The number of bits corresponding to the nominal range of the /// image data (in the image domain). /// </returns> public override int getNomRangeBits(int c) { return pbox == null?src.getNomRangeBits(c):pbox.getBitDepth(c); } /// <summary> Returns the component subsampling factor in the horizontal direction, /// for the specified component. This is, approximately, the ratio of /// dimensions between the reference grid and the component itself, see the /// 'ImgData' interface desription for details. /// /// </summary> /// <param name="c">The index of the component (between 0 and N-1) /// /// </param> /// <returns> The horizontal subsampling factor of component 'c' /// /// </returns> /// <seealso cref="jj2000.j2k.image.ImgData"> /// /// </seealso> public override int getCompSubsX(int c) { return imgdatasrc.getCompSubsX(srcChannel); } /// <summary> Returns the component subsampling factor in the vertical direction, for /// the specified component. This is, approximately, the ratio of /// dimensions between the reference grid and the component itself, see the /// 'ImgData' interface desription for details. /// /// </summary> /// <param name="c">The index of the component (between 0 and N-1) /// /// </param> /// <returns> The vertical subsampling factor of component 'c' /// /// </returns> /// <seealso cref="jj2000.j2k.image.ImgData"> /// /// </seealso> public override int getCompSubsY(int c) { return imgdatasrc.getCompSubsY(srcChannel); } /// <summary> Returns the width in pixels of the specified tile-component /// /// </summary> /// <param name="t">Tile index /// /// </param> /// <param name="c">The index of the component, from 0 to N-1. /// /// </param> /// <returns> The width in pixels of component <tt>c</tt> in tile<tt>t</tt>. /// /// </returns> public override int getTileCompWidth(int t, int c) { return imgdatasrc.getTileCompWidth(t, srcChannel); } /// <summary> Returns the height in pixels of the specified tile-component. /// /// </summary> /// <param name="t">The tile index. /// /// </param> /// <param name="c">The index of the component, from 0 to N-1. /// /// </param> /// <returns> The height in pixels of component <tt>c</tt> in tile /// <tt>t</tt>. /// /// </returns> public override int getTileCompHeight(int t, int c) { return imgdatasrc.getTileCompHeight(t, srcChannel); } /// <summary> Returns the width in pixels of the specified component in the overall /// image. /// /// </summary> /// <param name="c">The index of the component, from 0 to N-1. /// /// </param> /// <returns> The width in pixels of component <tt>c</tt> in the overall /// image. /// /// </returns> public override int getCompImgWidth(int c) { return imgdatasrc.getCompImgWidth(srcChannel); } /// <summary> Returns the number of bits, referred to as the "range bits", /// corresponding to the nominal range of the image data in the specified /// component. If this number is <i>n</b> then for unsigned data the /// nominal range is between 0 and 2^b-1, and for signed data it is between /// -2^(b-1) and 2^(b-1)-1. In the case of transformed data which is not in /// the image domain (e.g., wavelet coefficients), this method returns the /// "range bits" of the image data that generated the coefficients. /// /// </summary> /// <param name="c">The index of the component. /// /// </param> /// <returns> The number of bits corresponding to the nominal range of the /// image data (in the image domain). /// /// </returns> public override int getCompImgHeight(int c) { return imgdatasrc.getCompImgHeight(srcChannel); } /// <summary> Returns the horizontal coordinate of the upper-left corner of the /// specified component in the current tile. /// /// </summary> /// <param name="c">The index of the component. /// /// </param> public override int getCompULX(int c) { return imgdatasrc.getCompULX(srcChannel); } /// <summary> Returns the vertical coordinate of the upper-left corner of the /// specified component in the current tile. /// /// </summary> /// <param name="c">The index of the component. /// /// </param> public override int getCompULY(int c) { return imgdatasrc.getCompULY(srcChannel); } /* end class PalettizedColorSpaceMapper */ } }
using System; using System.Text; using PalmeralGenNHibernate.CEN.Default_; using NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Exceptions; using PalmeralGenNHibernate.EN.Default_; using PalmeralGenNHibernate.Exceptions; namespace PalmeralGenNHibernate.CAD.Default_ { public partial class ClienteCAD : BasicCAD, IClienteCAD { public ClienteCAD() : base () { } public ClienteCAD(ISession sessionAux) : base (sessionAux) { } public ClienteEN ReadOIDDefault (string nif) { ClienteEN clienteEN = null; try { SessionInitializeTransaction (); clienteEN = (ClienteEN)session.Get (typeof(ClienteEN), nif); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in ClienteCAD.", ex); } finally { SessionClose (); } return clienteEN; } public string Crear (ClienteEN cliente) { try { SessionInitializeTransaction (); session.Save (cliente); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in ClienteCAD.", ex); } finally { SessionClose (); } return cliente.Nif; } public void Editar (ClienteEN cliente) { try { SessionInitializeTransaction (); ClienteEN clienteEN = (ClienteEN)session.Load (typeof(ClienteEN), cliente.Nif); clienteEN.Nombre = cliente.Nombre; clienteEN.Descripcion = cliente.Descripcion; clienteEN.Email = cliente.Email; clienteEN.Localidad = cliente.Localidad; clienteEN.Provincia = cliente.Provincia; clienteEN.Pais = cliente.Pais; clienteEN.Direccion = cliente.Direccion; clienteEN.CodigoPostal = cliente.CodigoPostal; clienteEN.Telefono = cliente.Telefono; session.Update (clienteEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in ClienteCAD.", ex); } finally { SessionClose (); } } public void Eliminar (string nif) { try { SessionInitializeTransaction (); ClienteEN clienteEN = (ClienteEN)session.Load (typeof(ClienteEN), nif); session.Delete (clienteEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in ClienteCAD.", ex); } finally { SessionClose (); } } public System.Collections.Generic.IList<ClienteEN> ObtenerTodos (int first, int size) { System.Collections.Generic.IList<ClienteEN> result = null; try { SessionInitializeTransaction (); if (size > 0) result = session.CreateCriteria (typeof(ClienteEN)). SetFirstResult (first).SetMaxResults (size).List<ClienteEN>(); else result = session.CreateCriteria (typeof(ClienteEN)).List<ClienteEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in ClienteCAD.", ex); } finally { SessionClose (); } return result; } public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.ClienteEN> BuscarPorNombre (string p_nombre) { System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.ClienteEN> result; try { SessionInitializeTransaction (); //String sql = @"FROM ClienteEN self where FROM ClienteEN AS cli WHERE cli.Nombre LIKE CONCAT('%', :p_nombre , '%')"; //IQuery query = session.CreateQuery(sql); IQuery query = (IQuery)session.GetNamedQuery ("ClienteENbuscarPorNombreHQL"); query.SetParameter ("p_nombre", p_nombre); result = query.List<PalmeralGenNHibernate.EN.Default_.ClienteEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in ClienteCAD.", ex); } finally { SessionClose (); } return result; } public ClienteEN ObtenerCliente (string nif) { ClienteEN clienteEN = null; try { SessionInitializeTransaction (); clienteEN = (ClienteEN)session.Get (typeof(ClienteEN), nif); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in ClienteCAD.", ex); } finally { SessionClose (); } return clienteEN; } public void Unrelationer_instalaciones (string p_cliente, System.Collections.Generic.IList<string> p_instalacion) { try { SessionInitializeTransaction (); PalmeralGenNHibernate.EN.Default_.ClienteEN clienteEN = null; clienteEN = (ClienteEN)session.Load (typeof(ClienteEN), p_cliente); PalmeralGenNHibernate.EN.Default_.InstalacionEN instalacionesENAux = null; if (clienteEN.Instalaciones != null) { foreach (string item in p_instalacion) { instalacionesENAux = (PalmeralGenNHibernate.EN.Default_.InstalacionEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.InstalacionEN), item); if (clienteEN.Instalaciones.Contains (instalacionesENAux) == true) { clienteEN.Instalaciones.Remove (instalacionesENAux); instalacionesENAux.Cliente = null; } else throw new ModelException ("The identifier " + item + " in p_instalacion you are trying to unrelationer, doesn't exist in ClienteEN"); } } session.Update (clienteEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in ClienteCAD.", ex); } finally { SessionClose (); } } public void Relationer_instalaciones (string p_cliente, System.Collections.Generic.IList<string> p_instalacion) { PalmeralGenNHibernate.EN.Default_.ClienteEN clienteEN = null; try { SessionInitializeTransaction (); clienteEN = (ClienteEN)session.Load (typeof(ClienteEN), p_cliente); PalmeralGenNHibernate.EN.Default_.InstalacionEN instalacionesENAux = null; if (clienteEN.Instalaciones == null) { clienteEN.Instalaciones = new System.Collections.Generic.List<PalmeralGenNHibernate.EN.Default_.InstalacionEN>(); } foreach (string item in p_instalacion) { instalacionesENAux = new PalmeralGenNHibernate.EN.Default_.InstalacionEN (); instalacionesENAux = (PalmeralGenNHibernate.EN.Default_.InstalacionEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.InstalacionEN), item); instalacionesENAux.Cliente = clienteEN; clienteEN.Instalaciones.Add (instalacionesENAux); } session.Update (clienteEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in ClienteCAD.", ex); } finally { SessionClose (); } } } }
// ***************************************************************************** // // Copyright 2004, Weifen Luo // All rights reserved. The software and associated documentation // supplied hereunder are the proprietary information of Weifen Luo // and are supplied subject to licence terms. // // WinFormsUI Library Version 1.0 // ***************************************************************************** using System; using System.Drawing; using System.Windows.Forms; using System.Drawing.Drawing2D; using WeifenLuo.WinFormsUI; namespace DockSample { public class AutoHideStripFromBase : AutoHideStripBase { private const int _ImageHeight = 16; private const int _ImageWidth = 16; private const int _ImageGapTop = 2; private const int _ImageGapLeft = 4; private const int _ImageGapRight = 4; private const int _ImageGapBottom = 2; private const int _TextGapLeft = 4; private const int _TextGapRight = 10; private const int _TabGapTop = 3; private const int _TabGapLeft = 2; private const int _TabGapBetween = 10; private static StringFormat _stringFormatTabHorizontal; private static StringFormat _stringFormatTabVertical; private static Matrix _matrixIdentity; private static DockState[] _dockStates; #region Customizable Properties protected virtual StringFormat StringFormatTabHorizontal { get { return _stringFormatTabHorizontal; } } protected virtual StringFormat StringFormatTabVertical { get { return _stringFormatTabVertical; } } protected virtual int ImageHeight { get { return _ImageHeight; } } protected virtual int ImageWidth { get { return _ImageWidth; } } protected virtual int ImageGapTop { get { return _ImageGapTop; } } protected virtual int ImageGapLeft { get { return _ImageGapLeft; } } protected virtual int ImageGapRight { get { return _ImageGapRight; } } protected virtual int ImageGapBottom { get { return _ImageGapBottom; } } protected virtual int TextGapLeft { get { return _TextGapLeft; } } protected virtual int TextGapRight { get { return _TextGapRight; } } protected virtual int TabGapTop { get { return _TabGapTop; } } protected virtual int TabGapLeft { get { return _TabGapLeft; } } protected virtual int TabGapBetween { get { return _TabGapBetween; } } protected virtual void BeginDrawTab() { } protected virtual void EndDrawTab() { } protected virtual Brush BrushTabBackGround { get { return SystemBrushes.Control; } } protected virtual Pen PenTabBorder { get { return SystemPens.GrayText; } } protected virtual Brush BrushTabText { get { return SystemBrushes.FromSystemColor(SystemColors.ControlDarkDark); } } #endregion private Matrix MatrixIdentity { get { return _matrixIdentity; } } private DockState[] DockStates { get { return _dockStates; } } static AutoHideStripFromBase() { _stringFormatTabHorizontal = new StringFormat(); _stringFormatTabHorizontal.Alignment = StringAlignment.Near; _stringFormatTabHorizontal.LineAlignment = StringAlignment.Center; _stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap; _stringFormatTabVertical = new StringFormat(); _stringFormatTabVertical.Alignment = StringAlignment.Near; _stringFormatTabVertical.LineAlignment = StringAlignment.Center; _stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical; _matrixIdentity = new Matrix(); _dockStates = new DockState[4]; _dockStates[0] = DockState.DockLeftAutoHide; _dockStates[1] = DockState.DockRightAutoHide; _dockStates[2] = DockState.DockTopAutoHide; _dockStates[3] = DockState.DockBottomAutoHide; } protected internal AutoHideStripFromBase(DockPanel panel) : base(panel) { SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); BackColor = Color.WhiteSmoke; } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, SystemColors.ControlLight, Color.WhiteSmoke, LinearGradientMode.ForwardDiagonal)) { g.FillRectangle(brush, ClientRectangle); } DrawTabStrip(g); } protected override void OnLayout(LayoutEventArgs levent) { CalculateTabs(); base.OnLayout (levent); } private void DrawTabStrip(Graphics g) { DrawTabStrip(g, DockState.DockTopAutoHide); DrawTabStrip(g, DockState.DockBottomAutoHide); DrawTabStrip(g, DockState.DockLeftAutoHide); DrawTabStrip(g, DockState.DockRightAutoHide); } private void DrawTabStrip(Graphics g, DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return; Matrix matrixIdentity = g.Transform; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { Matrix matrixRotated = new Matrix(); matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); g.Transform = matrixRotated; } foreach (AutoHidePane pane in GetPanes(dockState)) { foreach (AutoHideTabFromBase tab in pane.Tabs) DrawTab(g, tab); } g.Transform = matrixIdentity; } private void CalculateTabs() { CalculateTabs(DockState.DockTopAutoHide); CalculateTabs(DockState.DockBottomAutoHide); CalculateTabs(DockState.DockLeftAutoHide); CalculateTabs(DockState.DockRightAutoHide); } private void CalculateTabs(DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight/ImageHeight); using (Graphics g = CreateGraphics()) { int x = TabGapLeft + rectTabStrip.X; foreach (AutoHidePane pane in GetPanes(dockState)) { int maxWidth = 0; foreach (AutoHideTabFromBase tab in pane.Tabs) { int width = imageWidth + ImageGapLeft + ImageGapRight + (int)g.MeasureString(tab.Content.TabText, Font).Width + 1 + TextGapLeft + TextGapRight; if (width > maxWidth) maxWidth = width; } foreach (AutoHideTabFromBase tab in pane.Tabs) { tab.TabX = x; if (tab.Content == pane.DockPane.ActiveContent) tab.TabWidth = maxWidth; else tab.TabWidth = imageWidth + ImageGapLeft + ImageGapRight; x += tab.TabWidth; } x += TabGapBetween; } } } private void DrawTab(Graphics g, AutoHideTabFromBase tab) { Rectangle rectTab = GetTabRectangle(tab); if (rectTab.IsEmpty) return; DockState dockState = tab.Content.DockState; DockContent content = tab.Content; BeginDrawTab(); Brush brushTabBackGround = BrushTabBackGround; Pen penTabBorder = PenTabBorder; Brush brushTabText = BrushTabText; g.FillRectangle(brushTabBackGround, rectTab); g.DrawLine(penTabBorder, rectTab.Left, rectTab.Top, rectTab.Left, rectTab.Bottom); g.DrawLine(penTabBorder, rectTab.Right, rectTab.Top, rectTab.Right, rectTab.Bottom); if (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide) g.DrawLine(penTabBorder, rectTab.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); else g.DrawLine(penTabBorder, rectTab.Left, rectTab.Top, rectTab.Right, rectTab.Top); // Set no rotate for drawing icon and text Matrix matrixRotate = g.Transform; g.Transform = MatrixIdentity; // Draw the icon Rectangle rectImage = rectTab; rectImage.X += ImageGapLeft; rectImage.Y += ImageGapTop; int imageHeight = rectTab.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight/ImageHeight); rectImage.Height = imageHeight; rectImage.Width = imageWidth; rectImage = GetTransformedRectangle(dockState, rectImage); g.DrawIcon(content.Icon, rectImage); // Draw the text if (content == content.Pane.ActiveContent) { Rectangle rectText = rectTab; rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText = GetTransformedRectangle(dockState, rectText); if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) g.DrawString(content.TabText, Font, brushTabText, rectText, StringFormatTabVertical); else g.DrawString(content.TabText, Font, brushTabText, rectText, StringFormatTabHorizontal); } // Set rotate back g.Transform = matrixRotate; EndDrawTab(); } private Rectangle GetLogicalTabStripRectangle(DockState dockState) { return GetLogicalTabStripRectangle(dockState, false); } private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed) { if (!DockHelper.IsDockStateAutoHide(dockState)) return Rectangle.Empty; int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count; int rightPanes = GetPanes(DockState.DockRightAutoHide).Count; int topPanes = GetPanes(DockState.DockTopAutoHide).Count; int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count; int x, y, width, height; height = MeasureHeight(); if (dockState == DockState.DockLeftAutoHide && leftPanes > 0) { x = 0; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height); } else if (dockState == DockState.DockRightAutoHide && rightPanes > 0) { x = Width - height; if (leftPanes != 0 && x < height) x = height; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height); } else if (dockState == DockState.DockTopAutoHide && topPanes > 0) { x = leftPanes == 0 ? 0 : height; y = 0; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0) { x = leftPanes == 0 ? 0 : height; y = Height - height; if (topPanes != 0 && y < height) y = height; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else return Rectangle.Empty; if (!transformed) return new Rectangle(x, y, width, height); else return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } private Rectangle GetTabRectangle(AutoHideTabFromBase tab) { return GetTabRectangle(tab, false); } private Rectangle GetTabRectangle(AutoHideTabFromBase tab, bool transformed) { DockState dockState = tab.Content.DockState; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return Rectangle.Empty; int x = tab.TabX; int y = rectTabStrip.Y + (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ? 0 : TabGapTop); int width = ((AutoHideTabFromBase)tab).TabWidth; int height = rectTabStrip.Height - TabGapTop; if (!transformed) return new Rectangle(x, y, width, height); else return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect) { if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide) return rect; PointF[] pts = new PointF[1]; // the center of the rectangle pts[0].X = (float)rect.X + (float)rect.Width / 2; pts[0].Y = (float)rect.Y + (float)rect.Height / 2; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); Matrix matrix = new Matrix(); matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); matrix.TransformPoints(pts); return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F), (int)(pts[0].Y - (float)rect.Width / 2 + .5F), rect.Height, rect.Width); } protected override DockContent GetHitTest(Point ptMouse) { foreach(DockState state in DockStates) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true); if (!rectTabStrip.Contains(ptMouse)) continue; foreach(AutoHidePane pane in GetPanes(state)) { foreach(AutoHideTabFromBase tab in pane.Tabs) { Rectangle rectTab = GetTabRectangle(tab, true); rectTab.Intersect(rectTabStrip); if (rectTab.Contains(ptMouse)) return tab.Content; } } } return null; } protected override int MeasureHeight() { return Math.Max(ImageGapBottom + ImageGapTop + ImageHeight, Font.Height) + TabGapTop; } protected override void OnRefreshChanges() { CalculateTabs(); Invalidate(); } } }
// *********************************************************************** // Copyright (c) 2012-2017 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; using NUnit.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Execution { using Commands; /// <summary> /// A WorkItem may be an individual test case, a fixture or /// a higher level grouping of tests. All WorkItems inherit /// from the abstract WorkItem class, which uses the template /// pattern to allow derived classes to perform work in /// whatever way is needed. /// /// A WorkItem is created with a particular TestExecutionContext /// and is responsible for re-establishing that context in the /// current thread before it begins or resumes execution. /// </summary> public abstract class WorkItem : IDisposable { static readonly Logger log = InternalTrace.GetLogger("WorkItem"); #region Construction and Initialization /// <summary> /// Construct a WorkItem for a particular test. /// </summary> /// <param name="test">The test that the WorkItem will run</param> /// <param name="filter">Filter used to include or exclude child items</param> public WorkItem(Test test, ITestFilter filter) { Test = test; Filter = filter; Result = test.MakeTestResult(); State = WorkItemState.Ready; ParallelScope = Test.Properties.ContainsKey(PropertyNames.ParallelScope) ? (ParallelScope)Test.Properties.Get(PropertyNames.ParallelScope) : ParallelScope.Default; #if APARTMENT_STATE TargetApartment = GetTargetApartment(Test); #endif State = WorkItemState.Ready; } /// <summary> /// Construct a work Item that wraps another work Item. /// Wrapper items are used to represent independently /// dispatched tasks, which form part of the execution /// of a single test, such as OneTimeTearDown. /// </summary> /// <param name="wrappedItem">The WorkItem being wrapped</param> public WorkItem(WorkItem wrappedItem) { // Use the same Test, Result, Actions, Context, ParallelScope // and TargetApartment as the item being wrapped. Test = wrappedItem.Test; Result = wrappedItem.Result; Context = wrappedItem.Context; ParallelScope = wrappedItem.ParallelScope; #if PARALLEL TestWorker = wrappedItem.TestWorker; #endif #if APARTMENT_STATE TargetApartment = wrappedItem.TargetApartment; #endif // State is independent of the wrapped item State = WorkItemState.Ready; } /// <summary> /// Initialize the TestExecutionContext. This must be done /// before executing the WorkItem. /// </summary> /// <remarks> /// Originally, the context was provided in the constructor /// but delaying initialization of the context until the item /// is about to be dispatched allows changes in the parent /// context during OneTimeSetUp to be reflected in the child. /// </remarks> /// <param name="context">The TestExecutionContext to use</param> public void InitializeContext(TestExecutionContext context) { Guard.OperationValid(Context == null, "The context has already been initialized"); Context = context; } #endregion #region Properties and Events /// <summary> /// Event triggered when the item is complete /// </summary> public event EventHandler Completed; /// <summary> /// Gets the current state of the WorkItem /// </summary> public WorkItemState State { get; private set; } /// <summary> /// The test being executed by the work item /// </summary> public Test Test { get; } /// <summary> /// The name of the work item - defaults to the Test name. /// </summary> public virtual string Name { get { return Test.Name; } } /// <summary> /// Filter used to include or exclude child tests /// </summary> public ITestFilter Filter { get; } /// <summary> /// The execution context /// </summary> public TestExecutionContext Context { get; private set; } #if PARALLEL /// <summary> /// The worker executing this item. /// </summary> public TestWorker TestWorker { get; internal set; } private ParallelExecutionStrategy? _executionStrategy; /// <summary> /// The ParallelExecutionStrategy to use for this work item /// </summary> public virtual ParallelExecutionStrategy ExecutionStrategy { get { if (!_executionStrategy.HasValue) _executionStrategy = GetExecutionStrategy(); return _executionStrategy.Value; } } /// <summary> /// Indicates whether this work item should use a separate dispatcher. /// </summary> public virtual bool IsolateChildTests { get; } = false; #endif /// <summary> /// The test result /// </summary> public TestResult Result { get; protected set; } /// <summary> /// Gets the ParallelScope associated with the test, if any, /// otherwise returning ParallelScope.Default; /// </summary> public ParallelScope ParallelScope { get; } #if APARTMENT_STATE internal ApartmentState TargetApartment { get; set; } private ApartmentState CurrentApartment { get; set; } #endif #endregion #region Public Methods /// <summary> /// Execute the current work item, including any /// child work items. /// </summary> public virtual void Execute() { #if PARALLEL // A supplementary thread is required in two conditions... // // 1. If the test used the RequiresThreadAttribute. This // is at the discretion of the user. // // 2. If the test needs to run in a different apartment. // This should not normally occur when using the parallel // dispatcher because tests are dispatches to a queue that // matches the requested apartment. Under the SimpleDispatcher // (--workers=0 option) it occurs routinely whenever a // different apartment is requested. #if APARTMENT_STATE CurrentApartment = Thread.CurrentThread.GetApartmentState(); var targetApartment = TargetApartment == ApartmentState.Unknown ? CurrentApartment : TargetApartment; if (Test.RequiresThread || targetApartment != CurrentApartment) #else if (Test.RequiresThread) #endif { // Handle error conditions in a single threaded fixture if (Context.IsSingleThreaded) { string msg = Test.RequiresThread ? "RequiresThreadAttribute may not be specified on a test within a single-SingleThreadedAttribute fixture." : "Tests in a single-threaded fixture may not specify a different apartment"; log.Error(msg); Result.SetResult(ResultState.NotRunnable, msg); WorkItemComplete(); return; } log.Debug("Running on separate thread because {0} is specified.", Test.RequiresThread ? "RequiresThread" : "different Apartment"); #if APARTMENT_STATE RunOnSeparateThread(targetApartment); #else RunOnSeparateThread(); #endif } else RunOnCurrentThread(); #else RunOnCurrentThread(); #endif } private readonly ManualResetEventSlim _completionEvent = new ManualResetEventSlim(); /// <summary> /// Wait until the execution of this item is complete /// </summary> public void WaitForCompletion() { _completionEvent.Wait(); } /// <summary> /// Marks the WorkItem as NotRunnable. /// </summary> /// <param name="reason">Reason for test being NotRunnable.</param> public void MarkNotRunnable(string reason) { Result.SetResult(ResultState.NotRunnable, reason); WorkItemComplete(); } #if THREAD_ABORT private readonly object threadLock = new object(); private int nativeThreadId; #endif /// <summary> /// Cancel (abort or stop) a WorkItem /// </summary> /// <param name="force">true if the WorkItem should be aborted, false if it should run to completion</param> public virtual void Cancel(bool force) { if (Context != null) Context.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; #if THREAD_ABORT if (force) { Thread tThread; int tNativeThreadId; lock (threadLock) { if (thread == null) return; tThread = thread; tNativeThreadId = nativeThreadId; thread = null; } if (!tThread.Join(0)) { log.Debug("Killing thread {0} for cancel", tThread.ManagedThreadId); ThreadUtility.Kill(tThread, tNativeThreadId); tThread.Join(); ChangeResult(ResultState.Cancelled, "Cancelled by user"); WorkItemComplete(); } } #endif } #endregion #region IDisposable Implementation /// <summary> /// Standard Dispose /// </summary> public void Dispose() { _completionEvent?.Dispose(); } #endregion #region Protected Methods /// <summary> /// Method that performs actually performs the work. It should /// set the State to WorkItemState.Complete when done. /// </summary> protected abstract void PerformWork(); /// <summary> /// Method called by the derived class when all work is complete /// </summary> protected void WorkItemComplete() { State = WorkItemState.Complete; Result.StartTime = Context.StartTime; Result.EndTime = DateTime.UtcNow; long tickCount = Stopwatch.GetTimestamp() - Context.StartTicks; double seconds = (double)tickCount / Stopwatch.Frequency; Result.Duration = seconds; // We add in the assert count from the context. If // this item is for a test case, we are adding the // test assert count to zero. If it's a fixture, we // are adding in any asserts that were run in the // fixture setup or teardown. Each context only // counts the asserts taking place in that context. // Each result accumulates the count from child // results along with its own asserts. Result.AssertCount += Context.AssertCount; Context.Listener.TestFinished(Result); Completed?.Invoke(this, EventArgs.Empty); _completionEvent.Set(); //Clear references to test objects to reduce memory usage Context.TestObject = null; Test.Fixture = null; } /// <summary> /// Builds the set up tear down list. /// </summary> /// <param name="setUpMethods">Unsorted array of setup MethodInfos.</param> /// <param name="tearDownMethods">Unsorted array of teardown MethodInfos.</param> /// <returns>A list of SetUpTearDownItems</returns> protected List<SetUpTearDownItem> BuildSetUpTearDownList(MethodInfo[] setUpMethods, MethodInfo[] tearDownMethods) { Guard.ArgumentNotNull(setUpMethods, nameof(setUpMethods)); Guard.ArgumentNotNull(tearDownMethods, nameof(tearDownMethods)); var list = new List<SetUpTearDownItem>(); Type fixtureType = Test.Type; if (fixtureType == null) return list; while (fixtureType != null && fixtureType != typeof(object)) { var node = BuildNode(fixtureType, setUpMethods, tearDownMethods); if (node.HasMethods) list.Add(node); fixtureType = fixtureType.GetTypeInfo().BaseType; } return list; } // This method builds a list of nodes that can be used to // run setup and teardown according to the NUnit specs. // We need to execute setup and teardown methods one level // at a time. However, we can't discover them by reflection // one level at a time, because that would cause overridden // methods to be called twice, once on the base class and // once on the derived class. // // For that reason, we start with a list of all setup and // teardown methods, found using a single reflection call, // and then descend through the inheritance hierarchy, // adding each method to the appropriate level as we go. private static SetUpTearDownItem BuildNode(Type fixtureType, IList<MethodInfo> setUpMethods, IList<MethodInfo> tearDownMethods) { // Create lists of methods for this level only. // Note that FindAll can't be used because it's not // available on all the platforms we support. var mySetUpMethods = SelectMethodsByDeclaringType(fixtureType, setUpMethods); var myTearDownMethods = SelectMethodsByDeclaringType(fixtureType, tearDownMethods); return new SetUpTearDownItem(mySetUpMethods, myTearDownMethods); } private static List<MethodInfo> SelectMethodsByDeclaringType(Type type, IList<MethodInfo> methods) { var list = new List<MethodInfo>(); foreach (var method in methods) if (method.DeclaringType == type) list.Add(method); return list; } /// <summary> /// Changes the result of the test, logging the old and new states /// </summary> /// <param name="resultState">The new ResultState</param> /// <param name="message">The new message</param> protected void ChangeResult(ResultState resultState, string message) { log.Debug("Changing result from {0} to {1}", Result.ResultState, resultState); Result.SetResult(resultState, message); } #endregion #region Private Methods #if PARALLEL private Thread thread; #if APARTMENT_STATE private void RunOnSeparateThread(ApartmentState apartment) #else private void RunOnSeparateThread() #endif { thread = new Thread(() => { thread.CurrentCulture = Context.CurrentCulture; thread.CurrentUICulture = Context.CurrentUICulture; #if THREAD_ABORT lock (threadLock) nativeThreadId = ThreadUtility.GetCurrentThreadNativeId(); #endif RunOnCurrentThread(); }); #if APARTMENT_STATE thread.SetApartmentState(apartment); #endif thread.Start(); thread.Join(); } #endif private void RunOnCurrentThread() { Context.CurrentTest = this.Test; Context.CurrentResult = this.Result; Context.Listener.TestStarted(this.Test); Context.StartTime = DateTime.UtcNow; Context.StartTicks = Stopwatch.GetTimestamp(); #if PARALLEL Context.TestWorker = this.TestWorker; #endif Context.EstablishExecutionEnvironment(); State = WorkItemState.Running; PerformWork(); } #if PARALLEL private ParallelExecutionStrategy GetExecutionStrategy() { // If there is no fixture and so nothing to do but dispatch // grandchildren we run directly. This saves time that would // otherwise be spent enqueuing and dequeuing items. if (Test.Type == null) return ParallelExecutionStrategy.Direct; // If the context is single-threaded we are required to run // the tests one by one on the same thread as the fixture. if (Context.IsSingleThreaded) return ParallelExecutionStrategy.Direct; // Check if item is explicitly marked as non-parallel if (ParallelScope.HasFlag(ParallelScope.None)) return ParallelExecutionStrategy.NonParallel; // Check if item is explicitly marked as parallel if (ParallelScope.HasFlag(ParallelScope.Self)) return ParallelExecutionStrategy.Parallel; // Item is not explicitly marked, so check the inherited context if (Context.ParallelScope.HasFlag(ParallelScope.Children) || Test is TestFixture && Context.ParallelScope.HasFlag(ParallelScope.Fixtures)) return ParallelExecutionStrategy.Parallel; // There is no scope specified either on the item itself or in the context. // In that case, simple work items are test cases and just run on the same // thread, while composite work items and teardowns are non-parallel. return this is SimpleWorkItem ? ParallelExecutionStrategy.Direct : ParallelExecutionStrategy.NonParallel; } #endif #if APARTMENT_STATE /// <summary> /// Recursively walks up the test hierarchy to see if the /// <see cref="ApartmentState"/> has been set on any of the parent tests. /// </summary> static ApartmentState GetTargetApartment(ITest test) { var apartment = test.Properties.ContainsKey(PropertyNames.ApartmentState) ? (ApartmentState)test.Properties.Get(PropertyNames.ApartmentState) : ApartmentState.Unknown; if (apartment == ApartmentState.Unknown && test.Parent != null) return GetTargetApartment(test.Parent); return apartment; } #endif #endregion } #if NET20 || NET35 static class ActionTargetsExtensions { public static bool HasFlag(this ActionTargets targets, ActionTargets value) { return (targets & value) != 0; } } #endif }
// 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.Windows.Input.Cursors.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.Windows.Input { static public partial class Cursors { #region Properties and indexers public static Cursor AppStarting { get { return default(Cursor); } } public static Cursor Arrow { get { return default(Cursor); } } public static Cursor ArrowCD { get { return default(Cursor); } } public static Cursor Cross { get { return default(Cursor); } } public static Cursor Hand { get { return default(Cursor); } } public static Cursor Help { get { return default(Cursor); } } public static Cursor IBeam { get { return default(Cursor); } } public static Cursor No { get { return default(Cursor); } } public static Cursor None { get { return default(Cursor); } } public static Cursor Pen { get { return default(Cursor); } } public static Cursor ScrollAll { get { return default(Cursor); } } public static Cursor ScrollE { get { return default(Cursor); } } public static Cursor ScrollN { get { return default(Cursor); } } public static Cursor ScrollNE { get { return default(Cursor); } } public static Cursor ScrollNS { get { return default(Cursor); } } public static Cursor ScrollNW { get { return default(Cursor); } } public static Cursor ScrollS { get { return default(Cursor); } } public static Cursor ScrollSE { get { return default(Cursor); } } public static Cursor ScrollSW { get { return default(Cursor); } } public static Cursor ScrollW { get { return default(Cursor); } } public static Cursor ScrollWE { get { return default(Cursor); } } public static Cursor SizeAll { get { return default(Cursor); } } public static Cursor SizeNESW { get { return default(Cursor); } } public static Cursor SizeNS { get { return default(Cursor); } } public static Cursor SizeNWSE { get { return default(Cursor); } } public static Cursor SizeWE { get { return default(Cursor); } } public static Cursor UpArrow { get { return default(Cursor); } } public static Cursor Wait { get { return default(Cursor); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Security.Cryptography { using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Globalization; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public class PasswordDeriveBytes : DeriveBytes { private int _extraCount; private int _prefix; private int _iterations; private byte[] _baseValue; private byte[] _extra; private byte[] _salt; private string _hashName; private byte[] _password; private HashAlgorithm _hash; private CspParameters _cspParams; [System.Security.SecurityCritical] // auto-generated private SafeProvHandle _safeProvHandle = null; private SafeProvHandle ProvHandle { [System.Security.SecurityCritical] // auto-generated get { if (_safeProvHandle == null) { lock (this) { if (_safeProvHandle == null) { SafeProvHandle safeProvHandle = Utils.AcquireProvHandle(_cspParams); System.Threading.Thread.MemoryBarrier(); _safeProvHandle = safeProvHandle; } } } return _safeProvHandle; } } // // public constructors // public PasswordDeriveBytes (String strPassword, byte[] rgbSalt) : this (strPassword, rgbSalt, new CspParameters()) {} public PasswordDeriveBytes (byte[] password, byte[] salt) : this (password, salt, new CspParameters()) {} public PasswordDeriveBytes (string strPassword, byte[] rgbSalt, string strHashName, int iterations) : this (strPassword, rgbSalt, strHashName, iterations, new CspParameters()) {} public PasswordDeriveBytes (byte[] password, byte[] salt, string hashName, int iterations) : this (password, salt, hashName, iterations, new CspParameters()) {} public PasswordDeriveBytes (string strPassword, byte[] rgbSalt, CspParameters cspParams) : this (strPassword, rgbSalt, "SHA1", 100, cspParams) {} public PasswordDeriveBytes (byte[] password, byte[] salt, CspParameters cspParams) : this (password, salt, "SHA1", 100, cspParams) {} public PasswordDeriveBytes (string strPassword, byte[] rgbSalt, String strHashName, int iterations, CspParameters cspParams) : this ((new UTF8Encoding(false)).GetBytes(strPassword), rgbSalt, strHashName, iterations, cspParams) {} // This method needs to be safe critical, because in debug builds the C# compiler will include null // initialization of the _safeProvHandle field in the method. Since SafeProvHandle is critical, a // transparent reference triggers an error using PasswordDeriveBytes. [SecuritySafeCritical] public PasswordDeriveBytes (byte[] password, byte[] salt, String hashName, int iterations, CspParameters cspParams) { this.IterationCount = iterations; this.Salt = salt; this.HashName = hashName; _password = password; _cspParams = cspParams; } // // public properties // public String HashName { get { return _hashName; } set { if (_baseValue != null) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_ValuesFixed", "HashName")); _hashName = value; _hash = (HashAlgorithm) CryptoConfig.CreateFromName(_hashName); } } public int IterationCount { get { return _iterations; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); Contract.EndContractBlock(); if (_baseValue != null) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_ValuesFixed", "IterationCount")); _iterations = value; } } public byte[] Salt { get { if (_salt == null) return null; return (byte[]) _salt.Clone(); } set { if (_baseValue != null) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_ValuesFixed", "Salt")); if (value == null) _salt = null; else _salt = (byte[]) value.Clone(); } } // // public methods // [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("Rfc2898DeriveBytes replaces PasswordDeriveBytes for deriving key material from a password and is preferred in new applications.")] // disable csharp compiler warning #0809: obsolete member overrides non-obsolete member: // Even though the compiler will not generate a warning for the obsolete method, the method still needs // to be marked as obsolete so that generated documentation (such as MSDN) correctly shows that the method // is obsolete and to use Rfc2898DeriveBytes instead. #pragma warning disable 0809 public override byte[] GetBytes(int cb) { int ib = 0; byte[] rgb; byte[] rgbOut = new byte[cb]; if (_baseValue == null) { ComputeBaseValue(); } else if (_extra != null) { ib = _extra.Length - _extraCount; if (ib >= cb) { Buffer.InternalBlockCopy(_extra, _extraCount, rgbOut, 0, cb); if (ib > cb) _extraCount += cb; else _extra = null; return rgbOut; } else { // // Note: The second parameter should really be _extraCount instead // However, changing this would constitute a breaking change compared // to what has shipped in V1.x. // Buffer.InternalBlockCopy(_extra, ib, rgbOut, 0, ib); _extra = null; } } rgb = ComputeBytes(cb-ib); Buffer.InternalBlockCopy(rgb, 0, rgbOut, ib, cb-ib); if (rgb.Length + ib > cb) { _extra = rgb; _extraCount = cb-ib; } return rgbOut; } #pragma warning restore 0809 public override void Reset() { _prefix = 0; _extra = null; _baseValue = null; } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (_hash != null) { _hash.Dispose(); } if (_baseValue != null) { Array.Clear(_baseValue, 0, _baseValue.Length); } if (_extra != null) { Array.Clear(_extra, 0, _extra.Length); } if (_password != null) { Array.Clear(_password, 0, _password.Length); } if (_salt != null) { Array.Clear(_salt, 0, _salt.Length); } } } [System.Security.SecuritySafeCritical] // auto-generated public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV) { if (keySize < 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize")); int algidhash = X509Utils.NameOrOidToAlgId(alghashname, OidGroup.HashAlgorithm); if (algidhash == 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm")); int algid = X509Utils.NameOrOidToAlgId(algname, OidGroup.AllGroups); if (algid == 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm")); // Validate the rgbIV array if (rgbIV == null) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidIV")); byte[] key = null; DeriveKey(ProvHandle, algid, algidhash, _password, _password.Length, keySize << 16, rgbIV, rgbIV.Length, JitHelpers.GetObjectHandleOnStack(ref key)); return key; } // // private methods // [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void DeriveKey(SafeProvHandle hProv, int algid, int algidHash, byte[] password, int cbPassword, int dwFlags, byte[] IV, int cbIV, ObjectHandleOnStack retKey); private byte[] ComputeBaseValue() { _hash.Initialize(); _hash.TransformBlock(_password, 0, _password.Length, _password, 0); if (_salt != null) _hash.TransformBlock(_salt, 0, _salt.Length, _salt, 0); _hash.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0); _baseValue = _hash.Hash; _hash.Initialize(); for (int i=1; i<(_iterations-1); i++) { _hash.ComputeHash(_baseValue); _baseValue = _hash.Hash; } return _baseValue; } [System.Security.SecurityCritical] // auto-generated private byte[] ComputeBytes(int cb) { int cbHash; int ib = 0; byte[] rgb; _hash.Initialize(); cbHash = _hash.HashSize / 8; rgb = new byte[((cb+cbHash-1)/cbHash)*cbHash]; using (CryptoStream cs = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write)) { HashPrefix(cs); cs.Write(_baseValue, 0, _baseValue.Length); cs.Close(); } Buffer.InternalBlockCopy(_hash.Hash, 0, rgb, ib, cbHash); ib += cbHash; while (cb > ib) { _hash.Initialize(); using (CryptoStream cs = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write)) { HashPrefix(cs); cs.Write(_baseValue, 0, _baseValue.Length); cs.Close(); } Buffer.InternalBlockCopy(_hash.Hash, 0, rgb, ib, cbHash); ib += cbHash; } return rgb; } void HashPrefix(CryptoStream cs) { int cb = 0; byte[] rgb = {(byte)'0', (byte)'0', (byte)'0'}; if (_prefix > 999) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_TooManyBytes")); if (_prefix >= 100) { rgb[0] += (byte) (_prefix /100); cb += 1; } if (_prefix >= 10) { rgb[cb] += (byte) ((_prefix % 100) / 10); cb += 1; } if (_prefix > 0) { rgb[cb] += (byte) (_prefix % 10); cb += 1; cs.Write(rgb, 0, cb); } _prefix += 1; } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData { #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; #if ODATALIB_ASYNC using System.Threading.Tasks; #endif using Microsoft.Data.Edm; using Microsoft.Data.OData.Metadata; #endregion Namespaces /// <summary> /// Base class for OData collection readers that verifies a proper sequence of read calls on the reader. /// </summary> internal abstract class ODataCollectionReaderCore : ODataCollectionReader { /// <summary>The input context to read from.</summary> private readonly ODataInputContext inputContext; /// <summary>The expected item type reference for the items in the collection.</summary> /// <remarks>If an expected type is specified the collection has to be homogeneous.</remarks> private readonly IEdmTypeReference expectedItemTypeReference; /// <summary>Stack of reader scopes to keep track of the current context of the reader.</summary> private readonly Stack<Scope> scopes = new Stack<Scope>(); /// <summary>If not null, the reader will notify the implementer of the interface of relevant state changes in the reader.</summary> private readonly IODataReaderWriterListener listener; /// <summary>The collection validator instance if no expected item type has been specified; otherwise null.</summary> private readonly CollectionWithoutExpectedTypeValidator collectionValidator; /// <summary> /// Constructor. /// </summary> /// <param name="inputContext">The input to read from.</param> /// <param name="expectedItemTypeReference">The expected type reference for the items in the collection.</param> /// <param name="listener">If not null, the reader will notify the implementer of the interface of relevant state changes in the reader.</param> protected ODataCollectionReaderCore( ODataInputContext inputContext, IEdmTypeReference expectedItemTypeReference, IODataReaderWriterListener listener) { this.inputContext = inputContext; this.expectedItemTypeReference = expectedItemTypeReference; if (this.expectedItemTypeReference == null) { // NOTE: collections cannot specify a type name for the collection itself, so always passing null. this.collectionValidator = new CollectionWithoutExpectedTypeValidator(/*expectedItemTypeName*/ null); } this.listener = listener; this.EnterScope(ODataCollectionReaderState.Start, null); } /// <summary> /// The current state of the reader. /// </summary> public override sealed ODataCollectionReaderState State { get { this.inputContext.VerifyNotDisposed(); Debug.Assert(this.scopes != null && this.scopes.Count > 0, "A scope must always exist."); return this.scopes.Peek().State; } } /// <summary> /// The most recent item that has been read. /// </summary> public override sealed object Item { get { this.inputContext.VerifyNotDisposed(); Debug.Assert(this.scopes != null && this.scopes.Count > 0, "A scope must always exist."); return this.scopes.Peek().Item; } } /// <summary> /// The state of the collection element - empty or non-empty. /// </summary> /// <remarks> /// Only used by ATOM. /// </remarks> protected bool IsCollectionElementEmpty { get { Debug.Assert(this.scopes != null && this.scopes.Count > 0, "A scope must always exist."); Debug.Assert(this.scopes.Peek().State == ODataCollectionReaderState.CollectionStart, "Expected the State to be CollectionStart"); return this.scopes.Peek().IsCollectionElementEmpty; } } /// <summary> /// The expected item type for the items in the collection. /// </summary> protected IEdmTypeReference ExpectedItemTypeReference { get { return this.expectedItemTypeReference; } } /// <summary> /// The collection validator instance if no expected item type has been specified; otherwise null. /// </summary> protected CollectionWithoutExpectedTypeValidator CollectionValidator { get { return this.collectionValidator; } } /// <summary> /// Returns true if we are reading a nested payload, e.g. an entry, a feed or a collection within a parameters payload. /// </summary> protected bool IsReadingNestedPayload { get { return this.listener != null; } } /// <summary> /// Reads the next item from the message payload. /// </summary> /// <returns>true if more items were read; otherwise false.</returns> public override sealed bool Read() { this.VerifyCanRead(true); return this.InterceptException(this.ReadSynchronously); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously reads the next item from the message payload. /// </summary> /// <returns>A task that when completed indicates whether more items were read.</returns> [SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")] public override sealed Task<bool> ReadAsync() { this.VerifyCanRead(false); return this.ReadAsynchronously().FollowOnFaultWith(t => this.EnterScope(ODataCollectionReaderState.Exception, null)); } #endif /// <summary> /// Reads the next <see cref="ODataItem"/> from the message payload. /// </summary> /// <returns>true if more items were read; otherwise false.</returns> protected bool ReadImplementation() { bool result; switch (this.State) { case ODataCollectionReaderState.Start: result = this.ReadAtStartImplementation(); break; case ODataCollectionReaderState.CollectionStart: result = this.ReadAtCollectionStartImplementation(); break; case ODataCollectionReaderState.Value: result = this.ReadAtValueImplementation(); break; case ODataCollectionReaderState.CollectionEnd: result = this.ReadAtCollectionEndImplementation(); break; case ODataCollectionReaderState.Exception: // fall through case ODataCollectionReaderState.Completed: Debug.Assert(false, "This case should have been caught earlier."); throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataCollectionReader_ReadImplementation)); default: Debug.Assert(false, "Unsupported collection reader state " + this.State + " detected."); throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataCollectionReader_ReadImplementation)); } return result; } /// <summary> /// Implementation of the collection reader logic when in state 'Start'. /// </summary> /// <returns>true if more items can be read from the reader; otherwise false.</returns> protected abstract bool ReadAtStartImplementation(); /// <summary> /// Implementation of the reader logic when in state 'CollectionStart'. /// </summary> /// <returns>true if more nodes can be read from the reader; otherwise false.</returns> protected abstract bool ReadAtCollectionStartImplementation(); /// <summary> /// Implementation of the reader logic when in state 'Value'. /// </summary> /// <returns>true if more nodes can be read from the reader; otherwise false.</returns> protected abstract bool ReadAtValueImplementation(); /// <summary> /// Implementation of the reader logic when in state 'CollectionEnd'. /// </summary> /// <returns>Should be false since no more nodes can be read from the reader after the collection ends.</returns> protected abstract bool ReadAtCollectionEndImplementation(); /// <summary> /// Reads the next <see cref="ODataItem"/> from the message payload. /// </summary> /// <returns>true if more items were read; otherwise false.</returns> protected bool ReadSynchronously() { return this.ReadImplementation(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously reads the next <see cref="ODataItem"/> from the message payload. /// </summary> /// <returns>A task that when completed indicates whether more items were read.</returns> [SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")] protected Task<bool> ReadAsynchronously() { // We are reading from the fully buffered read stream here; thus it is ok // to use synchronous reads and then return a completed task // NOTE: once we switch to fully async reading this will have to change return TaskUtils.GetTaskForSynchronousOperation<bool>(this.ReadImplementation); } #endif /// <summary> /// Creates a new <see cref="Scope"/> for the specified <paramref name="state"/> and /// with the provided <paramref name="item"/> and pushes it on the stack of scopes. /// </summary> /// <param name="state">The <see cref="ODataCollectionReaderState"/> to use for the new scope.</param> /// <param name="item">The item to attach with the state in the new scope.</param> protected void EnterScope(ODataCollectionReaderState state, object item) { this.EnterScope(state, item, false); } /// <summary> /// Creates a new <see cref="Scope"/> for the specified <paramref name="state"/> and /// with the provided <paramref name="item"/> and pushes it on the stack of scopes. /// </summary> /// <param name="state">The <see cref="ODataCollectionReaderState"/> to use for the new scope.</param> /// <param name="item">The item to attach with the state in the new scope.</param> /// <param name="isCollectionElementEmpty">The state of the collection element - empty or not-empty.</param> protected void EnterScope(ODataCollectionReaderState state, object item, bool isCollectionElementEmpty) { if (state == ODataCollectionReaderState.Value) { ValidationUtils.ValidateCollectionItem(item, true /* isStreamable */); } this.scopes.Push(new Scope(state, item, isCollectionElementEmpty)); if (this.listener != null) { if (state == ODataCollectionReaderState.Exception) { this.listener.OnException(); } else if (state == ODataCollectionReaderState.Completed) { this.listener.OnCompleted(); } } } /// <summary> /// Replaces the current scope with a new <see cref="Scope"/> with the specified <paramref name="state"/> and /// the item of the current scope. /// </summary> /// <param name="state">The <see cref="ODataCollectionReaderState"/> to use for the new scope.</param> /// <param name="item">The item associated with the replacement state.</param> protected void ReplaceScope(ODataCollectionReaderState state, object item) { Debug.Assert(this.scopes.Count > 0, "Stack must always be non-empty."); if (state == ODataCollectionReaderState.Value) { ValidationUtils.ValidateCollectionItem(item, true /* isStreamable */); } this.scopes.Pop(); this.EnterScope(state, item); } /// <summary> /// Removes the current scope from the stack of all scopes. /// </summary> /// <param name="state">The expected state of the current scope (to be popped).</param> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "state", Justification = "Used in debug builds in assertions.")] [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "scope", Justification = "Used in debug builds in assertions.")] protected void PopScope(ODataCollectionReaderState state) { Debug.Assert(this.scopes.Count > 1, "Stack must have more than 1 items in order to pop an item."); Scope scope = this.scopes.Pop(); Debug.Assert(scope.State == state, "scope.State == state"); } /// <summary> /// Catch any exception thrown by the action passed in; in the exception case move the reader into /// state ExceptionThrown and then rethrow the exception. /// </summary> /// <typeparam name="T">The type returned from the <paramref name="action"/> to execute.</typeparam> /// <param name="action">The action to execute.</param> /// <returns>The result of executing the <paramref name="action"/>.</returns> private T InterceptException<T>(Func<T> action) { try { return action(); } catch (Exception e) { if (ExceptionUtils.IsCatchableExceptionType(e)) { this.EnterScope(ODataCollectionReaderState.Exception, null); } throw; } } /// <summary> /// Verifies that calling Read is valid. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCanRead(bool synchronousCall) { this.inputContext.VerifyNotDisposed(); this.VerifyCallAllowed(synchronousCall); if (this.State == ODataCollectionReaderState.Exception || this.State == ODataCollectionReaderState.Completed) { throw new ODataException(Strings.ODataCollectionReaderCore_ReadOrReadAsyncCalledInInvalidState(this.State)); } } /// <summary> /// Verifies that a call is allowed to the reader. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCallAllowed(bool synchronousCall) { if (synchronousCall) { this.VerifySynchronousCallAllowed(); } else { #if ODATALIB_ASYNC this.VerifyAsynchronousCallAllowed(); #else Debug.Assert(false, "Async calls are not allowed in this build."); #endif } } /// <summary> /// Verifies that a synchronous operation is allowed on this reader. /// </summary> private void VerifySynchronousCallAllowed() { if (!this.inputContext.Synchronous) { throw new ODataException(Strings.ODataCollectionReaderCore_SyncCallOnAsyncReader); } } #if ODATALIB_ASYNC /// <summary> /// Verifies that an asynchronous operation is allowed on this reader. /// </summary> private void VerifyAsynchronousCallAllowed() { if (this.inputContext.Synchronous) { throw new ODataException(Strings.ODataCollectionReaderCore_AsyncCallOnSyncReader); } } #endif /// <summary> /// A collection reader scope; keeping track of the current reader state and an item associated with this state. /// </summary> protected sealed class Scope { /// <summary>The reader state of this scope.</summary> private readonly ODataCollectionReaderState state; /// <summary>The item attached to this scope.</summary> private readonly object item; /// <summary>True, if the collection element attached to this scope is empty. False otherwise.</summary> private readonly bool isCollectionElementEmpty; /// <summary> /// Constructor creating a new reader scope. /// </summary> /// <param name="state">The reader state of this scope.</param> /// <param name="item">The item attached to this scope.</param> [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Debug.Assert check only.")] public Scope(ODataCollectionReaderState state, object item) : this(state, item, false) { } /// <summary> /// Constructor creating a new reader scope. /// </summary> /// <param name="state">The reader state of this scope.</param> /// <param name="item">The item attached to this scope.</param> /// <param name="isCollectionElementEmpty">The state of the collection element - empty or not-empty</param> [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Debug.Assert check only.")] public Scope(ODataCollectionReaderState state, object item, bool isCollectionElementEmpty) { Debug.Assert( state == ODataCollectionReaderState.Start && item == null || state == ODataCollectionReaderState.CollectionStart && item is ODataCollectionStart || state == ODataCollectionReaderState.Value && (item == null || item is ODataComplexValue || EdmLibraryExtensions.IsPrimitiveType(item.GetType())) || state == ODataCollectionReaderState.CollectionEnd && item is ODataCollectionStart || state == ODataCollectionReaderState.Exception && item == null || state == ODataCollectionReaderState.Completed && item == null, "Reader state and associated item do not match."); this.state = state; this.item = item; this.isCollectionElementEmpty = isCollectionElementEmpty; if (this.isCollectionElementEmpty) { Debug.Assert(state == ODataCollectionReaderState.CollectionStart, "Expected state to be CollectionStart."); } } /// <summary> /// The reader state of this scope. /// </summary> public ODataCollectionReaderState State { get { return this.state; } } /// <summary> /// The item attached to this scope. /// </summary> public object Item { get { return this.item; } } /// <summary> /// The state of the Collection Element - empty or non-empty. /// </summary> public bool IsCollectionElementEmpty { get { return this.isCollectionElementEmpty; } } } } }
using CodeForDevices.WindowsUniversal.Hardware.Buses; using CodeForDotNet; using CodeForDotNet.Diagnostics; using Emlid.WindowsIot.Hardware.Protocols.Ppm; using System; using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Windows.Devices.Gpio; namespace Emlid.WindowsIot.Hardware.Boards.Navio.Internal { /// <summary> /// Navio Remote Control input hardware device. /// </summary> /// <remarks> /// Navio provides RC (receiver) input via a connector on it's servo rail mapped to GPIO pin 4. /// Navio+ has a logic level converter and you can connect receivers which generate both 3.3V and 5V signals. /// The older Navio model only has a built-in voltage divider in PPM Input that lowers the voltage level from 5V to 3.3V. /// So if you connect a 3.3V PPM device (which is rare) to the original Navio, no signal will not be detected. /// </remarks> public sealed class Navio1RCInputDevice : DisposableObject, INavioRCInputDevice { #region Constants /// <summary> /// GPIO controller index of the chip on the Navio board. /// </summary> public const int GpioControllerIndex = 0; /// <summary> /// GPIO pin number which is mapped to the RC input connector. /// </summary> public const int GpioInputPinNumber = 4; #endregion Constants #region Lifetime /// <summary> /// Creates and initializes an instance. /// </summary> public Navio1RCInputDevice() { try { // Initialize buffers _pulseBuffer = new ConcurrentQueue<PpmPulse>(); _pulseTrigger = new AutoResetEvent(false); _frameBuffer = new ConcurrentQueue<PpmFrame>(); _frameTrigger = new AutoResetEvent(false); // Configure GPIO _inputPin = GpioExtensions.Connect(GpioControllerIndex, GpioInputPinNumber, GpioPinDriveMode.Input, GpioSharingMode.Exclusive); if (_inputPin == null) { // Initialization error throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.Strings.GpioErrorDeviceNotFound, GpioInputPinNumber, GpioControllerIndex)); } if (_inputPin.DebounceTimeout != TimeSpan.Zero) _inputPin.DebounceTimeout = TimeSpan.Zero; // Create decoder thread (CPPM only to start with, SBus desired) _decoder = new CppmDecoder(); _stop = new CancellationTokenSource(); _channels = new int[_decoder.MaximumChannels]; Channels = new ReadOnlyCollection<int>(_channels); _decoderTask = Task.Factory.StartNew(() => { _decoder.DecodePulse(_pulseBuffer, _pulseTrigger, _frameBuffer, _frameTrigger, _stop.Token); }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); // Create receiver thread _receiverTask = Task.Factory.StartNew(() => { Receiver(); }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); // Hook events _inputPin.ValueChanged += OnInputPinValueChanged; // Start buffered event handling // TODO: Support buffered GPIO when possible //_inputPin.CreateInterruptBuffer(); //_inputPin.StartInterruptBuffer(); //_inputPin.StopInterruptCount(); } catch { // Close device in case partially initialized _inputPin?.Dispose(); // Continue error throw; } } #region IDisposable /// <summary> /// Frees resources owned by this instance. /// </summary> /// <param name="disposing"> /// True when called via <see cref="IDisposable.Dispose()"/>, false when called from the finalizer. /// </param> protected override void Dispose(bool disposing) { // Only managed resources to dispose if (!disposing) return; // Unhook events _inputPin.ValueChanged -= OnInputPinValueChanged; // Stop interrupts // TODO: Support buffered GPIO when possible //_inputPin.StopInterruptCount(); //_inputPin.StopInterruptBuffer(); // Stop background tasks if (_stop != null) { _stop.Cancel(); _stop.Dispose(); } // Stop events _pulseTrigger?.Dispose(); _frameTrigger?.Dispose(); // Close device _inputPin?.Dispose(); } #endregion IDisposable #endregion Lifetime #region Private Fields /// <summary> /// GPIO RC input pin. /// </summary> private readonly GpioPin _inputPin; /// <summary> /// Decoder called when each PPM cycle is detected. /// </summary> private readonly IPpmDecoder _decoder; /// <summary> /// Background decoder task. /// </summary> private readonly Task _decoderTask; /// <summary> /// Background receiver task. /// </summary> private readonly Task _receiverTask; /// <summary> /// Cancellation token used to signal worker threads to stop. /// </summary> private readonly CancellationTokenSource _stop; /// <summary> /// Buffer containing raw PPM pulses. /// </summary> private readonly ConcurrentQueue<PpmPulse> _pulseBuffer; /// <summary> /// Event used to signal the decoder that new captured PPM values are waiting to decode. /// </summary> private readonly AutoResetEvent _pulseTrigger; /// <summary> /// Buffer containing decoded PPM frames. /// </summary> private readonly ConcurrentQueue<PpmFrame> _frameBuffer; /// <summary> /// Event used to signal the consumer that new decoded PPM frames are ready to use. /// </summary> private readonly AutoResetEvent _frameTrigger; #endregion Private Fields #region Properties /// <summary> /// Channel values in microseconds. /// </summary> public ReadOnlyCollection<int> Channels { get; private set; } private int[] _channels; /// <summary> /// Returns false because multiple protocols are not supported, only CPPM. /// </summary> public bool Multiprotocol { get { return false; } } #endregion Properties #region Events /// <summary> /// Handles GPIO changes (rising and falling PPM signal), recording them to the decoder queue. /// </summary> /// <param name="sender">Event source, the <see cref="GpioPin"/> which changed.</param> /// <param name="arguments">Information about the GPIO pin value change.</param> /// <remarks> /// Main hardware routine which triggers the input translation process. /// This code must run as quickly as possible else we could miss the next event! /// </remarks> private void OnInputPinValueChanged(GpioPin sender, GpioPinValueChangedEventArgs arguments) { // Get PPM value var time = StopwatchExtensions.GetTimestampInMicroseconds(); var level = arguments.Edge == GpioPinEdge.RisingEdge; var value = new PpmPulse(time, level); // Queue for processing _pulseBuffer.Enqueue(value); _pulseTrigger.Set(); } /// <summary> /// Fired after a new frame of data has been received and decoded into <see cref="Channels"/>. /// </summary> public event EventHandler<PpmFrame> ChannelsChanged; #endregion Events #region Private Methods /// <summary> /// Waits for decoded frames, updates the <see cref="Channels"/> property and fires /// the <see cref="ChannelsChanged"/> event on a separate thread. /// </summary> private void Receiver() { while (!_stop.IsCancellationRequested) { // Run until stopped... // Wait for frame if (!_frameBuffer.TryDequeue(out PpmFrame frame)) { _frameTrigger.WaitOne(1000); continue; } // Validate var channelCount = frame.Channels.Count; if (channelCount > _channels.Length) { // Too many channels Debug.WriteLine(Resources.Strings.NavioRCInputDecoderChannelOverflow, channelCount, _channels.Length); continue; } // Copy new channel data for (var index = 0; index < channelCount; index++) _channels[index] = frame.Channels[index]; // Fire event ChannelsChanged?.Invoke(this, frame); } } #endregion Private Methods } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: supply/rpc/room_type_svc.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Supply.RPC { /// <summary>Holder for reflection information generated from supply/rpc/room_type_svc.proto</summary> public static partial class RoomTypeSvcReflection { #region Descriptor /// <summary>File descriptor for supply/rpc/room_type_svc.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static RoomTypeSvcReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ch5zdXBwbHkvcnBjL3Jvb21fdHlwZV9zdmMucHJvdG8SFmhvbG1zLnR5cGVz", "LnN1cHBseS5ycGMaKnByaW1pdGl2ZS9zZXJ2ZXJfYWN0aW9uX2NvbmZpcm1h", "dGlvbi5wcm90bxodcHJpbWl0aXZlL3BiX2xvY2FsX2RhdGUucHJvdG8aG2dv", "b2dsZS9wcm90b2J1Zi9lbXB0eS5wcm90bxomc3VwcGx5L3Jvb21fdHlwZXMv", "ZnVsbF9yb29tX3R5cGUucHJvdG8aIXN1cHBseS9yb29tX3R5cGVzL3Jvb21f", "dHlwZS5wcm90bxorc3VwcGx5L3Jvb21fdHlwZXMvcm9vbV90eXBlX2luZGlj", "YXRvci5wcm90bxouYm9va2luZy9yZXNlcnZhdGlvbnMvcmVzZXJ2YXRpb25f", "c3VtbWFyeS5wcm90bxobb3BlcmF0aW9ucy9yb29tcy9yb29tLnByb3RvIlUK", "FlJvb21UeXBlU3ZjQWxsUmVzcG9uc2USOwoKcm9vbV90eXBlcxgBIAMoCzIn", "LmhvbG1zLnR5cGVzLnN1cHBseS5yb29tX3R5cGVzLlJvb21UeXBlImIKH1Jv", "b21UeXBlU3ZjQWxsV2l0aFJvb21zUmVzcG9uc2USPwoKcm9vbV90eXBlcxgB", "IAMoCzIrLmhvbG1zLnR5cGVzLnN1cHBseS5yb29tX3R5cGVzLkZ1bGxSb29t", "VHlwZSJDCiVSb29tVHlwZVN2Y0dldEJ5Q2hhbm5lbE1hbmFnZXJSZXF1ZXN0", "EhoKEmNoYW5uZWxfbWFuYWdlcl9pZBgBIAEoCSL+AQoZUm9vbVR5cGVTdmNV", "cGRhdGVSZXNwb25zZRI/CgZyZXN1bHQYASABKA4yLy5ob2xtcy50eXBlcy5z", "dXBwbHkucnBjLlJvb21UeXBlU3ZjVXBkYXRlUmVzdWx0EjgKB3VwZGF0ZWQY", "AiABKAsyJy5ob2xtcy50eXBlcy5zdXBwbHkucm9vbV90eXBlcy5Sb29tVHlw", "ZRIgChh0b3RhbF9pbGxlZ2FsX2hvbGRfZGF0ZXMYAyABKA0SRAoYZmlyc3Rf", "aWxsZWdhbF9ob2xkX2RhdGVzGAQgAygLMiIuaG9sbXMudHlwZXMucHJpbWl0", "aXZlLlBiTG9jYWxEYXRlIqMBChlDaGVja0RlcGVuZGVuY2llc1Jlc3BvbnNl", "EkoKDHJlc2VydmF0aW9ucxgBIAMoCzI0LmhvbG1zLnR5cGVzLmJvb2tpbmcu", "cmVzZXJ2YXRpb25zLlJlc2VydmF0aW9uU3VtbWFyeRI6Cg5hdHRhY2hlZF9y", "b29tcxgCIAMoCzIiLmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucm9vbXMuUm9v", "bSqQAQoXUm9vbVR5cGVTdmNVcGRhdGVSZXN1bHQSIgoeUk9PTV9UWVBFX1NW", "Q19VUERBVEVfUkVTVUxUX09LEAASIgoeUk9PTV9UWVBFX1NWQ19VUERBVEVf", "Tk9UX0ZPVU5EEAESLQopUk9PTV9UWVBFX1NWQ19VUERBVEVfUkVTVUxUX0lM", "TEVHQUxfSE9MRFMQAjK7BgoLUm9vbVR5cGVTdmMSTQoDQWxsEhYuZ29vZ2xl", "LnByb3RvYnVmLkVtcHR5Gi4uaG9sbXMudHlwZXMuc3VwcGx5LnJwYy5Sb29t", "VHlwZVN2Y0FsbFJlc3BvbnNlEl8KDEFsbFdpdGhSb29tcxIWLmdvb2dsZS5w", "cm90b2J1Zi5FbXB0eRo3LmhvbG1zLnR5cGVzLnN1cHBseS5ycGMuUm9vbVR5", "cGVTdmNBbGxXaXRoUm9vbXNSZXNwb25zZRJkCgdHZXRCeUlkEjAuaG9sbXMu", "dHlwZXMuc3VwcGx5LnJvb21fdHlwZXMuUm9vbVR5cGVJbmRpY2F0b3IaJy5o", "b2xtcy50eXBlcy5zdXBwbHkucm9vbV90eXBlcy5Sb29tVHlwZRJ/ChVHZXRC", "eUNoYW5uZWxNYW5hZ2VySWQSPS5ob2xtcy50eXBlcy5zdXBwbHkucnBjLlJv", "b21UeXBlU3ZjR2V0QnlDaGFubmVsTWFuYWdlclJlcXVlc3QaJy5ob2xtcy50", "eXBlcy5zdXBwbHkucm9vbV90eXBlcy5Sb29tVHlwZRJaCgZDcmVhdGUSJy5o", "b2xtcy50eXBlcy5zdXBwbHkucm9vbV90eXBlcy5Sb29tVHlwZRonLmhvbG1z", "LnR5cGVzLnN1cHBseS5yb29tX3R5cGVzLlJvb21UeXBlEmQKBlVwZGF0ZRIn", "LmhvbG1zLnR5cGVzLnN1cHBseS5yb29tX3R5cGVzLlJvb21UeXBlGjEuaG9s", "bXMudHlwZXMuc3VwcGx5LnJwYy5Sb29tVHlwZVN2Y1VwZGF0ZVJlc3BvbnNl", "EmIKBkRlbGV0ZRInLmhvbG1zLnR5cGVzLnN1cHBseS5yb29tX3R5cGVzLlJv", "b21UeXBlGi8uaG9sbXMudHlwZXMucHJpbWl0aXZlLlNlcnZlckFjdGlvbkNv", "bmZpcm1hdGlvbhJvChFDaGVja0RlcGVuZGVuY2llcxInLmhvbG1zLnR5cGVz", "LnN1cHBseS5yb29tX3R5cGVzLlJvb21UeXBlGjEuaG9sbXMudHlwZXMuc3Vw", "cGx5LnJwYy5DaGVja0RlcGVuZGVuY2llc1Jlc3BvbnNlQhmqAhZIT0xNUy5U", "eXBlcy5TdXBwbHkuUlBDYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.ServerActionConfirmationReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.FullRoomTypeReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Reservations.ReservationSummaryReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Supply.RPC.RoomTypeSvcUpdateResult), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.RoomTypeSvcAllResponse), global::HOLMS.Types.Supply.RPC.RoomTypeSvcAllResponse.Parser, new[]{ "RoomTypes" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.RoomTypeSvcAllWithRoomsResponse), global::HOLMS.Types.Supply.RPC.RoomTypeSvcAllWithRoomsResponse.Parser, new[]{ "RoomTypes" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.RoomTypeSvcGetByChannelManagerRequest), global::HOLMS.Types.Supply.RPC.RoomTypeSvcGetByChannelManagerRequest.Parser, new[]{ "ChannelManagerId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.RoomTypeSvcUpdateResponse), global::HOLMS.Types.Supply.RPC.RoomTypeSvcUpdateResponse.Parser, new[]{ "Result", "Updated", "TotalIllegalHoldDates", "FirstIllegalHoldDates" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.RPC.CheckDependenciesResponse), global::HOLMS.Types.Supply.RPC.CheckDependenciesResponse.Parser, new[]{ "Reservations", "AttachedRooms" }, null, null, null) })); } #endregion } #region Enums public enum RoomTypeSvcUpdateResult { [pbr::OriginalName("ROOM_TYPE_SVC_UPDATE_RESULT_OK")] Ok = 0, [pbr::OriginalName("ROOM_TYPE_SVC_UPDATE_NOT_FOUND")] RoomTypeSvcUpdateNotFound = 1, [pbr::OriginalName("ROOM_TYPE_SVC_UPDATE_RESULT_ILLEGAL_HOLDS")] IllegalHolds = 2, } #endregion #region Messages public sealed partial class RoomTypeSvcAllResponse : pb::IMessage<RoomTypeSvcAllResponse> { private static readonly pb::MessageParser<RoomTypeSvcAllResponse> _parser = new pb::MessageParser<RoomTypeSvcAllResponse>(() => new RoomTypeSvcAllResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RoomTypeSvcAllResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.RoomTypeSvcReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcAllResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcAllResponse(RoomTypeSvcAllResponse other) : this() { roomTypes_ = other.roomTypes_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcAllResponse Clone() { return new RoomTypeSvcAllResponse(this); } /// <summary>Field number for the "room_types" field.</summary> public const int RoomTypesFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.Supply.RoomTypes.RoomType> _repeated_roomTypes_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Supply.RoomTypes.RoomType.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Supply.RoomTypes.RoomType> roomTypes_ = new pbc::RepeatedField<global::HOLMS.Types.Supply.RoomTypes.RoomType>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Supply.RoomTypes.RoomType> RoomTypes { get { return roomTypes_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RoomTypeSvcAllResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RoomTypeSvcAllResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!roomTypes_.Equals(other.roomTypes_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= roomTypes_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { roomTypes_.WriteTo(output, _repeated_roomTypes_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += roomTypes_.CalculateSize(_repeated_roomTypes_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RoomTypeSvcAllResponse other) { if (other == null) { return; } roomTypes_.Add(other.roomTypes_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { roomTypes_.AddEntriesFrom(input, _repeated_roomTypes_codec); break; } } } } } public sealed partial class RoomTypeSvcAllWithRoomsResponse : pb::IMessage<RoomTypeSvcAllWithRoomsResponse> { private static readonly pb::MessageParser<RoomTypeSvcAllWithRoomsResponse> _parser = new pb::MessageParser<RoomTypeSvcAllWithRoomsResponse>(() => new RoomTypeSvcAllWithRoomsResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RoomTypeSvcAllWithRoomsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.RoomTypeSvcReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcAllWithRoomsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcAllWithRoomsResponse(RoomTypeSvcAllWithRoomsResponse other) : this() { roomTypes_ = other.roomTypes_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcAllWithRoomsResponse Clone() { return new RoomTypeSvcAllWithRoomsResponse(this); } /// <summary>Field number for the "room_types" field.</summary> public const int RoomTypesFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.Supply.RoomTypes.FullRoomType> _repeated_roomTypes_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Supply.RoomTypes.FullRoomType.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Supply.RoomTypes.FullRoomType> roomTypes_ = new pbc::RepeatedField<global::HOLMS.Types.Supply.RoomTypes.FullRoomType>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Supply.RoomTypes.FullRoomType> RoomTypes { get { return roomTypes_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RoomTypeSvcAllWithRoomsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RoomTypeSvcAllWithRoomsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!roomTypes_.Equals(other.roomTypes_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= roomTypes_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { roomTypes_.WriteTo(output, _repeated_roomTypes_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += roomTypes_.CalculateSize(_repeated_roomTypes_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RoomTypeSvcAllWithRoomsResponse other) { if (other == null) { return; } roomTypes_.Add(other.roomTypes_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { roomTypes_.AddEntriesFrom(input, _repeated_roomTypes_codec); break; } } } } } public sealed partial class RoomTypeSvcGetByChannelManagerRequest : pb::IMessage<RoomTypeSvcGetByChannelManagerRequest> { private static readonly pb::MessageParser<RoomTypeSvcGetByChannelManagerRequest> _parser = new pb::MessageParser<RoomTypeSvcGetByChannelManagerRequest>(() => new RoomTypeSvcGetByChannelManagerRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RoomTypeSvcGetByChannelManagerRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.RoomTypeSvcReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcGetByChannelManagerRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcGetByChannelManagerRequest(RoomTypeSvcGetByChannelManagerRequest other) : this() { channelManagerId_ = other.channelManagerId_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcGetByChannelManagerRequest Clone() { return new RoomTypeSvcGetByChannelManagerRequest(this); } /// <summary>Field number for the "channel_manager_id" field.</summary> public const int ChannelManagerIdFieldNumber = 1; private string channelManagerId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ChannelManagerId { get { return channelManagerId_; } set { channelManagerId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RoomTypeSvcGetByChannelManagerRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RoomTypeSvcGetByChannelManagerRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ChannelManagerId != other.ChannelManagerId) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ChannelManagerId.Length != 0) hash ^= ChannelManagerId.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ChannelManagerId.Length != 0) { output.WriteRawTag(10); output.WriteString(ChannelManagerId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ChannelManagerId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ChannelManagerId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RoomTypeSvcGetByChannelManagerRequest other) { if (other == null) { return; } if (other.ChannelManagerId.Length != 0) { ChannelManagerId = other.ChannelManagerId; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { ChannelManagerId = input.ReadString(); break; } } } } } public sealed partial class RoomTypeSvcUpdateResponse : pb::IMessage<RoomTypeSvcUpdateResponse> { private static readonly pb::MessageParser<RoomTypeSvcUpdateResponse> _parser = new pb::MessageParser<RoomTypeSvcUpdateResponse>(() => new RoomTypeSvcUpdateResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RoomTypeSvcUpdateResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.RoomTypeSvcReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcUpdateResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcUpdateResponse(RoomTypeSvcUpdateResponse other) : this() { result_ = other.result_; Updated = other.updated_ != null ? other.Updated.Clone() : null; totalIllegalHoldDates_ = other.totalIllegalHoldDates_; firstIllegalHoldDates_ = other.firstIllegalHoldDates_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomTypeSvcUpdateResponse Clone() { return new RoomTypeSvcUpdateResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private global::HOLMS.Types.Supply.RPC.RoomTypeSvcUpdateResult result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.RPC.RoomTypeSvcUpdateResult Result { get { return result_; } set { result_ = value; } } /// <summary>Field number for the "updated" field.</summary> public const int UpdatedFieldNumber = 2; private global::HOLMS.Types.Supply.RoomTypes.RoomType updated_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.RoomTypes.RoomType Updated { get { return updated_; } set { updated_ = value; } } /// <summary>Field number for the "total_illegal_hold_dates" field.</summary> public const int TotalIllegalHoldDatesFieldNumber = 3; private uint totalIllegalHoldDates_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint TotalIllegalHoldDates { get { return totalIllegalHoldDates_; } set { totalIllegalHoldDates_ = value; } } /// <summary>Field number for the "first_illegal_hold_dates" field.</summary> public const int FirstIllegalHoldDatesFieldNumber = 4; private static readonly pb::FieldCodec<global::HOLMS.Types.Primitive.PbLocalDate> _repeated_firstIllegalHoldDates_codec = pb::FieldCodec.ForMessage(34, global::HOLMS.Types.Primitive.PbLocalDate.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Primitive.PbLocalDate> firstIllegalHoldDates_ = new pbc::RepeatedField<global::HOLMS.Types.Primitive.PbLocalDate>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Primitive.PbLocalDate> FirstIllegalHoldDates { get { return firstIllegalHoldDates_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RoomTypeSvcUpdateResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RoomTypeSvcUpdateResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; if (!object.Equals(Updated, other.Updated)) return false; if (TotalIllegalHoldDates != other.TotalIllegalHoldDates) return false; if(!firstIllegalHoldDates_.Equals(other.firstIllegalHoldDates_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); if (updated_ != null) hash ^= Updated.GetHashCode(); if (TotalIllegalHoldDates != 0) hash ^= TotalIllegalHoldDates.GetHashCode(); hash ^= firstIllegalHoldDates_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } if (updated_ != null) { output.WriteRawTag(18); output.WriteMessage(Updated); } if (TotalIllegalHoldDates != 0) { output.WriteRawTag(24); output.WriteUInt32(TotalIllegalHoldDates); } firstIllegalHoldDates_.WriteTo(output, _repeated_firstIllegalHoldDates_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } if (updated_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Updated); } if (TotalIllegalHoldDates != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(TotalIllegalHoldDates); } size += firstIllegalHoldDates_.CalculateSize(_repeated_firstIllegalHoldDates_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RoomTypeSvcUpdateResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } if (other.updated_ != null) { if (updated_ == null) { updated_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType(); } Updated.MergeFrom(other.Updated); } if (other.TotalIllegalHoldDates != 0) { TotalIllegalHoldDates = other.TotalIllegalHoldDates; } firstIllegalHoldDates_.Add(other.firstIllegalHoldDates_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::HOLMS.Types.Supply.RPC.RoomTypeSvcUpdateResult) input.ReadEnum(); break; } case 18: { if (updated_ == null) { updated_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType(); } input.ReadMessage(updated_); break; } case 24: { TotalIllegalHoldDates = input.ReadUInt32(); break; } case 34: { firstIllegalHoldDates_.AddEntriesFrom(input, _repeated_firstIllegalHoldDates_codec); break; } } } } } public sealed partial class CheckDependenciesResponse : pb::IMessage<CheckDependenciesResponse> { private static readonly pb::MessageParser<CheckDependenciesResponse> _parser = new pb::MessageParser<CheckDependenciesResponse>(() => new CheckDependenciesResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CheckDependenciesResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.RoomTypeSvcReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckDependenciesResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckDependenciesResponse(CheckDependenciesResponse other) : this() { reservations_ = other.reservations_.Clone(); attachedRooms_ = other.attachedRooms_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckDependenciesResponse Clone() { return new CheckDependenciesResponse(this); } /// <summary>Field number for the "reservations" field.</summary> public const int ReservationsFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Reservations.ReservationSummary> _repeated_reservations_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Booking.Reservations.ReservationSummary.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationSummary> reservations_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationSummary>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationSummary> Reservations { get { return reservations_; } } /// <summary>Field number for the "attached_rooms" field.</summary> public const int AttachedRoomsFieldNumber = 2; private static readonly pb::FieldCodec<global::HOLMS.Types.Operations.Rooms.Room> _repeated_attachedRooms_codec = pb::FieldCodec.ForMessage(18, global::HOLMS.Types.Operations.Rooms.Room.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.Room> attachedRooms_ = new pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.Room>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Operations.Rooms.Room> AttachedRooms { get { return attachedRooms_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CheckDependenciesResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CheckDependenciesResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!reservations_.Equals(other.reservations_)) return false; if(!attachedRooms_.Equals(other.attachedRooms_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= reservations_.GetHashCode(); hash ^= attachedRooms_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { reservations_.WriteTo(output, _repeated_reservations_codec); attachedRooms_.WriteTo(output, _repeated_attachedRooms_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += reservations_.CalculateSize(_repeated_reservations_codec); size += attachedRooms_.CalculateSize(_repeated_attachedRooms_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CheckDependenciesResponse other) { if (other == null) { return; } reservations_.Add(other.reservations_); attachedRooms_.Add(other.attachedRooms_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { reservations_.AddEntriesFrom(input, _repeated_reservations_codec); break; } case 18: { attachedRooms_.AddEntriesFrom(input, _repeated_attachedRooms_codec); break; } } } } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; namespace System.Collections.Immutable { /// <summary> /// A node in the AVL tree storing key/value pairs with Int32 keys. /// </summary> /// <remarks> /// This is a trimmed down version of <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> /// with <c>TKey</c> fixed to be <see cref="int"/>. This avoids multiple interface-based dispatches while examining /// each node in the tree during a lookup: an interface call to the comparer's <see cref="IComparer{T}.Compare"/> method, /// and then an interface call to <see cref="int"/>'s <see cref="IComparable{T}.CompareTo"/> method as part of /// the <see cref="T:System.Collections.Generic.GenericComparer`1"/>'s <see cref="IComparer{T}.Compare"/> implementation. /// </remarks> [DebuggerDisplay("{_key} = {_value}")] internal sealed partial class SortedInt32KeyNode<TValue> : IBinaryTree { /// <summary> /// The default empty node. /// </summary> internal static readonly SortedInt32KeyNode<TValue> EmptyNode = new SortedInt32KeyNode<TValue>(); /// <summary> /// The Int32 key associated with this node. /// </summary> private readonly int _key; /// <summary> /// The value associated with this node. /// </summary> private readonly TValue _value; /// <summary> /// A value indicating whether this node has been frozen (made immutable). /// </summary> /// <remarks> /// Nodes must be frozen before ever being observed by a wrapping collection type /// to protect collections from further mutations. /// </remarks> private bool _frozen; /// <summary> /// The depth of the tree beneath this node. /// </summary> private byte _height; // AVL tree height <= ~1.44 * log2(numNodes + 2) /// <summary> /// The left tree. /// </summary> private SortedInt32KeyNode<TValue> _left; /// <summary> /// The right tree. /// </summary> private SortedInt32KeyNode<TValue> _right; /// <summary> /// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is pre-frozen. /// </summary> private SortedInt32KeyNode() { _frozen = true; // the empty node is *always* frozen. } /// <summary> /// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is not yet frozen. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <param name="frozen">Whether this node is prefrozen.</param> private SortedInt32KeyNode(int key, TValue value, SortedInt32KeyNode<TValue> left, SortedInt32KeyNode<TValue> right, bool frozen = false) { Requires.NotNull(left, nameof(left)); Requires.NotNull(right, nameof(right)); Debug.Assert(!frozen || (left._frozen && right._frozen)); _key = key; _value = value; _left = left; _right = right; _frozen = frozen; _height = checked((byte)(1 + Math.Max(left._height, right._height))); } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return _left == null; } } /// <summary> /// Gets the height of the tree beneath this node. /// </summary> public int Height { get { return _height; } } /// <summary> /// Gets the left branch of this node. /// </summary> public SortedInt32KeyNode<TValue> Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> public SortedInt32KeyNode<TValue> Right { get { return _right; } } /// <summary> /// Gets the left branch of this node. /// </summary> IBinaryTree IBinaryTree.Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> IBinaryTree IBinaryTree.Right { get { return _right; } } /// <summary> /// Gets the number of elements contained by this node and below. /// </summary> int IBinaryTree.Count { get { throw new NotSupportedException(); } } /// <summary> /// Gets the value represented by the current node. /// </summary> public KeyValuePair<int, TValue> Value { get { return new KeyValuePair<int, TValue>(_key, _value); } } /// <summary> /// Gets the values. /// </summary> internal IEnumerable<TValue> Values { get { foreach (var pair in this) { yield return pair.Value; } } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> internal SortedInt32KeyNode<TValue> SetItem(int key, TValue value, IEqualityComparer<TValue> valueComparer, out bool replacedExistingValue, out bool mutated) { Requires.NotNull(valueComparer, nameof(valueComparer)); return this.SetOrAdd(key, value, valueComparer, true, out replacedExistingValue, out mutated); } /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> internal SortedInt32KeyNode<TValue> Remove(int key, out bool mutated) { return this.RemoveRecursive(key, out mutated); } /// <summary> /// Gets the value or default. /// </summary> /// <param name="key">The key.</param> /// <returns>The value.</returns> [Pure] internal TValue GetValueOrDefault(int key) { var match = this.Search(key); return match.IsEmpty ? default(TValue) : match._value; } /// <summary> /// Tries to get the value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>True if the key was found.</returns> [Pure] internal bool TryGetValue(int key, out TValue value) { var match = this.Search(key); if (match.IsEmpty) { value = default(TValue); return false; } else { value = match._value; return true; } } /// <summary> /// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes. /// </summary> internal void Freeze(Action<KeyValuePair<int, TValue>> freezeAction = null) { // If this node is frozen, all its descendants must already be frozen. if (!_frozen) { freezeAction?.Invoke(new KeyValuePair<int, TValue>(_key, _value)); _left.Freeze(freezeAction); _right.Freeze(freezeAction); _frozen = true; } } /// <summary> /// AVL rotate left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> RotateLeft(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); if (tree._right.IsEmpty) { return tree; } var right = tree._right; return right.Mutate(left: tree.Mutate(right: right._left)); } /// <summary> /// AVL rotate right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> RotateRight(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); if (tree._left.IsEmpty) { return tree; } var left = tree._left; return left.Mutate(right: tree.Mutate(left: left._right)); } /// <summary> /// AVL rotate double-left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> DoubleLeft(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); if (tree._right.IsEmpty) { return tree; } SortedInt32KeyNode<TValue> rotatedRightChild = tree.Mutate(right: RotateRight(tree._right)); return RotateLeft(rotatedRightChild); } /// <summary> /// AVL rotate double-right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> DoubleRight(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); if (tree._left.IsEmpty) { return tree; } SortedInt32KeyNode<TValue> rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left)); return RotateRight(rotatedLeftChild); } /// <summary> /// Returns a value indicating whether the tree is in balance. /// </summary> /// <param name="tree">The tree.</param> /// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns> [Pure] private static int Balance(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return tree._right._height - tree._left._height; } /// <summary> /// Determines whether the specified tree is right heavy. /// </summary> /// <param name="tree">The tree.</param> /// <returns> /// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>. /// </returns> [Pure] private static bool IsRightHeavy(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return Balance(tree) >= 2; } /// <summary> /// Determines whether the specified tree is left heavy. /// </summary> [Pure] private static bool IsLeftHeavy(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return Balance(tree) <= -2; } /// <summary> /// Balances the specified tree. /// </summary> /// <param name="tree">The tree.</param> /// <returns>A balanced tree.</returns> [Pure] private static SortedInt32KeyNode<TValue> MakeBalanced(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); if (IsRightHeavy(tree)) { return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree); } if (IsLeftHeavy(tree)) { return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree); } return tree; } /// <summary> /// Adds the specified key. Callers are expected to have validated arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="overwriteExistingValue">if <c>true</c>, an existing key=value pair will be overwritten with the new one.</param> /// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> private SortedInt32KeyNode<TValue> SetOrAdd(int key, TValue value, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated) { // Arg validation skipped in this private method because it's recursive and the tax // of revalidating arguments on each recursive call is significant. // All our callers are therefore required to have done input validation. replacedExistingValue = false; if (this.IsEmpty) { mutated = true; return new SortedInt32KeyNode<TValue>(key, value, this, this); } else { SortedInt32KeyNode<TValue> result = this; if (key > _key) { var newRight = _right.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } else if (key < _key) { var newLeft = _left.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { if (valueComparer.Equals(_value, value)) { mutated = false; return this; } else if (overwriteExistingValue) { mutated = true; replacedExistingValue = true; result = new SortedInt32KeyNode<TValue>(key, value, _left, _right); } else { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key)); } } return mutated ? MakeBalanced(result) : result; } } /// <summary> /// Removes the specified key. Callers are expected to validate arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> private SortedInt32KeyNode<TValue> RemoveRecursive(int key, out bool mutated) { if (this.IsEmpty) { mutated = false; return this; } else { SortedInt32KeyNode<TValue> result = this; if (key == _key) { // We have a match. mutated = true; // If this is a leaf, just remove it // by returning Empty. If we have only one child, // replace the node with the child. if (_right.IsEmpty && _left.IsEmpty) { result = EmptyNode; } else if (_right.IsEmpty && !_left.IsEmpty) { result = _left; } else if (!_right.IsEmpty && _left.IsEmpty) { result = _right; } else { // We have two children. Remove the next-highest node and replace // this node with it. var successor = _right; while (!successor._left.IsEmpty) { successor = successor._left; } bool dummyMutated; var newRight = _right.Remove(successor._key, out dummyMutated); result = successor.Mutate(left: _left, right: newRight); } } else if (key < _key) { var newLeft = _left.Remove(key, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { var newRight = _right.Remove(key, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } return result.IsEmpty ? result : MakeBalanced(result); } } /// <summary> /// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node /// with the described changes. /// </summary> /// <param name="left">The left branch of the mutated node.</param> /// <param name="right">The right branch of the mutated node.</param> /// <returns>The mutated (or created) node.</returns> private SortedInt32KeyNode<TValue> Mutate(SortedInt32KeyNode<TValue> left = null, SortedInt32KeyNode<TValue> right = null) { if (_frozen) { return new SortedInt32KeyNode<TValue>(_key, _value, left ?? _left, right ?? _right); } else { if (left != null) { _left = left; } if (right != null) { _right = right; } _height = checked((byte)(1 + Math.Max(_left._height, _right._height))); return this; } } /// <summary> /// Searches the specified key. Callers are expected to validate arguments. /// </summary> /// <param name="key">The key.</param> [Pure] private SortedInt32KeyNode<TValue> Search(int key) { if (this.IsEmpty || key == _key) { return this; } if (key > _key) { return _right.Search(key); } return _left.Search(key); } } }
// Deflater.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // 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. using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This is the Deflater class. The deflater class compresses input /// with the deflate algorithm described in RFC 1951. It has several /// compression levels and three different strategies described below. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of deflate and setInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> public class Deflater { #region Deflater Documentation /* * The Deflater can do the following state transitions: * * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---. * / | (2) (5) | * / v (5) | * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3) * \ | (3) | ,--------' * | | | (3) / * v v (5) v v * (1) -> BUSY_STATE ----> FINISHING_STATE * | (6) * v * FINISHED_STATE * \_____________________________________/ * | (7) * v * CLOSED_STATE * * (1) If we should produce a header we start in INIT_STATE, otherwise * we start in BUSY_STATE. * (2) A dictionary may be set only when we are in INIT_STATE, then * we change the state as indicated. * (3) Whether a dictionary is set or not, on the first call of deflate * we change to BUSY_STATE. * (4) -- intentionally left blank -- :) * (5) FINISHING_STATE is entered, when flush() is called to indicate that * there is no more INPUT. There are also states indicating, that * the header wasn't written yet. * (6) FINISHED_STATE is entered, when everything has been flushed to the * internal pending output buffer. * (7) At any time (7) * */ #endregion #region Public Constants /// <summary> /// The best and slowest compression level. This tries to find very /// long and distant string repetitions. /// </summary> public const int BEST_COMPRESSION = 9; /// <summary> /// The worst but fastest compression level. /// </summary> public const int BEST_SPEED = 1; /// <summary> /// The default compression level. /// </summary> public const int DEFAULT_COMPRESSION = -1; /// <summary> /// This level won't compress at all but output uncompressed blocks. /// </summary> public const int NO_COMPRESSION = 0; /// <summary> /// The compression method. This is the only method supported so far. /// There is no need to use this constant at all. /// </summary> public const int DEFLATED = 8; #endregion #region Local Constants private const int IS_SETDICT = 0x01; private const int IS_FLUSHING = 0x04; private const int IS_FINISHING = 0x08; private const int INIT_STATE = 0x00; private const int SETDICT_STATE = 0x01; // private static int INIT_FINISHING_STATE = 0x08; // private static int SETDICT_FINISHING_STATE = 0x09; private const int BUSY_STATE = 0x10; private const int FLUSHING_STATE = 0x14; private const int FINISHING_STATE = 0x1c; private const int FINISHED_STATE = 0x1e; private const int CLOSED_STATE = 0x7f; #endregion #region Constructors /// <summary> /// Creates a new deflater with default compression level. /// </summary> public Deflater() : this(DEFAULT_COMPRESSION, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level) : this(level, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION. /// </param> /// <param name="noZlibHeaderOrFooter"> /// true, if we should suppress the Zlib/RFC1950 header at the /// beginning and the adler checksum at the end of the output. This is /// useful for the GZIP/PKZIP formats. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level, bool noZlibHeaderOrFooter) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("level"); } pending = new DeflaterPending(); engine = new DeflaterEngine(pending); this.noZlibHeaderOrFooter = noZlibHeaderOrFooter; SetStrategy(DeflateStrategy.Default); SetLevel(level); Reset(); } #endregion /// <summary> /// Resets the deflater. The deflater acts afterwards as if it was /// just created with the same compression level and strategy as it /// had before. /// </summary> public void Reset() { state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE); totalOut = 0; pending.Reset(); engine.Reset(); } /// <summary> /// Gets the current adler checksum of the data that was processed so far. /// </summary> public int Adler { get { return engine.Adler; } } /// <summary> /// Gets the number of input bytes processed so far. /// </summary> public int TotalIn { get { return engine.TotalIn; } } /// <summary> /// Gets the number of output bytes so far. /// </summary> public long TotalOut { get { return totalOut; } } /// <summary> /// Flushes the current input block. Further calls to deflate() will /// produce enough output to inflate everything in the current input /// block. This is not part of Sun's JDK so I have made it package /// private. It is used by DeflaterOutputStream to implement /// flush(). /// </summary> public void Flush() { state |= IS_FLUSHING; } /// <summary> /// Finishes the deflater with the current input block. It is an error /// to give more input after this method was called. This method must /// be called to force all bytes to be flushed. /// </summary> public void Finish() { state |= (IS_FLUSHING | IS_FINISHING); } /// <summary> /// Returns true if the stream was finished and no more output bytes /// are available. /// </summary> public bool IsFinished { get { return (state == FINISHED_STATE) && pending.IsFlushed; } } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method can also return true when the stream /// was finished. /// </summary> public bool IsNeedingInput { get { return engine.NeedsInput(); } } /// <summary> /// Sets the data which should be compressed next. This should be only /// called when needsInput indicates that more input is needed. /// If you call setInput when needsInput() returns false, the /// previous input that is still pending will be thrown away. /// The given byte array should not be changed, before needsInput() returns /// true again. /// This call is equivalent to <code>setInput(input, 0, input.length)</code>. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was finished() or ended(). /// </exception> public void SetInput(byte[] input) { SetInput(input, 0, input.Length); } /// <summary> /// Sets the data which should be compressed next. This should be /// only called when needsInput indicates that more input is needed. /// The given byte array should not be changed, before needsInput() returns /// true again. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <param name="offset"> /// the start of the data. /// </param> /// <param name="count"> /// the number of data bytes of input. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was Finish()ed or if previous input is still pending. /// </exception> public void SetInput(byte[] input, int offset, int count) { if ((state & IS_FINISHING) != 0) { throw new InvalidOperationException("Finish() already called"); } engine.SetInput(input, offset, count); } /// <summary> /// Sets the compression level. There is no guarantee of the exact /// position of the change, but if you call this when needsInput is /// true the change of compression level will occur somewhere near /// before the end of the so far given input. /// </summary> /// <param name="level"> /// the new compression level. /// </param> public void SetLevel(int level) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("level"); } if (this.level != level) { this.level = level; engine.SetLevel(level); } } /// <summary> /// Get current compression level /// </summary> /// <returns>Returns the current compression level</returns> public int GetLevel() { return level; } /// <summary> /// Sets the compression strategy. Strategy is one of /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact /// position where the strategy is changed, the same as for /// SetLevel() applies. /// </summary> /// <param name="strategy"> /// The new compression strategy. /// </param> public void SetStrategy(DeflateStrategy strategy) { engine.Strategy = strategy; } /// <summary> /// Deflates the current input block with to the given array. /// </summary> /// <param name="output"> /// The buffer where compressed data is stored /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// IsNeedingInput() or IsFinished returns true or length is zero. /// </returns> public int Deflate(byte[] output) { return Deflate(output, 0, output.Length); } /// <summary> /// Deflates the current input block to the given array. /// </summary> /// <param name="output"> /// Buffer to store the compressed data. /// </param> /// <param name="offset"> /// Offset into the output array. /// </param> /// <param name="length"> /// The maximum number of bytes that may be stored. /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// needsInput() or finished() returns true or length is zero. /// </returns> /// <exception cref="System.InvalidOperationException"> /// If Finish() was previously called. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// If offset or length don't match the array length. /// </exception> public int Deflate(byte[] output, int offset, int length) { int origLength = length; if (state == CLOSED_STATE) { throw new InvalidOperationException("Deflater closed"); } if (state < BUSY_STATE) { // output header int header = (DEFLATED + ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8; int level_flags = (level - 1) >> 1; if (level_flags < 0 || level_flags > 3) { level_flags = 3; } header |= level_flags << 6; if ((state & IS_SETDICT) != 0) { // Dictionary was set header |= DeflaterConstants.PRESET_DICT; } header += 31 - (header % 31); pending.WriteShortMSB(header); if ((state & IS_SETDICT) != 0) { int chksum = engine.Adler; engine.ResetAdler(); pending.WriteShortMSB(chksum >> 16); pending.WriteShortMSB(chksum & 0xffff); } state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING)); } for (;;) { int count = pending.Flush(output, offset, length); offset += count; totalOut += count; length -= count; if (length == 0 || state == FINISHED_STATE) { break; } if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) { if (state == BUSY_STATE) { // We need more input now return origLength - length; } else if (state == FLUSHING_STATE) { if (level != NO_COMPRESSION) { /* We have to supply some lookahead. 8 bit lookahead * is needed by the zlib inflater, and we must fill * the next byte, so that all bits are flushed. */ int neededbits = 8 + ((-pending.BitCount) & 7); while (neededbits > 0) { /* write a static tree block consisting solely of * an EOF: */ pending.WriteBits(2, 10); neededbits -= 10; } } state = BUSY_STATE; } else if (state == FINISHING_STATE) { pending.AlignToByte(); // Compressed data is complete. Write footer information if required. if (!noZlibHeaderOrFooter) { int adler = engine.Adler; pending.WriteShortMSB(adler >> 16); pending.WriteShortMSB(adler & 0xffff); } state = FINISHED_STATE; } } } return origLength - length; } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>. /// </summary> /// <param name="dictionary"> /// the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// if SetInput () or Deflate () were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary) { SetDictionary(dictionary, 0, dictionary.Length); } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// The dictionary is a byte array containing strings that are /// likely to occur in the data which should be compressed. The /// dictionary is not stored in the compressed output, only a /// checksum. To decompress the output you need to supply the same /// dictionary again. /// </summary> /// <param name="dictionary"> /// The dictionary data /// </param> /// <param name="index"> /// The index where dictionary information commences. /// </param> /// <param name="count"> /// The number of bytes in the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// If SetInput () or Deflate() were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary, int index, int count) { if (state != INIT_STATE) { throw new InvalidOperationException(); } state = SETDICT_STATE; engine.SetDictionary(dictionary, index, count); } #region Instance Fields /// <summary> /// Compression level. /// </summary> int level; /// <summary> /// If true no Zlib/RFC1950 headers or footers are generated /// </summary> bool noZlibHeaderOrFooter; /// <summary> /// The current state. /// </summary> int state; /// <summary> /// The total bytes of output written. /// </summary> long totalOut; /// <summary> /// The pending output. /// </summary> DeflaterPending pending; /// <summary> /// The deflater engine. /// </summary> DeflaterEngine engine; #endregion } }
using WixSharp; using WixSharp.UI.Forms; namespace WixSharpSetup.Dialogs { partial class ExitDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.imgPanel = new System.Windows.Forms.Panel(); this.textPanel = new System.Windows.Forms.Panel(); this.title = new System.Windows.Forms.Label(); this.description = new System.Windows.Forms.Label(); this.image = new System.Windows.Forms.PictureBox(); this.bottomPanel = new System.Windows.Forms.Panel(); this.viewLog = new System.Windows.Forms.LinkLabel(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.back = new System.Windows.Forms.Button(); this.next = new System.Windows.Forms.Button(); this.cancel = new System.Windows.Forms.Button(); this.border1 = new System.Windows.Forms.Panel(); this.imgPanel.SuspendLayout(); this.textPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.image)).BeginInit(); this.bottomPanel.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // imgPanel // this.imgPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.imgPanel.Controls.Add(this.textPanel); this.imgPanel.Controls.Add(this.image); this.imgPanel.Location = new System.Drawing.Point(0, 0); this.imgPanel.Name = "imgPanel"; this.imgPanel.Size = new System.Drawing.Size(494, 312); this.imgPanel.TabIndex = 8; // // textPanel // this.textPanel.Controls.Add(this.title); this.textPanel.Controls.Add(this.description); this.textPanel.Location = new System.Drawing.Point(177, 17); this.textPanel.Name = "textPanel"; this.textPanel.Size = new System.Drawing.Size(305, 289); this.textPanel.TabIndex = 8; // // label1 // this.title.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.title.BackColor = System.Drawing.Color.Transparent; this.title.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.title.Location = new System.Drawing.Point(3, 0); this.title.Name = "label1"; this.title.Size = new System.Drawing.Size(299, 61); this.title.TabIndex = 6; this.title.Text = "[ExitDialogTitle]"; // // description // this.description.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.description.BackColor = System.Drawing.Color.Transparent; this.description.Location = new System.Drawing.Point(4, 88); this.description.Name = "description"; this.description.Size = new System.Drawing.Size(298, 201); this.description.TabIndex = 7; this.description.Text = "[ExitDialogDescription]"; // // image // this.image.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.image.Location = new System.Drawing.Point(0, 0); this.image.Name = "image"; this.image.Size = new System.Drawing.Size(156, 312); this.image.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.image.TabIndex = 4; this.image.TabStop = false; // // bottomPanel // this.bottomPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.bottomPanel.BackColor = System.Drawing.SystemColors.Control; this.bottomPanel.Controls.Add(this.viewLog); this.bottomPanel.Controls.Add(this.tableLayoutPanel1); this.bottomPanel.Controls.Add(this.border1); this.bottomPanel.Location = new System.Drawing.Point(0, 312); this.bottomPanel.Name = "bottomPanel"; this.bottomPanel.Size = new System.Drawing.Size(494, 49); this.bottomPanel.TabIndex = 5; // // viewLog // this.viewLog.Anchor = System.Windows.Forms.AnchorStyles.Left; this.viewLog.AutoSize = true; this.viewLog.BackColor = System.Drawing.Color.Transparent; this.viewLog.Location = new System.Drawing.Point(16, 17); this.viewLog.Name = "viewLog"; this.viewLog.Size = new System.Drawing.Size(54, 13); this.viewLog.TabIndex = 1; this.viewLog.TabStop = true; this.viewLog.Text = "[ViewLog]"; this.viewLog.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.viewLog_LinkClicked); // // tableLayoutPanel1 // this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel1.ColumnCount = 5; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 14F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this.back, 1, 0); this.tableLayoutPanel1.Controls.Add(this.next, 2, 0); this.tableLayoutPanel1.Controls.Add(this.cancel, 4, 0); this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 3); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 1; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(491, 43); this.tableLayoutPanel1.TabIndex = 7; // // back // this.back.Anchor = System.Windows.Forms.AnchorStyles.Right; this.back.AutoSize = true; this.back.Enabled = false; this.back.Location = new System.Drawing.Point(218, 10); this.back.MinimumSize = new System.Drawing.Size(75, 0); this.back.Name = "back"; this.back.Size = new System.Drawing.Size(77, 23); this.back.TabIndex = 0; this.back.Text = "[WixUIBack]"; this.back.UseVisualStyleBackColor = true; // // next // this.next.Anchor = System.Windows.Forms.AnchorStyles.Right; this.next.AutoSize = true; this.next.Location = new System.Drawing.Point(301, 10); this.next.MinimumSize = new System.Drawing.Size(75, 0); this.next.Name = "next"; this.next.Size = new System.Drawing.Size(81, 23); this.next.TabIndex = 0; this.next.Text = "[WixUIFinish]"; this.next.UseVisualStyleBackColor = true; this.next.Click += new System.EventHandler(this.finish_Click); // // cancel // this.cancel.Anchor = System.Windows.Forms.AnchorStyles.Right; this.cancel.AutoSize = true; this.cancel.Enabled = false; this.cancel.Location = new System.Drawing.Point(402, 10); this.cancel.MinimumSize = new System.Drawing.Size(75, 0); this.cancel.Name = "cancel"; this.cancel.Size = new System.Drawing.Size(86, 23); this.cancel.TabIndex = 0; this.cancel.Text = "[WixUICancel]"; this.cancel.UseVisualStyleBackColor = true; // // border1 // this.border1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.border1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.border1.Location = new System.Drawing.Point(0, 0); this.border1.Name = "border1"; this.border1.Size = new System.Drawing.Size(494, 1); this.border1.TabIndex = 9; // // ExitDialog // this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(494, 361); this.Controls.Add(this.imgPanel); this.Controls.Add(this.bottomPanel); this.Name = "ExitDialog"; this.Text = "[ExitDialog_Title]"; this.Load += new System.EventHandler(this.ExitDialog_Load); this.imgPanel.ResumeLayout(false); this.textPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.image)).EndInit(); this.bottomPanel.ResumeLayout(false); this.bottomPanel.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label description; private System.Windows.Forms.Label title; private System.Windows.Forms.Panel bottomPanel; private System.Windows.Forms.PictureBox image; private System.Windows.Forms.LinkLabel viewLog; private System.Windows.Forms.Panel imgPanel; private System.Windows.Forms.Panel border1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Button back; private System.Windows.Forms.Button next; private System.Windows.Forms.Button cancel; private System.Windows.Forms.Panel textPanel; } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using System.Text.RegularExpressions; using System.Xml.XPath; using OpenADK.Library; using OpenADK.Library.Infra; using OpenADK.Library.Tools.XPath; using OpenADK.Util; using OpenADK.Examples; namespace SIFQuery { public class SIFQuery : Agent, IQueryResults { private static readonly SIFQuery _agent = new SIFQuery(); private static IDictionary<string, ComparisonOperators> supportedComparisons = new Dictionary<string, ComparisonOperators>(); public SIFQuery() : base("SIFQuery") { } private static void InitializeComparisonList() { lock (supportedComparisons) { if (supportedComparisons.Count == 0) { supportedComparisons.Add("=", ComparisonOperators.EQ); supportedComparisons.Add(">", ComparisonOperators.GT); supportedComparisons.Add("<", ComparisonOperators.LT); supportedComparisons.Add(">=", ComparisonOperators.GE); supportedComparisons.Add("<=", ComparisonOperators.LE); supportedComparisons.Add("!=", ComparisonOperators.NE); } } } /// <summary> /// /// </summary> /// <param name="args"></param> [STAThread] public static void Main(string[] args) { try { if( args.Length < 2 ) { Console.WriteLine("Usage: SIFQuery /zone zone /url url [/events] [options]"); Console.WriteLine(" /zone zone The name of the zone"); Console.WriteLine(" /url url The zone URL"); AdkExamples.printHelp(); return; } // Pre-parse the command-line before initializing the ADK Adk.Debug = AdkDebugFlags.Moderate; AdkExamples.parseCL( null, args); // Initialize the ADK with the specified version, loading only the Student SDO package int sdoLibs; sdoLibs = (int)OpenADK.Library.us.SdoLibraryType.All; Adk.Initialize(SifVersion.SIF23,SIFVariant.SIF_US,sdoLibs); // Call StartAgent. _agent.StartAgent(args); // Turn down debugging Adk.Debug = AdkDebugFlags.None; // Call runConsole() This method does not return until the agent shuts down _agent.RunConsole(); // Wait for Ctrl-C to be pressed Console.WriteLine( "Agent is running (Press Ctrl-C to stop)" ); new AdkConsoleWait().WaitForExit(); } catch(Exception e) { Console.WriteLine(e); } finally { if( _agent != null && _agent.Initialized ){ // Always shutdown the agent on exit try { _agent.Shutdown( AdkExamples.Unreg ? ProvisioningFlags.Unprovide : ProvisioningFlags.None ); } catch( AdkException adkEx ){ Console.WriteLine( adkEx ); } } // set breakpoint here to prevent console from closing on errors Console.WriteLine(""); } } private void StartAgent(String[] args) { this.Initialize(); NameValueCollection parameters = AdkExamples.parseCL(this, args); string zoneId = parameters["zone"]; string url = parameters["url"]; if( zoneId == null || url == null ) { Console.WriteLine("The /zone and /url parameters are required"); Environment.Exit(0); } // only for SIF_Register and versions in SIF_Request messages... // this.Properties.OverrideSifVersions = "2.3,2.*"; // only for SIF_Message Version attribute in SIF_Request messages // this.Properties.OverrideSifMessageVersionForSifRequests = "2.3"; // 1) Get an instance of the zone to connect to IZone zone = ZoneFactory.GetInstance(zoneId, url); zone.SetQueryResults( this ); // 2) Connect to zones zone.Connect( AdkExamples.Reg ? ProvisioningFlags.Register : ProvisioningFlags.None ); } private void RunConsole() { Console.WriteLine( "SIFQuery Command Line" ); Version version = Assembly.GetExecutingAssembly().GetName().Version; Console.WriteLine( "Version " + version.ToString(3) ); Console.WriteLine( "Copyright " + DateTime.Now.Year + ", Data Solutions" ); PrintSQLHelp(); Regex sqlPattern = new Regex("(?:select)(.*)(?:from)(.*)(?:where)(.*)$", RegexOptions.IgnoreCase); bool finished = false; while( !finished ){ PrintPrompt(); string query = Console.ReadLine().Trim(); if( query.Length == 0 ){ continue; } string lcaseQuery = query.ToLower(); if( lcaseQuery.StartsWith("q")){ finished = true; continue; } if( lcaseQuery.IndexOf("where") == -1 ){ // The regular expression requires a where clause query = query + " where "; } Match results; try { results = sqlPattern.Match(query); } catch( Exception ex ){ Console.WriteLine( "ERROR evaluating expression: " + ex ); continue; } if(results.Captures.Count == 0 ){ Console.WriteLine( "Unknown error evaluating expression." ); continue; } if( results.Groups.Count >= 3 ){ Query q = CreateQuery(results.Groups[2].Value); if( q != null && AddConditions( q, results.Groups[3].Value ) && AddSelectFields( q, results.Groups[1].Value ) ) { Console.WriteLine( "Sending Query to zone.... " ); string queryXML = q.ToXml(SifVersion.LATEST); Console.WriteLine( queryXML ); // Store the original source query in the userData property q.UserData = queryXML; this.ZoneFactory.GetAllZones()[0].Query(q); } } else { Console.WriteLine( "ERROR: Unrecognized query syntax..." ); PrintSQLHelp(); } } } private void PrintPrompt(){ Console.Write( "SIF: " ); } private void PrintSQLHelp(){ Console.WriteLine( "Syntax: Select {fields} From {SIF Object} [Where {field}={value}] " ); Console.WriteLine( " {fields} one or more field names, seperated by a comma" ); Console.WriteLine( " (may by empty or * )" ); Console.WriteLine( " {SIF Object} the name of a SIF Object that is provided in the zone" ); Console.WriteLine( " {field} a field name" ); Console.WriteLine( " {value} a value" ); Console.WriteLine( "Examples:" ); Console.WriteLine( "SIF: Select * from StudentPersonal" ); Console.WriteLine( "SIF: Select * from StudentPersonal where RefId=43203167CFF14D08BB9C8E3FD0F9EC3C" ); Console.WriteLine( "SIF: Select * from StudentPersonal where Name/FirstName=Amber" ); Console.WriteLine( "SIF: Select Name/FirstName, Name/LastName from StudentPersonal where Demographics/Gender=F" ); Console.WriteLine( "SIF: Select * from StudentSchoolEnrollment where RefId=43203167CFF14D08BB9C8E3FD0F9EC3C" ); Console.WriteLine(); } private Query CreateQuery( String fromClause ){ IElementDef queryDef = Adk.Dtd.LookupElementDef( fromClause.Trim() ); if( queryDef == null ){ Console.WriteLine( "ERROR: Unrecognized FROM statement: " + fromClause ); PrintSQLHelp(); return null; } else{ return new Query( queryDef ); } } private bool AddSelectFields(Query q, String selectClause ) { if( selectClause.Length == 0 || selectClause.IndexOf( "*" ) > -1 ){ return true; } string[] fields = selectClause.Split(new char[] { ',' }); foreach(string field in fields){ string val = field.Trim(); if( val.Length > 0 ){ IElementDef restriction = Adk.Dtd.LookupElementDefBySQP( q.ObjectType, val ); if( restriction == null ){ Console.WriteLine( "ERROR: Unrecognized SELECT field: " + val ); PrintSQLHelp(); return false; } else { q.AddFieldRestriction(restriction); } } } return true; } private bool AddConditions(Query q, String whereClause ) { InitializeComparisonList(); bool added = true; whereClause = whereClause.Trim(); if( whereClause.Length == 0 ){ return added; } string[] whereConditions = Regex.Split(whereClause, "[aA][nN][dD]"); ComparisonOperators cmpOperator = ComparisonOperators.EQ; string[] fields = null; if (whereConditions.Length > 0) { foreach (String condition in whereConditions) { fields = null; foreach (KeyValuePair<string, ComparisonOperators> kvp in supportedComparisons) { string cmpString = kvp.Key; cmpOperator = kvp.Value; if (cmpOperator == ComparisonOperators.EQ) { int index = condition.LastIndexOf(cmpString); fields = new string[2]; if (index > 0) { fields[0] = condition.Substring(0, index); fields[1] = condition.Substring((index + 1)); } else { fields[0] = condition; } }//end if if (fields == null) { fields = Regex.Split(condition, cmpString); } if (fields[0] == condition) { //Means no match found using that current comparison operator //so skip this condition fields = null; continue; } if (fields.Length != 2) { Console.WriteLine("ERROR: Unsupported where clause: " + whereClause); PrintSQLHelp(); added = false; break; } string fieldExpr = fields[0].Trim(); IElementDef def = Adk.Dtd.LookupElementDefBySQP(q.ObjectType, fieldExpr ); if (def == null) { Console.WriteLine("ERROR: Unrecognized field in where clause: " + fieldExpr ); PrintSQLHelp(); added = false; break; } else { if (fieldExpr.IndexOf('[') > 0) { // If there is a square bracket in the field syntax, use the raw XPath, // rather then the ElementDef because using ElementDef restrictions // does not work for XPath expressions that contain predicates // Note that using raw XPath expressions works fine, but the ADK is no longer // going to be able to use version-independent rendering of the query q.AddCondition(fieldExpr, cmpOperator, fields[1].Trim()); } else { q.AddCondition( def, cmpOperator, fields[1].Trim() ); } //our condition has been found, no need to check the other comparison //operators for a match so move to the next condition break; } }//end foreach }//end foreach } return added; } public void OnQueryPending(IMessageInfo info, IZone zone){ SifMessageInfo smi = (SifMessageInfo)info; Console.WriteLine( "Sending SIF Request with MsgId " + smi.MsgId + " to zone " + zone.ZoneId ); } public void OnQueryResults(IDataObjectInputStream data, SIF_Error error, IZone zone, IMessageInfo info) { SifMessageInfo smi = (SifMessageInfo)info; DateTime start = DateTime.Now; if (smi.Timestamp.HasValue) { start = smi.Timestamp.Value; } Console.WriteLine(); Console.WriteLine( "********************************************* " ); Console.WriteLine( "Received SIF_Response packet from zone" + zone.ZoneId ); Console.WriteLine( "Details... " ); Console.WriteLine( "Request MsgId: " + smi.SIFRequestMsgId ); Console.WriteLine( "Packet Number: " + smi.PacketNumber ); Console.WriteLine(); if( error != null ){ Console.WriteLine( "The publisher returned an error: " ); Console.WriteLine( "Category: " + error.SIF_Category + " Code: " + error.SIF_Code ); Console.WriteLine( "Description " + error.SIF_Desc ); if( error.SIF_ExtendedDesc != null ) { Console.WriteLine( "Details: " + error.SIF_ExtendedDesc ); } return; } try { int objectCount = 0; while( data.Available ){ SifDataObject next = data.ReadDataObject(); objectCount++; Console.WriteLine(); Console.WriteLine( "Text Values for " + next.ElementDef.Name + " " + objectCount + " {" + next.Key + "}" ); SifXPathContext context = SifXPathContext.NewSIFContext(next); // Print out all attributes Console.WriteLine("Attributes:"); XPathNodeIterator textNodes = context.Select("//@*"); while( textNodes.MoveNext() ) { XPathNavigator navigator = textNodes.Current; Element value = (Element)navigator.UnderlyingObject; IElementDef valueDef = value.ElementDef; Console.WriteLine( valueDef.Parent.Tag( SifVersion.LATEST ) + "/@" + valueDef.Tag( SifVersion.LATEST ) + "=" + value.TextValue + ", " ); } Console.WriteLine(); // Print out all elements that have a text value Console.WriteLine("Element:"); textNodes = context.Select("//*"); while( textNodes.MoveNext() ) { XPathNavigator navigator = textNodes.Current; Element value = (Element)navigator.UnderlyingObject; String textValue = value.TextValue; if( textValue != null ){ IElementDef valueDef = value.ElementDef; Console.WriteLine( valueDef.Tag( SifVersion.LATEST ) + "=" + textValue + ", " ); } } } Console.WriteLine(); Console.WriteLine( "Total Objects in Packet: " + objectCount ); } catch( Exception ex ){ Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } if (!smi.MorePackets) { // This is the final packet. Print stats Console.WriteLine( "Final Packet has been received." ); IRequestInfo ri = smi.SIFRequestInfo; if( ri != null ){ Console.WriteLine( "Source Query: " ); Console.WriteLine( ri.UserData ); TimeSpan difference = start.Subtract(ri.RequestTime); Console.WriteLine( "Query execution time: " + difference.Milliseconds + " ms" ); } } else { Console.WriteLine( "This is not the final packet for this SIF_Response" ); } Console.WriteLine( "********************************************* " ); Console.WriteLine( ); PrintPrompt(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Net; using System.Reflection; using System.Text; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Voxels; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.World.Archiver { /// <summary> /// Handles an individual archive read request /// </summary> public class ArchiveReadRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The maximum major version of OAR that we can read. Minor versions shouldn't need a max number since version /// bumps here should be compatible. /// </summary> public static int MAX_MAJOR_VERSION = 0; protected Scene m_scene; protected Stream m_loadStream; protected Guid m_requestId; protected string m_errorMessage; /// <value> /// Should the archive being loaded be merged with what is already on the region? /// </value> protected bool m_merge; /// <value> /// Should we ignore any assets when reloading the archive? /// </value> protected bool m_skipAssets; /// <summary> /// Used to cache lookups for valid uuids. /// </summary> private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>(); public ArchiveReadRequest(Scene scene, string loadPath, bool merge, bool skipAssets, Guid requestId) { m_scene = scene; try { m_loadStream = new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); } m_errorMessage = String.Empty; m_merge = merge; m_skipAssets = skipAssets; m_requestId = requestId; } public ArchiveReadRequest(Scene scene, Stream loadStream, bool merge, bool skipAssets, Guid requestId) { m_scene = scene; m_loadStream = loadStream; m_merge = merge; m_skipAssets = skipAssets; m_requestId = requestId; } /// <summary> /// Dearchive the region embodied in this request. /// </summary> public void DearchiveRegion() { // The same code can handle dearchiving 0.1 and 0.2 OpenSim Archive versions DearchiveRegion0DotStar(); } private void DearchiveRegion0DotStar() { int successfulAssetRestores = 0; int failedAssetRestores = 0; List<string> serialisedSceneObjects = new List<string>(); List<string> serialisedParcels = new List<string>(); string filePath = "NONE"; TarArchiveReader archive = new TarArchiveReader(m_loadStream); byte[] data; TarArchiveReader.TarEntryType entryType; try { while ((data = archive.ReadEntry(out filePath, out entryType)) != null) { //m_log.DebugFormat( // "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length); if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType) continue; if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) { serialisedSceneObjects.Add(Encoding.UTF8.GetString(data)); } else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets) { if (LoadAsset(filePath, data)) successfulAssetRestores++; else failedAssetRestores++; if ((successfulAssetRestores + failedAssetRestores) % 250 == 0) m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets..."); } else if (!m_merge && filePath.StartsWith(ArchiveConstants.TERRAINS_PATH)) { LoadTerrain(filePath, data); } else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH)) { LoadRegionSettings(filePath, data); } else if (!m_merge && filePath.StartsWith(ArchiveConstants.LANDDATA_PATH)) { serialisedParcels.Add(Encoding.UTF8.GetString(data)); } else if (filePath == ArchiveConstants.CONTROL_FILE_PATH) { LoadControlFile(filePath, data); } } //m_log.Debug("[ARCHIVER]: Reached end of archive"); } catch (Exception e) { m_log.ErrorFormat( "[ARCHIVER]: Aborting load with error in archive file {0}. {1}", filePath, e); m_errorMessage += e.ToString(); m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage); return; } finally { archive.Close(); } if (!m_skipAssets) { m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores); if (failedAssetRestores > 0) { m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores); m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores); } } if (!m_merge) { m_log.Info("[ARCHIVER]: Clearing all existing scene objects"); m_scene.DeleteAllSceneObjects(); } // Try to retain the original creator/owner/lastowner if their uuid is present on this grid // otherwise, use the master avatar uuid instead // Reload serialized parcels m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count); List<LandData> landData = new List<LandData>(); foreach (string serialisedParcel in serialisedParcels) { LandData parcel = LandDataSerializer.Deserialize(serialisedParcel); if (!ResolveUserUuid(parcel.OwnerID)) parcel.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner; landData.Add(parcel); } m_scene.EventManager.TriggerIncomingLandDataFromStorage(landData); m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count); // Reload serialized prims m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count); IRegionSerialiserModule serialiser = m_scene.RequestModuleInterface<IRegionSerialiserModule>(); int sceneObjectsLoadedCount = 0; foreach (string serialisedSceneObject in serialisedSceneObjects) { /* m_log.DebugFormat("[ARCHIVER]: Loading xml with raw size {0}", serialisedSceneObject.Length); // Really large xml files (multi megabyte) appear to cause // memory problems // when loading the xml. But don't enable this check yet if (serialisedSceneObject.Length > 5000000) { m_log.Error("[ARCHIVER]: Ignoring xml since size > 5000000);"); continue; } */ SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject); // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned // on the same region server and multiple examples a single object archive to be imported // to the same scene (when this is possible). sceneObject.ResetIDs(); foreach (SceneObjectPart part in sceneObject.Parts) { if (!ResolveUserUuid(part.CreatorID)) part.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner; if (!ResolveUserUuid(part.OwnerID)) part.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner; if (!ResolveUserUuid(part.LastOwnerID)) part.LastOwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner; // And zap any troublesome sit target information part.SitTargetOrientation = new Quaternion(0, 0, 0, 1); part.SitTargetPosition = new Vector3(0, 0, 0); // Fix ownership/creator of inventory items // Not doing so results in inventory items // being no copy/no mod for everyone lock (part.TaskInventory) { TaskInventoryDictionary inv = part.TaskInventory; foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv) { if (!ResolveUserUuid(kvp.Value.OwnerID)) { kvp.Value.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner; } if (!ResolveUserUuid(kvp.Value.CreatorID)) { kvp.Value.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner; } } } } if (m_scene.AddRestoredSceneObject(sceneObject, true, false)) { sceneObjectsLoadedCount++; sceneObject.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, 0); sceneObject.ResumeScripts(); } } m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount); int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount; if (ignoredObjects > 0) m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects); m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive"); m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage); } /// <summary> /// Look up the given user id to check whether it's one that is valid for this grid. /// </summary> /// <param name="uuid"></param> /// <returns></returns> private bool ResolveUserUuid(UUID uuid) { if (!m_validUserUuids.ContainsKey(uuid)) { UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid); if (account != null) m_validUserUuids.Add(uuid, true); else m_validUserUuids.Add(uuid, false); } if (m_validUserUuids[uuid]) return true; else return false; } /// <summary> /// Load an asset /// </summary> /// <param name="assetFilename"></param> /// <param name="data"></param> /// <returns>true if asset was successfully loaded, false otherwise</returns> private bool LoadAsset(string assetPath, byte[] data) { // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR); if (i == -1) { m_log.ErrorFormat( "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR); return false; } string extension = filename.Substring(i); string uuid = filename.Remove(filename.Length - extension.Length); if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension)) { sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension]; if (assetType == (sbyte)AssetType.Unknown) m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid); //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString()); asset.Data = data; // We're relying on the asset service to do the sensible thing and not store the asset if it already // exists. m_scene.AssetService.Store(asset); /** * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so * it might be best done when dearchive takes place on a separate thread if (asset.Type=AssetType.Texture) { IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>(); if (cacheLayerDecode != null) cacheLayerDecode.syncdecode(asset.FullID, asset.Data); } */ return true; } else { m_log.ErrorFormat( "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}", assetPath, extension); return false; } } /// <summary> /// Load region settings data /// </summary> /// <param name="settingsPath"></param> /// <param name="data"></param> /// <returns> /// true if settings were loaded successfully, false otherwise /// </returns> private bool LoadRegionSettings(string settingsPath, byte[] data) { RegionSettings loadedRegionSettings; try { loadedRegionSettings = RegionSettingsSerializer.Deserialize(data); } catch (Exception e) { m_log.ErrorFormat( "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}", settingsPath, e); return false; } RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings; currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit; currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage; currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide; currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell; currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly; currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch; currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform; currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions; currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics; currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts; currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE; currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW; currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE; currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW; currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE; currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW; currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE; currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW; currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun; currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus; currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing; currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit; currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit; currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1; currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2; currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3; currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4; currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun; currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight; currentRegionSettings.Save(); IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>(); if (estateModule != null) estateModule.sendRegionHandshakeToAll(); return true; } /// <summary> /// Load terrain data /// </summary> /// <param name="terrainPath"></param> /// <param name="data"></param> /// <returns> /// true if terrain was resolved successfully, false otherwise. /// </returns> private bool LoadTerrain(string terrainPath, byte[] data) { ITerrainModule terrainModule = m_scene.RequestModuleInterface<ITerrainModule>(); MemoryStream ms = new MemoryStream(data); terrainModule.LoadFromStream(terrainPath, ms); ms.Close(); m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath); return true; } /// <summary> /// Load oar control file /// </summary> /// <param name="path"></param> /// <param name="data"></param> protected void LoadControlFile(string path, byte[] data) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None); XmlTextReader xtr = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context); RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings; // Loaded metadata will empty if no information exists in the archive currentRegionSettings.LoadedCreationDateTime = 0; currentRegionSettings.LoadedCreationID = ""; while (xtr.Read()) { if (xtr.NodeType == XmlNodeType.Element) { if (xtr.Name.ToString() == "archive") { int majorVersion = int.Parse(xtr["major_version"]); int minorVersion = int.Parse(xtr["minor_version"]); string version = string.Format("{0}.{1}", majorVersion, minorVersion); if (majorVersion > MAX_MAJOR_VERSION) { throw new Exception( string.Format( "The OAR you are trying to load has major version number of {0} but this version of OpenSim can only load OARs with major version number {1} and below", majorVersion, MAX_MAJOR_VERSION)); } m_log.InfoFormat("[ARCHIVER]: Loading OAR with version {0}", version); } if (xtr.Name.ToString() == "datetime") { int value; if (Int32.TryParse(xtr.ReadElementContentAsString(), out value)) currentRegionSettings.LoadedCreationDateTime = value; } else if (xtr.Name.ToString() == "id") { currentRegionSettings.LoadedCreationID = xtr.ReadElementContentAsString(); } } } currentRegionSettings.Save(); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.PythonTools.Editor; using Microsoft.PythonTools.Editor.Core; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.PythonTools.Intellisense { class ExpansionClient : IVsExpansionClient { private readonly PythonEditorServices _services; private readonly IVsTextLines _lines; private readonly IVsExpansion _expansion; private readonly IVsTextView _view; private readonly ITextView _textView; private IVsExpansionSession _session; private bool _sessionEnded, _selectEndSpan; private ITrackingPoint _selectionStart, _selectionEnd; public const string SurroundsWith = "SurroundsWith"; public const string SurroundsWithStatement = "SurroundsWithStatement"; public const string Expansion = "Expansion"; public ExpansionClient(ITextView textView, PythonEditorServices services) { _textView = textView; _services = services; _view = _services.EditorAdaptersFactoryService.GetViewAdapter(_textView); _lines = (IVsTextLines)_services.EditorAdaptersFactoryService.GetBufferAdapter(_textView.TextBuffer); _expansion = _lines as IVsExpansion; if (_expansion == null) { throw new ArgumentException("TextBuffer does not support expansions"); } } public bool InSession { get { return _session != null; } } public int EndExpansion() { _session = null; _sessionEnded = true; _selectionStart = _selectionEnd = null; return VSConstants.S_OK; } private static int TryGetXmlNodes(IVsExpansionSession session, out XElement header, out XElement snippet) { MSXML.IXMLDOMNode headerNode, snippetNode; int hr; header = null; snippet = null; if (ErrorHandler.Failed(hr = session.GetHeaderNode(null, out headerNode))) { return hr; } if (ErrorHandler.Failed(hr = session.GetSnippetNode(null, out snippetNode))) { return hr; } header = XElement.Parse(headerNode.xml); snippet = XElement.Parse(snippetNode.xml); return VSConstants.S_OK; } public int FormatSpan(IVsTextLines pBuffer, TextSpan[] ts) { XElement header, snippet; int hr = TryGetXmlNodes(_session, out header, out snippet); if (ErrorHandler.Failed(hr)) { return hr; } var ns = header.Name.NamespaceName; bool surroundsWith = header .Elements(XName.Get("SnippetTypes", ns)) .Elements(XName.Get("SnippetType", ns)) .Any(n => n.Value == SurroundsWith); bool surroundsWithStatement = header .Elements(XName.Get("SnippetTypes", ns)) .Elements(XName.Get("SnippetType", ns)) .Any(n => n.Value == SurroundsWithStatement); ns = snippet.Name.NamespaceName; var declList = snippet .Element(XName.Get("Declarations", ns))? .Elements() .Elements(XName.Get("ID", ns)) .Select(n => n.Value) .Where(n => !string.IsNullOrEmpty(n)) .ToList() ?? new List<string>(); var importList = snippet .Element(XName.Get("Imports", ns))? .Elements(XName.Get("Import", ns)) .Elements(XName.Get("Namespace", ns)) .Select(n => n.Value) .Where(n => !string.IsNullOrEmpty(n)) .ToList() ?? new List<string>(); var codeText = snippet .Element(XName.Get("Code", ns))? .Value ?? string.Empty; // get the indentation of where we're inserting the code... string baseIndentation = GetBaseIndentation(ts); int startPosition; pBuffer.GetPositionOfLineIndex(ts[0].iStartLine, ts[0].iStartIndex, out startPosition); var insertTrackingPoint = _textView.TextBuffer.CurrentSnapshot.CreateTrackingPoint(startPosition, PointTrackingMode.Positive); TextSpan? endSpan = null; using (var edit = _textView.TextBuffer.CreateEdit()) { if (surroundsWith || surroundsWithStatement) { // this is super annoyning... Most languages can do a surround with and $selected$ can be // an empty string and everything's the same. But in Python we can't just have something like // "while True: " without a pass statement. So if we start off with an empty selection we // need to insert a pass statement. This is the purpose of the "SurroundsWithStatement" // snippet type. // // But, to make things even more complicated, we don't have a good indication of what's the // template text vs. what's the selected text. We do have access to the original template, // but all of the values have been replaced with their default values when we get called // here. So we need to go back and re-apply the template, except for the $selected$ part. // // Also, the text has \n, but the inserted text has been replaced with the appropriate newline // character for the buffer. var templateText = codeText.Replace("\n", _textView.Options.GetNewLineCharacter()); foreach (var decl in declList) { string defaultValue; if (ErrorHandler.Succeeded(_session.GetFieldValue(decl, out defaultValue))) { templateText = templateText.Replace("$" + decl + "$", defaultValue); } } templateText = templateText.Replace("$end$", ""); // we can finally figure out where the selected text began witin the original template... int selectedIndex = templateText.IndexOfOrdinal("$selected$", ignoreCase: true); if (selectedIndex != -1) { var selection = _textView.Selection; // now we need to get the indentation of the $selected$ element within the template, // as we'll need to indent the selected code to that level. string indentation = GetTemplateSelectionIndentation(templateText, selectedIndex); var start = _selectionStart.GetPosition(_textView.TextBuffer.CurrentSnapshot); var end = _selectionEnd.GetPosition(_textView.TextBuffer.CurrentSnapshot); if (end < start) { // we didn't actually have a selction, and our negative tracking pushed us // back to the start of the buffer... end = start; } var selectedSpan = Span.FromBounds(start, end); if (surroundsWithStatement && String.IsNullOrWhiteSpace(_textView.TextBuffer.CurrentSnapshot.GetText(selectedSpan))) { // we require a statement here and the user hasn't selected any code to surround, // so we insert a pass statement (and we'll select it after the completion is done) edit.Replace(new Span(startPosition + selectedIndex, end - start), "pass"); // Surround With can be invoked with no selection, but on a line with some text. // In that case we need to inject an extra new line. var endLine = _textView.TextBuffer.CurrentSnapshot.GetLineFromPosition(end); var endText = endLine.GetText().Substring(end - endLine.Start); if (!String.IsNullOrWhiteSpace(endText)) { edit.Insert(end, _textView.Options.GetNewLineCharacter()); } // we want to leave the pass statement selected so the user can just // continue typing over it... var startLine = _textView.TextBuffer.CurrentSnapshot.GetLineFromPosition(startPosition + selectedIndex); _selectEndSpan = true; endSpan = new TextSpan() { iStartLine = startLine.LineNumber, iEndLine = startLine.LineNumber, iStartIndex = baseIndentation.Length + indentation.Length, iEndIndex = baseIndentation.Length + indentation.Length + 4, }; } IndentSpan( edit, indentation, _textView.TextBuffer.CurrentSnapshot.GetLineFromPosition(start).LineNumber + 1, // 1st line is already indented _textView.TextBuffer.CurrentSnapshot.GetLineFromPosition(end).LineNumber ); } } // we now need to update any code which was not selected that we just inserted. IndentSpan(edit, baseIndentation, ts[0].iStartLine + 1, ts[0].iEndLine); edit.Apply(); } if (endSpan != null) { _session.SetEndSpan(endSpan.Value); } // add any missing imports... AddMissingImports( importList, insertTrackingPoint.GetPoint(_textView.TextBuffer.CurrentSnapshot) ); return hr; } private void AddMissingImports(List<string> importList, SnapshotPoint point) { if (importList.Count == 0) { return; } var bi = _services.GetBufferInfo(_textView.TextBuffer); var entry = bi?.AnalysisEntry; if (entry == null) { return; } SourceLocation loc; try { loc = point.ToSourceLocation(); } catch (ArgumentException ex) { Debug.Fail(ex.ToUnhandledExceptionMessage(GetType())); return; } foreach (var import in importList) { var isMissing = entry.Analyzer.WaitForRequest( entry.Analyzer.IsMissingImportAsync(entry, import, loc), "ExpansionClient.IsMissingImportAsync", false ); if (isMissing) { VsProjectAnalyzer.AddImport(_textView.TextBuffer, null, import); } } } private static string GetTemplateSelectionIndentation(string templateText, int selectedIndex) { string indentation = ""; for (int i = selectedIndex - 1; i >= 0; i--) { if (templateText[i] != '\t' && templateText[i] != ' ') { indentation = templateText.Substring(i + 1, selectedIndex - i - 1); break; } } return indentation; } private string GetBaseIndentation(TextSpan[] ts) { var indentationLine = _textView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(ts[0].iStartLine).GetText(); string baseIndentation = indentationLine; for (int i = 0; i < indentationLine.Length; i++) { if (indentationLine[i] != ' ' && indentationLine[i] != '\t') { baseIndentation = indentationLine.Substring(0, i); break; } } return baseIndentation; } private void IndentSpan(ITextEdit edit, string indentation, int startLine, int endLine) { var snapshot = _textView.TextBuffer.CurrentSnapshot; for (int i = startLine; i <= endLine; i++) { var curline = snapshot.GetLineFromLineNumber(i); edit.Insert(curline.Start, indentation); } } public int GetExpansionFunction(MSXML.IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction pFunc) { pFunc = null; return VSConstants.S_OK; } public int IsValidKind(IVsTextLines pBuffer, TextSpan[] ts, string bstrKind, out int pfIsValidKind) { pfIsValidKind = 1; return VSConstants.S_OK; } public int IsValidType(IVsTextLines pBuffer, TextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType) { pfIsValidType = 1; return VSConstants.S_OK; } public int OnAfterInsertion(IVsExpansionSession pSession) { return VSConstants.S_OK; } public int OnBeforeInsertion(IVsExpansionSession pSession) { _session = pSession; return VSConstants.S_OK; } public int OnItemChosen(string pszTitle, string pszPath) { int caretLine, caretColumn; GetCaretPosition(out caretLine, out caretColumn); var textSpan = new TextSpan() { iStartLine = caretLine, iStartIndex = caretColumn, iEndLine = caretLine, iEndIndex = caretColumn }; return InsertNamedExpansion(pszTitle, pszPath, textSpan); } public int InsertNamedExpansion(string pszTitle, string pszPath, TextSpan textSpan) { if (_session != null) { // if the user starts an expansion session while one is in progress // then abort the current expansion session _session.EndCurrentExpansion(1); _session = null; } var selection = _textView.Selection; var snapshot = selection.Start.Position.Snapshot; _selectionStart = snapshot.CreateTrackingPoint(selection.Start.Position, VisualStudio.Text.PointTrackingMode.Positive); _selectionEnd = snapshot.CreateTrackingPoint(selection.End.Position, VisualStudio.Text.PointTrackingMode.Negative); _selectEndSpan = _sessionEnded = false; int hr = _expansion.InsertNamedExpansion( pszTitle, pszPath, textSpan, this, GuidList.guidPythonLanguageServiceGuid, 0, out _session ); if (ErrorHandler.Succeeded(hr)) { if (_sessionEnded) { _session = null; } } return hr; } public int NextField() { return _session.GoToNextExpansionField(0); } public int PreviousField() { return _session.GoToPreviousExpansionField(); } public int EndCurrentExpansion(bool leaveCaret) { if (_selectEndSpan) { TextSpan[] endSpan = new TextSpan[1]; if (ErrorHandler.Succeeded(_session.GetEndSpan(endSpan))) { var snapshot = _textView.TextBuffer.CurrentSnapshot; var startLine = snapshot.GetLineFromLineNumber(endSpan[0].iStartLine); var span = new Span(startLine.Start + endSpan[0].iStartIndex, 4); _textView.Caret.MoveTo(new SnapshotPoint(snapshot, span.Start)); _textView.Selection.Select(new SnapshotSpan(_textView.TextBuffer.CurrentSnapshot, span), false); return _session.EndCurrentExpansion(1); } } return _session.EndCurrentExpansion(leaveCaret ? 1 : 0); } public int PositionCaretForEditing(IVsTextLines pBuffer, TextSpan[] ts) { return VSConstants.S_OK; } private void GetCaretPosition(out int caretLine, out int caretColumn) { ErrorHandler.ThrowOnFailure(_view.GetCaretPos(out caretLine, out caretColumn)); // Handle virtual space int lineLength; ErrorHandler.ThrowOnFailure(_lines.GetLengthOfLine(caretLine, out lineLength)); if (caretColumn > lineLength) { caretColumn = lineLength; } } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Contoso.Core.ModifyPagesWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// 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.IO.Pipelines; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http { using BadHttpRequestException = Microsoft.AspNetCore.Http.BadHttpRequestException; internal abstract class Http1MessageBody : MessageBody { protected readonly Http1Connection _context; private bool _readerCompleted; protected Http1MessageBody(Http1Connection context, bool keepAlive) : base(context) { _context = context; RequestKeepAlive = keepAlive; } public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default) { ThrowIfReaderCompleted(); return ReadAsyncInternal(cancellationToken); } public abstract ValueTask<ReadResult> ReadAsyncInternal(CancellationToken cancellationToken = default); public override bool TryRead(out ReadResult readResult) { ThrowIfReaderCompleted(); return TryReadInternal(out readResult); } public abstract bool TryReadInternal(out ReadResult readResult); public override void Complete(Exception? exception) { _readerCompleted = true; _context.ReportApplicationError(exception); } protected override Task OnConsumeAsync() { try { while (TryReadInternal(out var readResult)) { AdvanceTo(readResult.Buffer.End); if (readResult.IsCompleted) { return Task.CompletedTask; } } } catch (BadHttpRequestException ex) { // At this point, the response has already been written, so this won't result in a 4XX response; // however, we still need to stop the request processing loop and log. _context.SetBadRequestState(ex); return Task.CompletedTask; } catch (InvalidOperationException ex) { var connectionAbortedException = new ConnectionAbortedException(CoreStrings.ConnectionAbortedByApplication, ex); _context.ReportApplicationError(connectionAbortedException); // Have to abort the connection because we can't finish draining the request _context.StopProcessingNextRequest(); return Task.CompletedTask; } return OnConsumeAsyncAwaited(); } protected async Task OnConsumeAsyncAwaited() { Log.RequestBodyNotEntirelyRead(_context.ConnectionIdFeature, _context.TraceIdentifier); _context.TimeoutControl.SetTimeout(Constants.RequestBodyDrainTimeout.Ticks, TimeoutReason.RequestBodyDrain); try { ReadResult result; do { result = await ReadAsyncInternal(); AdvanceTo(result.Buffer.End); } while (!result.IsCompleted); } catch (BadHttpRequestException ex) { _context.SetBadRequestState(ex); } catch (OperationCanceledException ex) when (ex is ConnectionAbortedException || ex is TaskCanceledException) { Log.RequestBodyDrainTimedOut(_context.ConnectionIdFeature, _context.TraceIdentifier); } catch (InvalidOperationException ex) { var connectionAbortedException = new ConnectionAbortedException(CoreStrings.ConnectionAbortedByApplication, ex); _context.ReportApplicationError(connectionAbortedException); // Have to abort the connection because we can't finish draining the request _context.StopProcessingNextRequest(); } finally { _context.TimeoutControl.CancelTimeout(); } } public static MessageBody For( HttpVersion httpVersion, HttpRequestHeaders headers, Http1Connection context) { // see also http://tools.ietf.org/html/rfc2616#section-4.4 var keepAlive = httpVersion != HttpVersion.Http10; var upgrade = false; if (headers.HasConnection) { var connectionOptions = HttpHeaders.ParseConnection(headers); upgrade = (connectionOptions & ConnectionOptions.Upgrade) != 0; keepAlive = keepAlive || (connectionOptions & ConnectionOptions.KeepAlive) != 0; keepAlive = keepAlive && (connectionOptions & ConnectionOptions.Close) == 0; } // Ignore upgrades if the request has a body. Technically it's possible to support, but we'd have to add a lot // more logic to allow reading/draining the normal body before the connection could be fully upgraded. // See https://tools.ietf.org/html/rfc7230#section-6.7, https://tools.ietf.org/html/rfc7540#section-3.2 if (upgrade && headers.ContentLength.GetValueOrDefault() == 0 && headers.HeaderTransferEncoding.Count == 0) { context.OnTrailersComplete(); // No trailers for these. return new Http1UpgradeMessageBody(context, keepAlive); } if (headers.HasTransferEncoding) { var transferEncoding = headers.HeaderTransferEncoding; var transferCoding = HttpHeaders.GetFinalTransferCoding(transferEncoding); // https://tools.ietf.org/html/rfc7230#section-3.3.3 // If a Transfer-Encoding header field // is present in a request and the chunked transfer coding is not // the final encoding, the message body length cannot be determined // reliably; the server MUST respond with the 400 (Bad Request) // status code and then close the connection. if (transferCoding != TransferCoding.Chunked) { KestrelBadHttpRequestException.Throw(RequestRejectionReason.FinalTransferCodingNotChunked, transferEncoding); } // TODO may push more into the wrapper rather than just calling into the message body // NBD for now. return new Http1ChunkedEncodingMessageBody(context, keepAlive); } if (headers.ContentLength.HasValue) { var contentLength = headers.ContentLength.Value; if (contentLength == 0) { return keepAlive ? MessageBody.ZeroContentLengthKeepAlive : MessageBody.ZeroContentLengthClose; } return new Http1ContentLengthMessageBody(context, contentLength, keepAlive); } // If we got here, request contains no Content-Length or Transfer-Encoding header. // Reject with Length Required for HTTP 1.0. if (httpVersion == HttpVersion.Http10 && (context.Method == HttpMethod.Post || context.Method == HttpMethod.Put)) { KestrelBadHttpRequestException.Throw(RequestRejectionReason.LengthRequiredHttp10, context.Method); } context.OnTrailersComplete(); // No trailers for these. return keepAlive ? MessageBody.ZeroContentLengthKeepAlive : MessageBody.ZeroContentLengthClose; } [StackTraceHidden] protected void ThrowIfReaderCompleted() { if (_readerCompleted) { throw new InvalidOperationException("Reading is not allowed after the reader was completed."); } } [StackTraceHidden] protected void ThrowUnexpectedEndOfRequestContent() { // OnInputOrOutputCompleted() is an idempotent method that closes the connection. Sometimes // input completion is observed here before the Input.OnWriterCompleted() callback is fired, // so we call OnInputOrOutputCompleted() now to prevent a race in our tests where a 400 // response is written after observing the unexpected end of request content instead of just // closing the connection without a response as expected. _context.OnInputOrOutputCompleted(); KestrelBadHttpRequestException.Throw(RequestRejectionReason.UnexpectedEndOfRequestContent); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; using System.Threading; internal static partial class Interop { internal static partial class HttpApi { internal static readonly HTTPAPI_VERSION s_version = new HTTPAPI_VERSION() { HttpApiMajorVersion = 2, HttpApiMinorVersion = 0 }; internal static readonly bool s_supported = InitHttpApi(s_version); internal static IPEndPoint s_any = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort); internal static IPEndPoint s_ipv6Any = new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort); internal const int IPv4AddressSize = 16; internal const int IPv6AddressSize = 28; private static unsafe bool InitHttpApi(HTTPAPI_VERSION version) { uint statusCode = HttpInitialize(version, (uint)HTTP_FLAGS.HTTP_INITIALIZE_SERVER, null); return statusCode == ERROR_SUCCESS; } [StructLayout(LayoutKind.Sequential)] internal struct HTTP_VERSION { internal ushort MajorVersion; internal ushort MinorVersion; } internal enum HTTP_RESPONSE_INFO_TYPE { HttpResponseInfoTypeMultipleKnownHeaders, HttpResponseInfoTypeAuthenticationProperty, HttpResponseInfoTypeQosProperty, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_RESPONSE_INFO { internal HTTP_RESPONSE_INFO_TYPE Type; internal uint Length; internal void* pInfo; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_RESPONSE_HEADERS { internal ushort UnknownHeaderCount; internal HTTP_UNKNOWN_HEADER* pUnknownHeaders; internal ushort TrailerCount; internal HTTP_UNKNOWN_HEADER* pTrailers; internal HTTP_KNOWN_HEADER KnownHeaders; internal HTTP_KNOWN_HEADER KnownHeaders_02; internal HTTP_KNOWN_HEADER KnownHeaders_03; internal HTTP_KNOWN_HEADER KnownHeaders_04; internal HTTP_KNOWN_HEADER KnownHeaders_05; internal HTTP_KNOWN_HEADER KnownHeaders_06; internal HTTP_KNOWN_HEADER KnownHeaders_07; internal HTTP_KNOWN_HEADER KnownHeaders_08; internal HTTP_KNOWN_HEADER KnownHeaders_09; internal HTTP_KNOWN_HEADER KnownHeaders_10; internal HTTP_KNOWN_HEADER KnownHeaders_11; internal HTTP_KNOWN_HEADER KnownHeaders_12; internal HTTP_KNOWN_HEADER KnownHeaders_13; internal HTTP_KNOWN_HEADER KnownHeaders_14; internal HTTP_KNOWN_HEADER KnownHeaders_15; internal HTTP_KNOWN_HEADER KnownHeaders_16; internal HTTP_KNOWN_HEADER KnownHeaders_17; internal HTTP_KNOWN_HEADER KnownHeaders_18; internal HTTP_KNOWN_HEADER KnownHeaders_19; internal HTTP_KNOWN_HEADER KnownHeaders_20; internal HTTP_KNOWN_HEADER KnownHeaders_21; internal HTTP_KNOWN_HEADER KnownHeaders_22; internal HTTP_KNOWN_HEADER KnownHeaders_23; internal HTTP_KNOWN_HEADER KnownHeaders_24; internal HTTP_KNOWN_HEADER KnownHeaders_25; internal HTTP_KNOWN_HEADER KnownHeaders_26; internal HTTP_KNOWN_HEADER KnownHeaders_27; internal HTTP_KNOWN_HEADER KnownHeaders_28; internal HTTP_KNOWN_HEADER KnownHeaders_29; internal HTTP_KNOWN_HEADER KnownHeaders_30; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_KNOWN_HEADER { internal ushort RawValueLength; internal sbyte* pRawValue; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_UNKNOWN_HEADER { internal ushort NameLength; internal ushort RawValueLength; internal sbyte* pName; internal sbyte* pRawValue; } internal enum HTTP_DATA_CHUNK_TYPE : int { HttpDataChunkFromMemory = 0, HttpDataChunkFromFileHandle = 1, HttpDataChunkFromFragmentCache = 2, HttpDataChunkMaximum = 3, } [StructLayout(LayoutKind.Sequential, Size = 32)] internal unsafe struct HTTP_DATA_CHUNK { internal HTTP_DATA_CHUNK_TYPE DataChunkType; internal uint p0; internal byte* pBuffer; internal uint BufferLength; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_RESPONSE { internal uint Flags; internal HTTP_VERSION Version; internal ushort StatusCode; internal ushort ReasonLength; internal sbyte* pReason; internal HTTP_RESPONSE_HEADERS Headers; internal ushort EntityChunkCount; internal HTTP_DATA_CHUNK* pEntityChunks; internal ushort ResponseInfoCount; internal HTTP_RESPONSE_INFO* pResponseInfo; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_REQUEST_INFO { internal HTTP_REQUEST_INFO_TYPE InfoType; internal uint InfoLength; internal void* pInfo; } internal enum HTTP_REQUEST_INFO_TYPE { HttpRequestInfoTypeAuth, HttpRequestInfoTypeChannelBind, HttpRequestInfoTypeSslProtocol, HttpRequestInfoTypeSslTokenBinding } internal enum HTTP_VERB : int { HttpVerbUnparsed = 0, HttpVerbUnknown = 1, HttpVerbInvalid = 2, HttpVerbOPTIONS = 3, HttpVerbGET = 4, HttpVerbHEAD = 5, HttpVerbPOST = 6, HttpVerbPUT = 7, HttpVerbDELETE = 8, HttpVerbTRACE = 9, HttpVerbCONNECT = 10, HttpVerbTRACK = 11, HttpVerbMOVE = 12, HttpVerbCOPY = 13, HttpVerbPROPFIND = 14, HttpVerbPROPPATCH = 15, HttpVerbMKCOL = 16, HttpVerbLOCK = 17, HttpVerbUNLOCK = 18, HttpVerbSEARCH = 19, HttpVerbMaximum = 20, } [StructLayout(LayoutKind.Sequential)] internal struct SOCKADDR { internal ushort sa_family; internal byte sa_data; internal byte sa_data_02; internal byte sa_data_03; internal byte sa_data_04; internal byte sa_data_05; internal byte sa_data_06; internal byte sa_data_07; internal byte sa_data_08; internal byte sa_data_09; internal byte sa_data_10; internal byte sa_data_11; internal byte sa_data_12; internal byte sa_data_13; internal byte sa_data_14; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_TRANSPORT_ADDRESS { internal SOCKADDR* pRemoteAddress; internal SOCKADDR* pLocalAddress; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_REQUEST_HEADERS { internal ushort UnknownHeaderCount; internal HTTP_UNKNOWN_HEADER* pUnknownHeaders; internal ushort TrailerCount; internal HTTP_UNKNOWN_HEADER* pTrailers; internal HTTP_KNOWN_HEADER KnownHeaders; internal HTTP_KNOWN_HEADER KnownHeaders_02; internal HTTP_KNOWN_HEADER KnownHeaders_03; internal HTTP_KNOWN_HEADER KnownHeaders_04; internal HTTP_KNOWN_HEADER KnownHeaders_05; internal HTTP_KNOWN_HEADER KnownHeaders_06; internal HTTP_KNOWN_HEADER KnownHeaders_07; internal HTTP_KNOWN_HEADER KnownHeaders_08; internal HTTP_KNOWN_HEADER KnownHeaders_09; internal HTTP_KNOWN_HEADER KnownHeaders_10; internal HTTP_KNOWN_HEADER KnownHeaders_11; internal HTTP_KNOWN_HEADER KnownHeaders_12; internal HTTP_KNOWN_HEADER KnownHeaders_13; internal HTTP_KNOWN_HEADER KnownHeaders_14; internal HTTP_KNOWN_HEADER KnownHeaders_15; internal HTTP_KNOWN_HEADER KnownHeaders_16; internal HTTP_KNOWN_HEADER KnownHeaders_17; internal HTTP_KNOWN_HEADER KnownHeaders_18; internal HTTP_KNOWN_HEADER KnownHeaders_19; internal HTTP_KNOWN_HEADER KnownHeaders_20; internal HTTP_KNOWN_HEADER KnownHeaders_21; internal HTTP_KNOWN_HEADER KnownHeaders_22; internal HTTP_KNOWN_HEADER KnownHeaders_23; internal HTTP_KNOWN_HEADER KnownHeaders_24; internal HTTP_KNOWN_HEADER KnownHeaders_25; internal HTTP_KNOWN_HEADER KnownHeaders_26; internal HTTP_KNOWN_HEADER KnownHeaders_27; internal HTTP_KNOWN_HEADER KnownHeaders_28; internal HTTP_KNOWN_HEADER KnownHeaders_29; internal HTTP_KNOWN_HEADER KnownHeaders_30; internal HTTP_KNOWN_HEADER KnownHeaders_31; internal HTTP_KNOWN_HEADER KnownHeaders_32; internal HTTP_KNOWN_HEADER KnownHeaders_33; internal HTTP_KNOWN_HEADER KnownHeaders_34; internal HTTP_KNOWN_HEADER KnownHeaders_35; internal HTTP_KNOWN_HEADER KnownHeaders_36; internal HTTP_KNOWN_HEADER KnownHeaders_37; internal HTTP_KNOWN_HEADER KnownHeaders_38; internal HTTP_KNOWN_HEADER KnownHeaders_39; internal HTTP_KNOWN_HEADER KnownHeaders_40; internal HTTP_KNOWN_HEADER KnownHeaders_41; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_SSL_CLIENT_CERT_INFO { internal uint CertFlags; internal uint CertEncodedSize; internal byte* pCertEncoded; internal void* Token; internal byte CertDeniedByMapper; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_SSL_INFO { internal ushort ServerCertKeySize; internal ushort ConnectionKeySize; internal uint ServerCertIssuerSize; internal uint ServerCertSubjectSize; internal sbyte* pServerCertIssuer; internal sbyte* pServerCertSubject; internal HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo; internal uint SslClientCertNegotiated; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_REQUEST { internal uint Flags; internal ulong ConnectionId; internal ulong RequestId; internal ulong UrlContext; internal HTTP_VERSION Version; internal HTTP_VERB Verb; internal ushort UnknownVerbLength; internal ushort RawUrlLength; internal sbyte* pUnknownVerb; internal sbyte* pRawUrl; internal HTTP_COOKED_URL CookedUrl; internal HTTP_TRANSPORT_ADDRESS Address; internal HTTP_REQUEST_HEADERS Headers; internal ulong BytesReceived; internal ushort EntityChunkCount; internal HTTP_DATA_CHUNK* pEntityChunks; internal ulong RawConnectionId; internal HTTP_SSL_INFO* pSslInfo; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_REQUEST_V2 { internal HTTP_REQUEST RequestV1; internal ushort RequestInfoCount; internal HTTP_REQUEST_INFO* pRequestInfo; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_COOKED_URL { internal ushort FullUrlLength; internal ushort HostLength; internal ushort AbsPathLength; internal ushort QueryStringLength; internal ushort* pFullUrl; internal ushort* pHost; internal ushort* pAbsPath; internal ushort* pQueryString; } [StructLayout(LayoutKind.Sequential)] internal struct HTTP_REQUEST_CHANNEL_BIND_STATUS { internal IntPtr ServiceName; internal IntPtr ChannelToken; internal uint ChannelTokenSize; internal uint Flags; } internal enum HTTP_SERVER_PROPERTY { HttpServerAuthenticationProperty, HttpServerLoggingProperty, HttpServerQosProperty, HttpServerTimeoutsProperty, HttpServerQueueLengthProperty, HttpServerStateProperty, HttpServer503VerbosityProperty, HttpServerBindingProperty, HttpServerExtendedAuthenticationProperty, HttpServerListenEndpointProperty, HttpServerChannelBindProperty, HttpServerProtectionLevelProperty, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct HTTP_REQUEST_TOKEN_BINDING_INFO { public byte* TokenBinding; public uint TokenBindingSize; public byte* TlsUnique; public uint TlsUniqueSize; public IntPtr KeyType; } internal enum TOKENBINDING_HASH_ALGORITHM : byte { TOKENBINDING_HASH_ALGORITHM_SHA256 = 4, } internal enum TOKENBINDING_SIGNATURE_ALGORITHM : byte { TOKENBINDING_SIGNATURE_ALGORITHM_RSA = 1, TOKENBINDING_SIGNATURE_ALGORITHM_ECDSAP256 = 3, } internal enum TOKENBINDING_TYPE : byte { TOKENBINDING_TYPE_PROVIDED = 0, TOKENBINDING_TYPE_REFERRED = 1, } internal enum TOKENBINDING_EXTENSION_FORMAT { TOKENBINDING_EXTENSION_FORMAT_UNDEFINED = 0, } [StructLayout(LayoutKind.Sequential)] internal struct TOKENBINDING_IDENTIFIER { public TOKENBINDING_TYPE bindingType; public TOKENBINDING_HASH_ALGORITHM hashAlgorithm; public TOKENBINDING_SIGNATURE_ALGORITHM signatureAlgorithm; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct TOKENBINDING_RESULT_DATA { public uint identifierSize; public TOKENBINDING_IDENTIFIER* identifierData; public TOKENBINDING_EXTENSION_FORMAT extensionFormat; public uint extensionSize; public IntPtr extensionData; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct TOKENBINDING_RESULT_LIST { public uint resultCount; public TOKENBINDING_RESULT_DATA* resultData; } [Flags] internal enum HTTP_FLAGS : uint { NONE = 0x00000000, HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY = 0x00000001, HTTP_RECEIVE_SECURE_CHANNEL_TOKEN = 0x00000001, HTTP_SEND_RESPONSE_FLAG_DISCONNECT = 0x00000001, HTTP_SEND_RESPONSE_FLAG_MORE_DATA = 0x00000002, HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA = 0x00000004, HTTP_SEND_RESPONSE_FLAG_RAW_HEADER = 0x00000004, HTTP_SEND_REQUEST_FLAG_MORE_DATA = 0x00000001, HTTP_PROPERTY_FLAG_PRESENT = 0x00000001, HTTP_INITIALIZE_SERVER = 0x00000001, HTTP_INITIALIZE_CBT = 0x00000004, HTTP_SEND_RESPONSE_FLAG_OPAQUE = 0x00000040, } private const int HttpHeaderRequestMaximum = (int)HttpRequestHeader.UserAgent + 1; private const int HttpHeaderResponseMaximum = (int)HttpResponseHeader.WwwAuthenticate + 1; internal static class HTTP_REQUEST_HEADER_ID { internal static string ToString(int position) { return s_strings[position]; } private static readonly string[] s_strings = { "Cache-Control", "Connection", "Date", "Keep-Alive", "Pragma", "Trailer", "Transfer-Encoding", "Upgrade", "Via", "Warning", "Allow", "Content-Length", "Content-Type", "Content-Encoding", "Content-Language", "Content-Location", "Content-MD5", "Content-Range", "Expires", "Last-Modified", "Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Authorization", "Cookie", "Expect", "From", "Host", "If-Match", "If-Modified-Since", "If-None-Match", "If-Range", "If-Unmodified-Since", "Max-Forwards", "Proxy-Authorization", "Referer", "Range", "Te", "Translate", "User-Agent", }; } internal enum HTTP_TIMEOUT_TYPE { EntityBody, DrainEntityBody, RequestQueue, IdleConnection, HeaderWait, MinSendRate, } [StructLayout(LayoutKind.Sequential)] internal struct HTTP_TIMEOUT_LIMIT_INFO { internal HTTP_FLAGS Flags; internal ushort EntityBody; internal ushort DrainEntityBody; internal ushort RequestQueue; internal ushort IdleConnection; internal ushort HeaderWait; internal uint MinSendRate; } [StructLayout(LayoutKind.Sequential)] internal struct HTTPAPI_VERSION { internal ushort HttpApiMajorVersion; internal ushort HttpApiMinorVersion; } [StructLayout(LayoutKind.Sequential)] internal struct HTTP_BINDING_INFO { internal HTTP_FLAGS Flags; internal IntPtr RequestQueueHandle; } [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpInitialize(HTTPAPI_VERSION version, uint flags, void* pReserved); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern uint HttpSetUrlGroupProperty(ulong urlGroupId, HTTP_SERVER_PROPERTY serverProperty, IntPtr pPropertyInfo, uint propertyInfoLength); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpCreateServerSession(HTTPAPI_VERSION version, ulong* serverSessionId, uint reserved); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpCreateUrlGroup(ulong serverSessionId, ulong* urlGroupId, uint reserved); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern uint HttpCloseUrlGroup(ulong urlGroupId); [DllImport(Libraries.HttpApi, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe uint HttpCreateRequestQueue(HTTPAPI_VERSION version, string pName, Interop.Kernel32.SECURITY_ATTRIBUTES* pSecurityAttributes, uint flags, out HttpRequestQueueV2Handle pReqQueueHandle); [DllImport(Libraries.HttpApi, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern uint HttpAddUrlToUrlGroup(ulong urlGroupId, string pFullyQualifiedUrl, ulong context, uint pReserved); [DllImport(Libraries.HttpApi, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern uint HttpRemoveUrlFromUrlGroup(ulong urlGroupId, string pFullyQualifiedUrl, uint flags); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpReceiveHttpRequest(SafeHandle requestQueueHandle, ulong requestId, uint flags, HTTP_REQUEST* pRequestBuffer, uint requestBufferLength, uint* pBytesReturned, NativeOverlapped* pOverlapped); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpSendHttpResponse(SafeHandle requestQueueHandle, ulong requestId, uint flags, HTTP_RESPONSE* pHttpResponse, void* pCachePolicy, uint* pBytesSent, SafeLocalAllocHandle pRequestBuffer, uint requestBufferLength, NativeOverlapped* pOverlapped, void* pLogData); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpWaitForDisconnect(SafeHandle requestQueueHandle, ulong connectionId, NativeOverlapped* pOverlapped); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpReceiveRequestEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, void* pEntityBuffer, uint entityBufferLength, out uint bytesReturned, NativeOverlapped* pOverlapped); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpSendResponseEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, ushort entityChunkCount, HTTP_DATA_CHUNK* pEntityChunks, uint* pBytesSent, SafeLocalAllocHandle pRequestBuffer, uint requestBufferLength, NativeOverlapped* pOverlapped, void* pLogData); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpCloseRequestQueue(IntPtr pReqQueueHandle); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern uint HttpCancelHttpRequest(SafeHandle requestQueueHandle, ulong requestId, IntPtr pOverlapped); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern uint HttpCloseServerSession(ulong serverSessionId); internal sealed class SafeLocalFreeChannelBinding : ChannelBinding { private const int LMEM_FIXED = 0; private int _size; private SafeLocalFreeChannelBinding() { } public override int Size { get { return _size; } } public static SafeLocalFreeChannelBinding LocalAlloc(int cb) { SafeLocalFreeChannelBinding result = HttpApi.LocalAlloc(LMEM_FIXED, (UIntPtr)cb); if (result.IsInvalid) { result.SetHandleAsInvalid(); throw new OutOfMemoryException(); } result._size = cb; return result; } override protected bool ReleaseHandle() { return Interop.Kernel32.LocalFree(handle) == IntPtr.Zero; } } [DllImport(Libraries.Kernel32, SetLastError = true)] internal static extern SafeLocalFreeChannelBinding LocalAlloc(int uFlags, UIntPtr sizetdwBytes); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, HTTP_SSL_CLIENT_CERT_INFO* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, NativeOverlapped* pOverlapped); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, byte* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, NativeOverlapped* pOverlapped); internal static readonly string[] HttpVerbs = new string[] { null, "Unknown", "Invalid", "OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", "TRACK", "MOVE", "COPY", "PROPFIND", "PROPPATCH", "MKCOL", "LOCK", "UNLOCK", "SEARCH", }; internal static class HTTP_RESPONSE_HEADER_ID { internal enum Enum { HttpHeaderCacheControl = 0, // general-header [section 4.5] HttpHeaderConnection = 1, // general-header [section 4.5] HttpHeaderDate = 2, // general-header [section 4.5] HttpHeaderKeepAlive = 3, // general-header [not in rfc] HttpHeaderPragma = 4, // general-header [section 4.5] HttpHeaderTrailer = 5, // general-header [section 4.5] HttpHeaderTransferEncoding = 6, // general-header [section 4.5] HttpHeaderUpgrade = 7, // general-header [section 4.5] HttpHeaderVia = 8, // general-header [section 4.5] HttpHeaderWarning = 9, // general-header [section 4.5] HttpHeaderAllow = 10, // entity-header [section 7.1] HttpHeaderContentLength = 11, // entity-header [section 7.1] HttpHeaderContentType = 12, // entity-header [section 7.1] HttpHeaderContentEncoding = 13, // entity-header [section 7.1] HttpHeaderContentLanguage = 14, // entity-header [section 7.1] HttpHeaderContentLocation = 15, // entity-header [section 7.1] HttpHeaderContentMd5 = 16, // entity-header [section 7.1] HttpHeaderContentRange = 17, // entity-header [section 7.1] HttpHeaderExpires = 18, // entity-header [section 7.1] HttpHeaderLastModified = 19, // entity-header [section 7.1] // Response Headers HttpHeaderAcceptRanges = 20, // response-header [section 6.2] HttpHeaderAge = 21, // response-header [section 6.2] HttpHeaderEtag = 22, // response-header [section 6.2] HttpHeaderLocation = 23, // response-header [section 6.2] HttpHeaderProxyAuthenticate = 24, // response-header [section 6.2] HttpHeaderRetryAfter = 25, // response-header [section 6.2] HttpHeaderServer = 26, // response-header [section 6.2] HttpHeaderSetCookie = 27, // response-header [not in rfc] HttpHeaderVary = 28, // response-header [section 6.2] HttpHeaderWwwAuthenticate = 29, // response-header [section 6.2] HttpHeaderResponseMaximum = 30, HttpHeaderMaximum = 41 } private static readonly string[] s_strings = { "Cache-Control", "Connection", "Date", "Keep-Alive", "Pragma", "Trailer", "Transfer-Encoding", "Upgrade", "Via", "Warning", "Allow", "Content-Length", "Content-Type", "Content-Encoding", "Content-Language", "Content-Location", "Content-MD5", "Content-Range", "Expires", "Last-Modified", "Accept-Ranges", "Age", "ETag", "Location", "Proxy-Authenticate", "Retry-After", "Server", "Set-Cookie", "Vary", "WWW-Authenticate", }; private static readonly Dictionary<string, int> s_hashtable = CreateTable(); private static Dictionary<string, int> CreateTable() { var table = new Dictionary<string, int>((int)Enum.HttpHeaderResponseMaximum); for (int i = 0; i < (int)Enum.HttpHeaderResponseMaximum; i++) { table.Add(s_strings[i], i); } return table; } internal static int IndexOfKnownHeader(string headerName) { int index; return s_hashtable.TryGetValue(headerName, out index) ? index : -1; } internal static string ToString(int position) { return s_strings[position]; } } private static unsafe string GetKnownHeader(HTTP_REQUEST* request, long fixup, int headerIndex) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(null); } string header = null; HTTP_KNOWN_HEADER* pKnownHeader = (&request->Headers.KnownHeaders) + headerIndex; if (NetEventSource.IsEnabled) { NetEventSource.Info(null, $"HttpApi::GetKnownHeader() pKnownHeader:0x{(IntPtr)pKnownHeader}"); NetEventSource.Info(null, $"HttpApi::GetKnownHeader() pRawValue:0x{(IntPtr)pKnownHeader->pRawValue} RawValueLength:{pKnownHeader->RawValueLength}"); } // For known headers, when header value is empty, RawValueLength will be 0 and // pRawValue will point to empty string if (pKnownHeader->pRawValue != null) { header = new string(pKnownHeader->pRawValue + fixup, 0, pKnownHeader->RawValueLength); } if (NetEventSource.IsEnabled) { NetEventSource.Exit(null, $"HttpApi::GetKnownHeader() return:{header}"); } return header; } internal static unsafe string GetKnownHeader(HTTP_REQUEST* request, int headerIndex) { return GetKnownHeader(request, 0, headerIndex); } private static unsafe string GetVerb(HTTP_REQUEST* request, long fixup) { string verb = null; if ((int)request->Verb > (int)HTTP_VERB.HttpVerbUnknown && (int)request->Verb < (int)HTTP_VERB.HttpVerbMaximum) { verb = HttpVerbs[(int)request->Verb]; } else if (request->Verb == HTTP_VERB.HttpVerbUnknown && request->pUnknownVerb != null) { verb = new string(request->pUnknownVerb + fixup, 0, request->UnknownVerbLength); } return verb; } internal static unsafe string GetVerb(HTTP_REQUEST* request) { return GetVerb(request, 0); } internal static unsafe string GetVerb(IntPtr memoryBlob, IntPtr originalAddress) { return GetVerb((HTTP_REQUEST*)memoryBlob.ToPointer(), (byte*)memoryBlob - (byte*)originalAddress); } // Server API internal static unsafe WebHeaderCollection GetHeaders(IntPtr memoryBlob, IntPtr originalAddress) { NetEventSource.Enter(null); // Return value. WebHeaderCollection headerCollection = new WebHeaderCollection(); byte* pMemoryBlob = (byte*)memoryBlob; HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob; long fixup = pMemoryBlob - (byte*)originalAddress; int index; // unknown headers if (request->Headers.UnknownHeaderCount != 0) { HTTP_UNKNOWN_HEADER* pUnknownHeader = (HTTP_UNKNOWN_HEADER*)(fixup + (byte*)request->Headers.pUnknownHeaders); for (index = 0; index < request->Headers.UnknownHeaderCount; index++) { // For unknown headers, when header value is empty, RawValueLength will be 0 and // pRawValue will be null. if (pUnknownHeader->pName != null && pUnknownHeader->NameLength > 0) { string headerName = new string(pUnknownHeader->pName + fixup, 0, pUnknownHeader->NameLength); string headerValue; if (pUnknownHeader->pRawValue != null && pUnknownHeader->RawValueLength > 0) { headerValue = new string(pUnknownHeader->pRawValue + fixup, 0, pUnknownHeader->RawValueLength); } else { headerValue = string.Empty; } headerCollection.Add(headerName, headerValue); } pUnknownHeader++; } } // known headers HTTP_KNOWN_HEADER* pKnownHeader = &request->Headers.KnownHeaders; for (index = 0; index < HttpHeaderRequestMaximum; index++) { // For known headers, when header value is empty, RawValueLength will be 0 and // pRawValue will point to empty string ("\0") if (pKnownHeader->pRawValue != null) { string headerValue = new string(pKnownHeader->pRawValue + fixup, 0, pKnownHeader->RawValueLength); headerCollection.Add(HTTP_REQUEST_HEADER_ID.ToString(index), headerValue); } pKnownHeader++; } NetEventSource.Exit(null); return headerCollection; } internal static unsafe uint GetChunks(IntPtr memoryBlob, IntPtr originalAddress, ref int dataChunkIndex, ref uint dataChunkOffset, byte[] buffer, int offset, int size) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(null, $"HttpApi::GetChunks() memoryBlob:{memoryBlob}"); } // Return value. uint dataRead = 0; byte* pMemoryBlob = (byte*)memoryBlob; HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob; long fixup = pMemoryBlob - (byte*)originalAddress; if (request->EntityChunkCount > 0 && dataChunkIndex < request->EntityChunkCount && dataChunkIndex != -1) { HTTP_DATA_CHUNK* pDataChunk = (HTTP_DATA_CHUNK*)(fixup + (byte*)&request->pEntityChunks[dataChunkIndex]); fixed (byte* pReadBuffer = buffer) { byte* pTo = &pReadBuffer[offset]; while (dataChunkIndex < request->EntityChunkCount && dataRead < size) { if (dataChunkOffset >= pDataChunk->BufferLength) { dataChunkOffset = 0; dataChunkIndex++; pDataChunk++; } else { byte* pFrom = pDataChunk->pBuffer + dataChunkOffset + fixup; uint bytesToRead = pDataChunk->BufferLength - (uint)dataChunkOffset; if (bytesToRead > (uint)size) { bytesToRead = (uint)size; } for (uint i = 0; i < bytesToRead; i++) { *(pTo++) = *(pFrom++); } dataRead += bytesToRead; dataChunkOffset += bytesToRead; } } } } //we're finished. if (dataChunkIndex == request->EntityChunkCount) { dataChunkIndex = -1; } if (NetEventSource.IsEnabled) { NetEventSource.Exit(null); } return dataRead; } internal static unsafe HTTP_VERB GetKnownVerb(IntPtr memoryBlob, IntPtr originalAddress) { NetEventSource.Enter(null); // Return value. HTTP_VERB verb = HTTP_VERB.HttpVerbUnknown; HTTP_REQUEST* request = (HTTP_REQUEST*)memoryBlob.ToPointer(); if ((int)request->Verb > (int)HTTP_VERB.HttpVerbUnparsed && (int)request->Verb < (int)HTTP_VERB.HttpVerbMaximum) { verb = request->Verb; } NetEventSource.Exit(null); return verb; } internal static unsafe IPEndPoint GetRemoteEndPoint(IntPtr memoryBlob, IntPtr originalAddress) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null); SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); byte* pMemoryBlob = (byte*)memoryBlob; HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob; IntPtr address = request->Address.pRemoteAddress != null ? (IntPtr)(pMemoryBlob - (byte*)originalAddress + (byte*)request->Address.pRemoteAddress) : IntPtr.Zero; CopyOutAddress(address, ref v4address, ref v6address); IPEndPoint endpoint = null; if (v4address != null) { endpoint = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort).Create(v4address) as IPEndPoint; } else if (v6address != null) { endpoint = new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort).Create(v6address) as IPEndPoint; } if (NetEventSource.IsEnabled) NetEventSource.Exit(null); return endpoint; } internal static unsafe IPEndPoint GetLocalEndPoint(IntPtr memoryBlob, IntPtr originalAddress) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null); SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); byte* pMemoryBlob = (byte*)memoryBlob; HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob; IntPtr address = request->Address.pLocalAddress != null ? (IntPtr)(pMemoryBlob - (byte*)originalAddress + (byte*)request->Address.pLocalAddress) : IntPtr.Zero; CopyOutAddress(address, ref v4address, ref v6address); IPEndPoint endpoint = null; if (v4address != null) { endpoint = s_any.Create(v4address) as IPEndPoint; } else if (v6address != null) { endpoint = s_ipv6Any.Create(v6address) as IPEndPoint; } if (NetEventSource.IsEnabled) NetEventSource.Exit(null); return endpoint; } private static unsafe void CopyOutAddress(IntPtr address, ref SocketAddress v4address, ref SocketAddress v6address) { if (address != IntPtr.Zero) { ushort addressFamily = *((ushort*)address); if (addressFamily == (ushort)AddressFamily.InterNetwork) { v6address = null; for (int index = 2; index < IPv4AddressSize; index++) { v4address[index] = ((byte*)address)[index]; } return; } if (addressFamily == (ushort)AddressFamily.InterNetworkV6) { v4address = null; for (int index = 2; index < IPv6AddressSize; index++) { v6address[index] = ((byte*)address)[index]; } return; } } v4address = null; v6address = 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. */ namespace Apache.Ignite.Core.Tests.Cache.Query { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Portable; using Apache.Ignite.Core.Portable; using NUnit.Framework; /// <summary> /// Queries tests. /// </summary> public class CacheQueriesTest { /** Grid count. */ private const int GridCnt = 2; /** Cache name. */ private const string CacheName = "cache"; /** Path to XML configuration. */ private const string CfgPath = "config\\cache-query.xml"; /** Maximum amount of items in cache. */ private const int MaxItemCnt = 100; /// <summary> /// /// </summary> [TestFixtureSetUp] public virtual void StartGrids() { TestUtils.JvmDebug = true; TestUtils.KillProcesses(); IgniteConfigurationEx cfg = new IgniteConfigurationEx { PortableConfiguration = new PortableConfiguration { TypeConfigurations = new[] { new PortableTypeConfiguration(typeof (QueryPerson)), new PortableTypeConfiguration(typeof (PortableScanQueryFilter<QueryPerson>)), new PortableTypeConfiguration(typeof (PortableScanQueryFilter<PortableUserObject>)) } }, JvmClasspath = TestUtils.CreateTestClasspath(), JvmOptions = TestUtils.TestJavaOptions(), SpringConfigUrl = CfgPath }; for (int i = 0; i < GridCnt; i++) { cfg.GridName = "grid-" + i; Ignition.Start(cfg); } } /// <summary> /// /// </summary> [TestFixtureTearDown] public virtual void StopGrids() { for (int i = 0; i < GridCnt; i++) Ignition.Stop("grid-" + i, true); } /// <summary> /// /// </summary> [SetUp] public virtual void BeforeTest() { Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name); } /// <summary> /// /// </summary> [TearDown] public virtual void AfterTest() { var cache = Cache(); for (int i = 0; i < GridCnt; i++) { for (int j = 0; j < MaxItemCnt; j++) cache.Remove(j); Assert.IsTrue(cache.IsEmpty); } Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name); } /// <summary> /// /// </summary> /// <param name="idx"></param> /// <returns></returns> public IIgnite GetIgnite(int idx) { return Ignition.GetIgnite("grid-" + idx); } /// <summary> /// /// </summary> /// <param name="idx"></param> /// <returns></returns> public ICache<int, QueryPerson> Cache(int idx) { return GetIgnite(idx).Cache<int, QueryPerson>(CacheName); } /// <summary> /// /// </summary> /// <returns></returns> public ICache<int, QueryPerson> Cache() { return Cache(0); } /// <summary> /// Test arguments validation for SQL queries. /// </summary> [Test] public void TestValidationSql() { // 1. No sql. Assert.Throws<ArgumentException>(() => { Cache().Query(new SqlQuery(typeof(QueryPerson), null)); }); // 2. No type. Assert.Throws<ArgumentException>(() => { Cache().Query(new SqlQuery((string)null, "age >= 50")); }); } /// <summary> /// Test arguments validation for SQL fields queries. /// </summary> [Test] public void TestValidationSqlFields() { // 1. No sql. Assert.Throws<ArgumentException>(() => { Cache().QueryFields(new SqlFieldsQuery(null)); }); } /// <summary> /// Test arguments validation for TEXT queries. /// </summary> [Test] public void TestValidationText() { // 1. No text. Assert.Throws<ArgumentException>(() => { Cache().Query(new TextQuery(typeof(QueryPerson), null)); }); // 2. No type. Assert.Throws<ArgumentException>(() => { Cache().Query(new TextQuery((string)null, "Ivanov")); }); } /// <summary> /// Cursor tests. /// </summary> [Test] [SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")] public void TestCursor() { var cache0 = Cache().WithAsync(); cache0.WithAsync().Put(1, new QueryPerson("Ivanov", 30)); IFuture<object> res = cache0.GetFuture<object>(); res.Get(); Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(1, new QueryPerson("Petrov", 40)); Cache().Put(1, new QueryPerson("Sidorov", 50)); SqlQuery qry = new SqlQuery(typeof(QueryPerson), "age >= 20"); // 1. Test GetAll(). using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry)) { cursor.GetAll(); Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); }); Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); }); } // 2. Test GetEnumerator. using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry)) { cursor.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); }); Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); }); } } /// <summary> /// Test enumerator. /// </summary> [Test] [SuppressMessage("ReSharper", "UnusedVariable")] public void TestEnumerator() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(2, new QueryPerson("Petrov", 40)); Cache().Put(3, new QueryPerson("Sidorov", 50)); Cache().Put(4, new QueryPerson("Unknown", 60)); // 1. Empty result set. using ( IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(new SqlQuery(typeof(QueryPerson), "age = 100"))) { IEnumerator<ICacheEntry<int, QueryPerson>> e = cursor.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => { ICacheEntry<int, QueryPerson> entry = e.Current; }); Assert.IsFalse(e.MoveNext()); Assert.Throws<InvalidOperationException>(() => { ICacheEntry<int, QueryPerson> entry = e.Current; }); Assert.Throws<NotSupportedException>(() => e.Reset()); } SqlQuery qry = new SqlQuery(typeof (QueryPerson), "age < 60"); // 2. Page size is bigger than result set. qry.PageSize = 4; CheckEnumeratorQuery(qry); // 3. Page size equal to result set. qry.PageSize = 3; CheckEnumeratorQuery(qry); // 4. Page size if less than result set. qry.PageSize = 2; CheckEnumeratorQuery(qry); } /// <summary> /// Test SQL query arguments passing. /// </summary> public void TestSqlQueryArguments() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(2, new QueryPerson("Petrov", 40)); Cache().Put(3, new QueryPerson("Sidorov", 50)); // 1. Empty result set. using ( IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(new SqlQuery(typeof(QueryPerson), "age < ?", 50))) { foreach (ICacheEntry<int, QueryPerson> entry in cursor.GetAll()) Assert.IsTrue(entry.Key == 1 || entry.Key == 2); } } /// <summary> /// Test SQL fields query arguments passing. /// </summary> public void TestSqlFieldsQueryArguments() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(2, new QueryPerson("Petrov", 40)); Cache().Put(3, new QueryPerson("Sidorov", 50)); // 1. Empty result set. using ( IQueryCursor<IList> cursor = Cache().QueryFields( new SqlFieldsQuery("SELECT age FROM QueryPerson WHERE age < ?", 50))) { foreach (IList entry in cursor.GetAll()) Assert.IsTrue((int) entry[0] < 50); } } /// <summary> /// Check query result for enumerator test. /// </summary> /// <param name="qry">QUery.</param> private void CheckEnumeratorQuery(SqlQuery qry) { using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry)) { bool first = false; bool second = false; bool third = false; foreach (var entry in cursor) { if (entry.Key == 1) { first = true; Assert.AreEqual("Ivanov", entry.Value.Name); Assert.AreEqual(30, entry.Value.Age); } else if (entry.Key == 2) { second = true; Assert.AreEqual("Petrov", entry.Value.Name); Assert.AreEqual(40, entry.Value.Age); } else if (entry.Key == 3) { third = true; Assert.AreEqual("Sidorov", entry.Value.Name); Assert.AreEqual(50, entry.Value.Age); } else Assert.Fail("Unexpected value: " + entry); } Assert.IsTrue(first && second && third); } } /// <summary> /// Check SQL query. /// </summary> [Test] public void TestSqlQuery() { CheckSqlQuery(MaxItemCnt, false, false); } /// <summary> /// Check SQL query in portable mode. /// </summary> [Test] public void TestSqlQueryPortable() { CheckSqlQuery(MaxItemCnt, false, true); } /// <summary> /// Check local SQL query. /// </summary> [Test] public void TestSqlQueryLocal() { CheckSqlQuery(MaxItemCnt, true, false); } /// <summary> /// Check local SQL query in portable mode. /// </summary> [Test] public void TestSqlQueryLocalPortable() { CheckSqlQuery(MaxItemCnt, true, true); } /// <summary> /// Check SQL query. /// </summary> /// <param name="cnt">Amount of cache entries to create.</param> /// <param name="loc">Local query flag.</param> /// <param name="keepPortable">Keep portable flag.</param> private void CheckSqlQuery(int cnt, bool loc, bool keepPortable) { var cache = Cache(); // 1. Populate cache with data, calculating expected count in parallel. var exp = PopulateCache(cache, loc, cnt, x => x < 50); // 2. Validate results. SqlQuery qry = loc ? new SqlQuery(typeof(QueryPerson), "age < 50", true) : new SqlQuery(typeof(QueryPerson), "age < 50"); ValidateQueryResults(cache, qry, exp, keepPortable); } /// <summary> /// Check SQL fields query. /// </summary> [Test] public void TestSqlFieldsQuery() { CheckSqlFieldsQuery(MaxItemCnt, false); } /// <summary> /// Check local SQL fields query. /// </summary> [Test] public void TestSqlFieldsQueryLocal() { CheckSqlFieldsQuery(MaxItemCnt, true); } /// <summary> /// Check SQL fields query. /// </summary> /// <param name="cnt">Amount of cache entries to create.</param> /// <param name="loc">Local query flag.</param> private void CheckSqlFieldsQuery(int cnt, bool loc) { var cache = Cache(); // 1. Populate cache with data, calculating expected count in parallel. var exp = PopulateCache(cache, loc, cnt, x => x < 50); // 2. Vlaidate results. SqlFieldsQuery qry = loc ? new SqlFieldsQuery("SELECT name, age FROM QueryPerson WHERE age < 50", true) : new SqlFieldsQuery("SELECT name, age FROM QueryPerson WHERE age < 50"); using (IQueryCursor<IList> cursor = cache.QueryFields(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); foreach (var entry in cursor.GetAll()) { Assert.AreEqual(2, entry.Count); Assert.AreEqual(entry[0].ToString(), entry[1].ToString()); exp0.Remove((int)entry[1]); } Assert.AreEqual(0, exp0.Count); } using (IQueryCursor<IList> cursor = cache.QueryFields(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); foreach (var entry in cursor) { Assert.AreEqual(entry[0].ToString(), entry[1].ToString()); exp0.Remove((int)entry[1]); } Assert.AreEqual(0, exp0.Count); } } /// <summary> /// Check text query. /// </summary> [Test] public void TestTextQuery() { CheckTextQuery(MaxItemCnt, false, false); } /// <summary> /// Check SQL query in portable mode. /// </summary> [Test] public void TestTextQueryPortable() { CheckTextQuery(MaxItemCnt, false, true); } /// <summary> /// Check local SQL query. /// </summary> [Test] public void TestTextQueryLocal() { CheckTextQuery(MaxItemCnt, true, false); } /// <summary> /// Check local SQL query in portable mode. /// </summary> [Test] public void TestTextQueryLocalPortable() { CheckTextQuery(MaxItemCnt, true, true); } /// <summary> /// Check text query. /// </summary> /// <param name="cnt">Amount of cache entries to create.</param> /// <param name="loc">Local query flag.</param> /// <param name="keepPortable">Keep portable flag.</param> private void CheckTextQuery(int cnt, bool loc, bool keepPortable) { var cache = Cache(); // 1. Populate cache with data, calculating expected count in parallel. var exp = PopulateCache(cache, loc, cnt, x => x.ToString().StartsWith("1")); // 2. Validate results. TextQuery qry = loc ? new TextQuery(typeof(QueryPerson), "1*", true) : new TextQuery(typeof(QueryPerson), "1*"); ValidateQueryResults(cache, qry, exp, keepPortable); } /// <summary> /// Check scan query. /// </summary> [Test] public void TestScanQuery() { CheckScanQuery<QueryPerson>(MaxItemCnt, false, false); } /// <summary> /// Check scan query in portable mode. /// </summary> [Test] public void TestScanQueryPortable() { CheckScanQuery<PortableUserObject>(MaxItemCnt, false, true); } /// <summary> /// Check local scan query. /// </summary> [Test] public void TestScanQueryLocal() { CheckScanQuery<QueryPerson>(MaxItemCnt, true, false); } /// <summary> /// Check local scan query in portable mode. /// </summary> [Test] public void TestScanQueryLocalPortable() { CheckScanQuery<PortableUserObject>(MaxItemCnt, true, true); } /// <summary> /// Check scan query with partitions. /// </summary> [Test] [Ignore("IGNITE-1012")] public void TestScanQueryPartitions([Values(true, false)] bool loc) { CheckScanQueryPartitions<QueryPerson>(MaxItemCnt, loc, false); } /// <summary> /// Check scan query with partitions in portable mode. /// </summary> [Test] [Ignore("IGNITE-1012")] public void TestScanQueryPartitionsPortable([Values(true, false)] bool loc) { CheckScanQueryPartitions<PortableUserObject>(MaxItemCnt, loc, true); } /// <summary> /// Tests that query attempt on non-indexed cache causes an exception. /// </summary> [Test] public void TestIndexingDisabledError() { var cache = GetIgnite(0).GetOrCreateCache<int, QueryPerson>("nonindexed_cache"); var queries = new QueryBase[] { new TextQuery(typeof (QueryPerson), "1*"), new SqlQuery(typeof (QueryPerson), "age < 50") }; foreach (var qry in queries) { var err = Assert.Throws<IgniteException>(() => cache.Query(qry)); Assert.AreEqual("Indexing is disabled for cache: nonindexed_cache. " + "Use setIndexedTypes or setTypeMetadata methods on CacheConfiguration to enable.", err.Message); } } /// <summary> /// Check scan query. /// </summary> /// <param name="cnt">Amount of cache entries to create.</param> /// <param name="loc">Local query flag.</param> /// <param name="keepPortable">Keep portable flag.</param> private void CheckScanQuery<TV>(int cnt, bool loc, bool keepPortable) { var cache = Cache(); // No predicate var exp = PopulateCache(cache, loc, cnt, x => true); var qry = new ScanQuery<int, TV>(); ValidateQueryResults(cache, qry, exp, keepPortable); // Serializable exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>()); ValidateQueryResults(cache, qry, exp, keepPortable); // Portable exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new PortableScanQueryFilter<TV>()); ValidateQueryResults(cache, qry, exp, keepPortable); // Exception exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV> {ThrowErr = true}); var ex = Assert.Throws<IgniteException>(() => ValidateQueryResults(cache, qry, exp, keepPortable)); Assert.AreEqual(ScanQueryFilter<TV>.ErrMessage, ex.Message); } /// <summary> /// Checks scan query with partitions. /// </summary> /// <param name="cnt">Amount of cache entries to create.</param> /// <param name="loc">Local query flag.</param> /// <param name="keepPortable">Keep portable flag.</param> private void CheckScanQueryPartitions<TV>(int cnt, bool loc, bool keepPortable) { StopGrids(); StartGrids(); var cache = Cache(); var aff = cache.Ignite.Affinity(CacheName); var exp = PopulateCache(cache, loc, cnt, x => true); // populate outside the loop (slow) for (var part = 0; part < aff.Partitions; part++) { //var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys var exp0 = new HashSet<int>(); foreach (var x in exp) if (aff.Partition(x) == part) exp0.Add(x); var qry = new ScanQuery<int, TV> { Partition = part }; Console.WriteLine("Checking query on partition " + part); ValidateQueryResults(cache, qry, exp0, keepPortable); } // Partitions with predicate exp = PopulateCache(cache, loc, cnt, x => x < 50); // populate outside the loop (slow) for (var part = 0; part < aff.Partitions; part++) { //var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys var exp0 = new HashSet<int>(); foreach (var x in exp) if (aff.Partition(x) == part) exp0.Add(x); var qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>()) { Partition = part }; Console.WriteLine("Checking predicate query on partition " + part); ValidateQueryResults(cache, qry, exp0, keepPortable); } } /// <summary> /// Validates the query results. /// </summary> /// <param name="cache">Cache.</param> /// <param name="qry">Query.</param> /// <param name="exp">Expected keys.</param> /// <param name="keepPortable">Keep portable flag.</param> private static void ValidateQueryResults(ICache<int, QueryPerson> cache, QueryBase qry, HashSet<int> exp, bool keepPortable) { if (keepPortable) { var cache0 = cache.WithKeepPortable<int, IPortableObject>(); using (var cursor = cache0.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor.GetAll()) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.Field<string>("name")); Assert.AreEqual(entry.Key, entry.Value.Field<int>("age")); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } using (var cursor = cache0.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.Field<string>("name")); Assert.AreEqual(entry.Key, entry.Value.Field<int>("age")); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } } else { using (var cursor = cache.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor.GetAll()) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.Name); Assert.AreEqual(entry.Key, entry.Value.Age); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } using (var cursor = cache.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.Name); Assert.AreEqual(entry.Key, entry.Value.Age); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } } } /// <summary> /// Asserts that all expected entries have been received. /// </summary> private static void AssertMissingExpectedKeys(ICollection<int> exp, ICache<int, QueryPerson> cache, IList<ICacheEntry<int, object>> all) { if (exp.Count == 0) return; var sb = new StringBuilder(); var aff = cache.Ignite.Affinity(cache.Name); foreach (var key in exp) { var part = aff.Partition(key); sb.AppendFormat( "Query did not return expected key '{0}' (exists: {1}), partition '{2}', partition nodes: ", key, cache.Get(key) != null, part); var partNodes = aff.MapPartitionToPrimaryAndBackups(part); foreach (var node in partNodes) sb.Append(node).Append(" "); sb.AppendLine(";"); } sb.Append("Returned keys: "); foreach (var e in all) sb.Append(e.Key).Append(" "); sb.AppendLine(";"); Assert.Fail(sb.ToString()); } /// <summary> /// Populates the cache with random entries and returns expected results set according to filter. /// </summary> /// <param name="cache">The cache.</param> /// <param name="cnt">Amount of cache entries to create.</param> /// <param name="loc">Local query flag.</param> /// <param name="expectedEntryFilter">The expected entry filter.</param> /// <returns>Expected results set.</returns> private static HashSet<int> PopulateCache(ICache<int, QueryPerson> cache, bool loc, int cnt, Func<int, bool> expectedEntryFilter) { var rand = new Random(); var exp = new HashSet<int>(); for (var i = 0; i < cnt; i++) { var val = rand.Next(100); cache.Put(val, new QueryPerson(val.ToString(), val)); if (expectedEntryFilter(val) && (!loc || cache.Ignite.Affinity(cache.Name) .IsPrimary(cache.Ignite.Cluster.LocalNode, val))) exp.Add(val); } return exp; } } /// <summary> /// Person. /// </summary> public class QueryPerson { /// <summary> /// Constructor. /// </summary> public QueryPerson() { // No-op. } /// <summary> /// Constructor. /// </summary> /// <param name="name">Name.</param> /// <param name="age">Age.</param> public QueryPerson(string name, int age) { Name = name; Age = age; } /// <summary> /// Name. /// </summary> public string Name { get; set; } /// <summary> /// Age. /// </summary> public int Age { get; set; } } /// <summary> /// Query filter. /// </summary> [Serializable] public class ScanQueryFilter<TV> : ICacheEntryFilter<int, TV> { // Error message public const string ErrMessage = "Error in ScanQueryFilter.Invoke"; // Error flag public bool ThrowErr { get; set; } /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, TV> entry) { if (ThrowErr) throw new Exception(ErrMessage); return entry.Key < 50; } } /// <summary> /// Portable query filter. /// </summary> public class PortableScanQueryFilter<TV> : ScanQueryFilter<TV>, IPortableMarshalAware { /** <inheritdoc /> */ public void WritePortable(IPortableWriter writer) { var w = writer.RawWriter(); w.WriteBoolean(ThrowErr); } /** <inheritdoc /> */ public void ReadPortable(IPortableReader reader) { var r = reader.RawReader(); ThrowErr = r.ReadBoolean(); } } }
// // Copyright (c) 2004-2021 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 System.Linq; namespace NLog.UnitTests { using System; using System.Text; using System.Collections.Generic; using System.Reflection; using NLog.Config; using Xunit; /// <summary> /// Test the characteristics of the API. Config of the API is tested in <see cref="NLog.UnitTests.Config.ConfigApiTests"/> /// </summary> public class ApiTests : NLogTestBase { private Type[] allTypes; private Assembly nlogAssembly = typeof(LogManager).Assembly; private readonly Dictionary<Type, int> typeUsageCount = new Dictionary<Type, int>(); public ApiTests() { allTypes = typeof(LogManager).Assembly.GetTypes(); } [Fact] public void PublicEnumsTest() { foreach (Type type in allTypes) { if (!type.IsPublic) { continue; } if (type.IsEnum || type.IsInterface) { typeUsageCount[type] = 0; } } typeUsageCount[typeof(IInstallable)] = 1; foreach (Type type in allTypes) { if (type.IsGenericTypeDefinition) { continue; } if (type.BaseType != null) { IncrementUsageCount(type.BaseType); } foreach (var iface in type.GetInterfaces()) { IncrementUsageCount(iface); } foreach (var method in type.GetMethods()) { if (method.IsGenericMethodDefinition) { continue; } // Console.WriteLine(" {0}", method.Name); try { IncrementUsageCount(method.ReturnType); foreach (var p in method.GetParameters()) { IncrementUsageCount(p.ParameterType); } } catch (Exception ex) { // this sometimes throws on .NET Compact Framework, but is not fatal Console.WriteLine("EXCEPTION {0}", ex); } } } var unusedTypes = new List<Type>(); StringBuilder sb = new StringBuilder(); foreach (var kvp in typeUsageCount) { if (kvp.Value == 0) { Console.WriteLine("Type '{0}' is not used.", kvp.Key); unusedTypes.Add(kvp.Key); sb.Append(kvp.Key.FullName).Append("\n"); } } Assert.Empty(unusedTypes); } [Fact] public void TypesInInternalNamespaceShouldBeInternalTest() { var excludes = new HashSet<Type> { typeof(NLog.Internal.Xamarin.PreserveAttribute), #pragma warning disable CS0618 // Type or member is obsolete typeof(NLog.Internal.Fakeables.IAppDomain), // TODO NLog 5 - handle IAppDomain #pragma warning restore CS0618 // Type or member is obsolete }; var notInternalTypes = allTypes .Where(t => t.Namespace != null && t.Namespace.Contains(".Internal")) .Where(t => !t.IsNested && (t.IsVisible || t.IsPublic)) .Where(n => !excludes.Contains(n)) .Select(t => t.FullName) .ToList(); Assert.Empty(notInternalTypes); } private void IncrementUsageCount(Type type) { if (type.IsArray) { type = type.GetElementType(); } if (type.IsGenericType && !type.IsGenericTypeDefinition) { IncrementUsageCount(type.GetGenericTypeDefinition()); foreach (var parm in type.GetGenericArguments()) { IncrementUsageCount(parm); } return; } if (type.Assembly != nlogAssembly) { return; } if (typeUsageCount.ContainsKey(type)) { typeUsageCount[type]++; } } [Fact] public void TryGetRawValue_ThreadAgnostic_Attribute_Required() { foreach (Type type in allTypes) { if (typeof(NLog.Internal.IRawValue).IsAssignableFrom(type) && !type.IsInterface) { var threadAgnosticAttribute = type.GetCustomAttribute<ThreadAgnosticAttribute>(); Assert.True(!(threadAgnosticAttribute is null), $"{type.ToString()} cannot implement IRawValue"); } } } [Fact] public void IStringValueRenderer_AppDomainFixedOutput_Attribute_NotRequired() { foreach (Type type in allTypes) { if (typeof(NLog.Internal.IStringValueRenderer).IsAssignableFrom(type) && !type.IsInterface) { var appDomainFixedOutputAttribute = type.GetCustomAttribute<AppDomainFixedOutputAttribute>(); Assert.True(appDomainFixedOutputAttribute is null, $"{type.ToString()} should not implement IStringValueRenderer"); } } } [Fact] public void AppDomainFixedOutput_Attribute_EnsureThreadAgnostic() { foreach (Type type in allTypes) { var appDomainFixedOutputAttribute = type.GetCustomAttribute<AppDomainFixedOutputAttribute>(); if (appDomainFixedOutputAttribute != null) { var threadAgnosticAttribute = type.GetCustomAttribute<ThreadAgnosticAttribute>(); Assert.True(!(threadAgnosticAttribute is null), $"{type.ToString()} should also have ThreadAgnostic"); } } } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Text; using Amazon.Util; using System.Globalization; using Amazon.Runtime.Internal.Util; namespace Amazon.Runtime.Internal.Auth { public class AWS3Signer : AbstractAWSSigner { private const string HTTP_SCHEME = "AWS3"; private const string HTTPS_SCHEME = "AWS3-HTTPS"; private bool UseAws3Https { get; set; } public AWS3Signer(bool useAws3Https) { UseAws3Https = useAws3Https; } public AWS3Signer() : this(false) { } public override ClientProtocol Protocol { get { return ClientProtocol.RestProtocol; } } /// <summary> /// Signs the specified request with the AWS3 signing protocol by using the /// AWS account credentials given in the method parameters. /// </summary> /// <param name="awsAccessKeyId">The AWS public key</param> /// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param> /// <param name="metrics">Request metrics</param> /// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param> /// <param name="request">The request to have the signature compute for</param> /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception> public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { var signer = SelectSigner(request, clientConfig); var useV4 = signer is AWS4Signer; if (useV4) signer.Sign(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey); else { if (UseAws3Https) { SignHttps(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey); } else { SignHttp(request, metrics, awsAccessKeyId, awsSecretAccessKey); } } } private static void SignHttps(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { string nonce = Guid.NewGuid().ToString(); string date = AWSSDKUtils.FormattedCurrentTimestampRFC822; string stringToSign; stringToSign = date + nonce; metrics.AddProperty(Metric.StringToSign, stringToSign); string signature = ComputeHash(stringToSign, awsSecretAccessKey, clientConfig.SignatureMethod); StringBuilder builder = new StringBuilder(); builder.Append(HTTPS_SCHEME).Append(" "); builder.Append("AWSAccessKeyId=" + awsAccessKeyId + ","); builder.Append("Algorithm=" + clientConfig.SignatureMethod.ToString() + ","); builder.Append("SignedHeaders=x-amz-date;x-amz-nonce,"); builder.Append("Signature=" + signature); request.Headers[HeaderKeys.XAmzAuthorizationHeader] = builder.ToString(); request.Headers[HeaderKeys.XAmzNonceHeader] = nonce; request.Headers[HeaderKeys.XAmzDateHeader] = date; } private static void SignHttp(IRequest request, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256; string nonce = Guid.NewGuid().ToString(); string date = AWSSDKUtils.FormattedCurrentTimestampRFC822; bool isHttps = IsHttpsRequest(request); // Temporarily disabling the AWS3 HTTPS signing scheme and only using AWS3 HTTP isHttps = false; request.Headers[HeaderKeys.DateHeader] = date; request.Headers[HeaderKeys.XAmzDateHeader] = date; // Clear out existing auth header (can be there if retry) request.Headers.Remove(HeaderKeys.XAmzAuthorizationHeader); // AWS3 HTTP requires that we sign the Host header // so we have to have it in the request by the time we sign. string hostHeader = request.Endpoint.Host; if (!request.Endpoint.IsDefaultPort) hostHeader += ":" + request.Endpoint.Port; request.Headers[HeaderKeys.HostHeader] = hostHeader; byte[] bytesToSign = null; string stringToSign; if (isHttps) { request.Headers[HeaderKeys.XAmzNonceHeader] = nonce; stringToSign = date + nonce; bytesToSign = Encoding.UTF8.GetBytes(stringToSign); } else { Uri url = request.Endpoint; if (!string.IsNullOrEmpty(request.ResourcePath)) url = new Uri(request.Endpoint, request.ResourcePath); stringToSign = request.HttpMethod + "\n" + GetCanonicalizedResourcePath(url) + "\n" + GetCanonicalizedQueryString(request.Parameters) + "\n" + GetCanonicalizedHeadersForStringToSign(request) + "\n" + GetRequestPayload(request); bytesToSign = CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(Encoding.UTF8.GetBytes(stringToSign)); } metrics.AddProperty(Metric.StringToSign, stringToSign); string signature = ComputeHash(bytesToSign, awsSecretAccessKey, algorithm); StringBuilder builder = new StringBuilder(); builder.Append(isHttps ? HTTPS_SCHEME : HTTP_SCHEME); builder.Append(" "); builder.Append("AWSAccessKeyId=" + awsAccessKeyId + ","); builder.Append("Algorithm=" + algorithm.ToString() + ","); if (!isHttps) { builder.Append(GetSignedHeadersComponent(request) + ","); } builder.Append("Signature=" + signature); string authorizationHeader = builder.ToString(); request.Headers[HeaderKeys.XAmzAuthorizationHeader] = authorizationHeader; } #region Http signing helpers private static string GetCanonicalizedResourcePath(Uri endpoint) { string uri = endpoint.AbsolutePath; if (string.IsNullOrEmpty(uri)) { return "/"; } else { return AWSSDKUtils.UrlEncode(uri, true); } } private static bool IsHttpsRequest(IRequest request) { string protocol = request.Endpoint.Scheme; if (protocol.Equals("http", StringComparison.OrdinalIgnoreCase)) { return false; } else if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase)) { return true; } else { throw new AmazonServiceException( "Unknown request endpoint protocol encountered while signing request: " + protocol); } } private static string GetCanonicalizedQueryString(IDictionary<string, string> parameters) { IDictionary<string, string> sorted = new SortedDictionary<string, string>(parameters, StringComparer.Ordinal); StringBuilder builder = new StringBuilder(); foreach (var pair in sorted) { if (pair.Value != null) { string key = pair.Key; string value = pair.Value; builder.Append(AWSSDKUtils.UrlEncode(key, false)); builder.Append("="); builder.Append(AWSSDKUtils.UrlEncode(value, false)); builder.Append("&"); } } string result = builder.ToString(); return (string.IsNullOrEmpty(result) ? string.Empty : result.Substring(0, result.Length - 1)); } private static string GetRequestPayload(IRequest request) { if (request.Content == null) return string.Empty; return Encoding.UTF8.GetString(request.Content, 0, request.Content.Length); } private static string GetSignedHeadersComponent(IRequest request) { StringBuilder builder = new StringBuilder(); builder.Append("SignedHeaders="); bool first = true; foreach (string header in GetHeadersForStringToSign(request)) { if (!first) builder.Append(";"); builder.Append(header); first = false; } return builder.ToString(); } private static List<string> GetHeadersForStringToSign(IRequest request) { List<string> headersToSign = new List<string>(); foreach (var entry in request.Headers) { string key = entry.Key; if (key.StartsWith("x-amz", StringComparison.OrdinalIgnoreCase) || key.Equals("content-encoding", StringComparison.OrdinalIgnoreCase) || key.Equals("host", StringComparison.OrdinalIgnoreCase)) { headersToSign.Add(key); } } headersToSign.Sort(StringComparer.OrdinalIgnoreCase); return headersToSign; } private static string GetCanonicalizedHeadersForStringToSign(IRequest request) { List<string> headersToSign = GetHeadersForStringToSign(request); for (int i = 0; i < headersToSign.Count; i++) { headersToSign[i] = headersToSign[i].ToLowerInvariant(); } SortedDictionary<string,string> sortedHeaderMap = new SortedDictionary<string,string>(); foreach (var entry in request.Headers) { if (headersToSign.Contains(entry.Key.ToLowerInvariant())) { sortedHeaderMap[entry.Key] = entry.Value; } } StringBuilder builder = new StringBuilder(); foreach (var entry in sortedHeaderMap) { builder.Append(entry.Key.ToLowerInvariant()); builder.Append(":"); builder.Append(entry.Value); builder.Append("\n"); } return builder.ToString(); } #endregion } internal class AWS3HTTPSigner : AWS3Signer { public AWS3HTTPSigner() : base(false) { } } }
// Copyright (c) 2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Reflection; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Palaso.UI.WindowsForms.GeckoBasedControls { public static class NativeReplacements { private static Assembly _monoWinFormsAssembly; // internal mono WinForms type private static Type _xplatUIX11; // internal mono WinForms type private static Type _xplatUI; // internal mono WinForms type private static Type _hwnd; // internal mono WinForms type private static Type _X11Keyboard; internal static Assembly MonoWinFormsAssembly { get { if (_monoWinFormsAssembly == null) #pragma warning disable 0618 // Using Obsolete method LoadWithPartialName. _monoWinFormsAssembly = Assembly.LoadWithPartialName("System.Windows.Forms"); #pragma warning restore 0618 return _monoWinFormsAssembly; } } private static Type XplatUIX11 { get { if (_xplatUIX11 == null) _xplatUIX11 = MonoWinFormsAssembly.GetType("System.Windows.Forms.XplatUIX11"); return _xplatUIX11; } } private static Type XplatUI { get { if (_xplatUI == null) _xplatUI = MonoWinFormsAssembly.GetType("System.Windows.Forms.XplatUI"); return _xplatUI; } } private static Type Hwnd { get { if (_hwnd == null) _hwnd = MonoWinFormsAssembly.GetType("System.Windows.Forms.Hwnd"); return _hwnd; } } private static Type X11Keyboard { get { if (_X11Keyboard == null) _X11Keyboard = MonoWinFormsAssembly.GetType("System.Windows.Forms.X11Keyboard"); return _X11Keyboard; } } #region keyboard /// <summary> /// Sets XplatUI.State.ModifierKeys, which is what the Control.ModifierKeys WinForm property returns. /// </summary> public static void SetKeyStateTable(int virtualKey, byte value) { var keyboard = XplatUIX11.GetField("Keyboard", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); if (keyboard == null) return; var key_state_table = X11Keyboard.GetField("key_state_table", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (key_state_table == null) return; var b = (byte[])key_state_table.GetValue(keyboard.GetValue(null)); b[virtualKey] = value; key_state_table.SetValue(keyboard.GetValue(null), b); } #endregion #region GetFocus /// <summary> /// Gets the focus. /// </summary> /// <returns> /// The focus. /// </returns> public static IntPtr GetFocus() { if (Palaso.PlatformUtilities.Platform.IsWindows) return WindowsGetFocus(); return MonoGetFocus(); } /// <summary></summary> [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "GetFocus")] static extern IntPtr WindowsGetFocus(); // internal mono WinForms static instance that traces focus private static FieldInfo _focusWindow; // internal mono Winforms static instance handle to the X server. public static FieldInfo _displayHandle; // internal mono WinForms Hwnd.whole_window internal static FieldInfo _wholeWindow; // internal mono WinForms Hwnd.GetHandleFromWindow internal static MethodInfo _getHandleFromWindow; // internal mono WinForms method Hwnd.ObjectFromHandle internal static MethodInfo _objectFromHandle; /// <summary> /// Gets mono's internal Focused Window Ptr/Handle. /// </summary> public static IntPtr MonoGetFocus() { if (_focusWindow == null) _focusWindow = XplatUIX11.GetField("FocusWindow", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); // Get static field to determine Focused Window. return (IntPtr)_focusWindow.GetValue(null); } /// <summary> /// Get mono's internal display handle to the X server /// </summary> public static IntPtr MonoGetDisplayHandle() { if (_displayHandle == null) _displayHandle = XplatUIX11.GetField("DisplayHandle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); return (IntPtr)_displayHandle.GetValue(null); } private static object GetHwnd(IntPtr handle) { // first call call Hwnd.ObjectFromHandle to get the hwnd. if (_objectFromHandle == null) _objectFromHandle = Hwnd.GetMethod("ObjectFromHandle", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); return _objectFromHandle.Invoke(null, new object[] { handle }); } /// <summary> /// Get an x11 Window Id from a winforms Control handle /// </summary> public static IntPtr MonoGetX11Window(IntPtr handle) { if (handle == IntPtr.Zero) return IntPtr.Zero; object hwnd = GetHwnd(handle); if (_wholeWindow == null) _wholeWindow = Hwnd.GetField("whole_window", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); return (IntPtr)_wholeWindow.GetValue(hwnd); } /// <summary> /// Get a WinForm Control/Handle from an x11 Window Id / windowHandle /// </summary> /// <returns> /// The Control Handle or IntPtr.Zero if window id doesn't represent an winforms control. /// </returns> /// <param name='windowHandle'> /// Window handle / x11 Window Id. /// </param> public static IntPtr MonoGetHandleFromWindowHandle(IntPtr windowHandle) { if (windowHandle == IntPtr.Zero) return IntPtr.Zero; if (_getHandleFromWindow == null) _getHandleFromWindow = Hwnd.GetMethod("GetHandleFromWindow", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); return (IntPtr)_getHandleFromWindow.Invoke(null, new object[] { windowHandle }); } #endregion #region SendSetFocusWindowsMessage public static void SendSetFocusWindowsMessage(Control control, IntPtr fromHandle) { if (control == null) throw new ArgumentNullException("control"); if (control.IsDisposed) throw new ObjectDisposedException("control"); if (Palaso.PlatformUtilities.Platform.IsWindows) NativeSendMessage(control.Handle, WM_SETFOCUS, (int)fromHandle, 0); else { // NativeSendMessage seem to force creation of the control. if (!control.IsHandleCreated) control.CreateControl(); try { control.Focus(); } catch { /* FB36027 */ } } } public const int WM_SETFOCUS = 0x7; [DllImport("user32.dll", EntryPoint = "SendMessage")] static extern int NativeSendMessage( IntPtr hWnd, // handle to destination window uint Msg, // message int wParam, // first message parameter int lParam // second message parameter ); #endregion #region SendMessage private static MethodInfo _sendMessage; /// <summary> /// Please don't use this unless your really have to, and then only if its for sending messages internaly within the application. /// For example sending WM_NCPAINT maybe portable but sending WM_USER + N to another application is definitely not poratable. /// </summary> public static void SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam) { if (Palaso.PlatformUtilities.Platform.IsDotNet) { NativeSendMessage(hWnd, Msg, wParam, lParam); } else { if (_sendMessage == null) _sendMessage = XplatUI.GetMethod("SendMessage", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static, null, new Type[] { typeof(IntPtr), typeof(int), typeof(IntPtr), typeof(IntPtr) }, null); _sendMessage.Invoke(null, new object[] { hWnd, (int)Msg, (IntPtr)wParam, (IntPtr)lParam }); } } #endregion #region X window properties methods public static void SetWmClass(string name, string @class, IntPtr handle) { var a = new NativeX11Methods.XClassHint { res_name = Marshal.StringToCoTaskMemAnsi(name), res_class = Marshal.StringToCoTaskMemAnsi(@class) }; IntPtr classHints = Marshal.AllocCoTaskMem(Marshal.SizeOf(a)); Marshal.StructureToPtr(a, classHints, true); NativeX11Methods.XSetClassHint(NativeReplacements.MonoGetDisplayHandle(), NativeReplacements.MonoGetX11Window(handle), classHints); Marshal.FreeCoTaskMem(a.res_name); Marshal.FreeCoTaskMem(a.res_class); Marshal.FreeCoTaskMem(classHints); } /// <summary> /// Set a winform windows "X group leader" value. /// By default all mono winform applications get the same group leader (WM_HINTS property) /// (use xprop to see a windows WM_HINTS values) /// </summary> public static void SetGroupLeader(IntPtr handle, IntPtr newValue) { var x11Handle = MonoGetX11Window(handle); IntPtr ptr = NativeX11Methods.XGetWMHints(NativeReplacements.MonoGetDisplayHandle(), x11Handle); var wmhints = (NativeX11Methods.XWMHints)Marshal.PtrToStructure(ptr, typeof(NativeX11Methods.XWMHints)); NativeX11Methods.XFree(ptr); wmhints.window_group = NativeReplacements.MonoGetX11Window(newValue); NativeX11Methods.XSetWMHints(NativeReplacements.MonoGetDisplayHandle(), NativeReplacements.MonoGetX11Window(x11Handle), ref wmhints); } #endregion } }
#region Using directives #define USE_TRACING using System; using System.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Xml; #endregion ////////////////////////////////////////////////////////////////////// // <summary>Handles atom:person element.</summary> ////////////////////////////////////////////////////////////////////// namespace Google.GData.Client { ////////////////////////////////////////////////////////////////////// /// <summary>TypeConverter, so that AtomHead shows up in the property pages /// </summary> ////////////////////////////////////////////////////////////////////// [ComVisible(false)] public class AtomPersonConverter : ExpandableObjectConverter { ///<summary>Standard type converter method</summary> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof (AtomPerson)) return true; return base.CanConvertTo(context, destinationType); } ///<summary>Standard type converter method</summary> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { AtomPerson person = value as AtomPerson; if (destinationType == typeof (string) && person != null) { return "Person: " + person.Name; } return base.ConvertTo(context, culture, value, destinationType); } } ////////////////////////////////////////////////////////////////////// /// <summary>enum to describe the different person types /// </summary> ////////////////////////////////////////////////////////////////////// public enum AtomPersonType { /// <summary>is an author</summary> Author, /// <summary>is an contributor</summary> Contributor, /// /// <summary>parsing error</summary> Unknown } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>generic Person object, used for the feed and for the entry /// </summary> ////////////////////////////////////////////////////////////////////// [TypeConverter(typeof (AtomPersonConverter)), Description("Expand to see the person object for the feed/entry.")] public class AtomPerson : AtomBase { /// <summary>email holds the email property as a string</summary> private string email; /// <summary>name holds the Name property as a string</summary> private string name; /// <summary>holds the type for persistence</summary> private readonly AtomPersonType type; /// <summary>link holds an Uri, representing the link atribute</summary> private AtomUri uri; /// <summary>public default constructor, usefull only for property pages</summary> public AtomPerson() { type = AtomPersonType.Author; } ////////////////////////////////////////////////////////////////////// /// <summary>Constructor taking a type to indicate whether person is author or contributor.</summary> /// <param name="type">indicates if author or contributor</param> ////////////////////////////////////////////////////////////////////// public AtomPerson(AtomPersonType type) { this.type = type; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Constructor taking a type to indicate whether person is author or contributor, plus the person's name</summary> /// <param name="type">indicates if author or contributor</param> /// <param name="name">person's name</param> ////////////////////////////////////////////////////////////////////// public AtomPerson(AtomPersonType type, string name) : this(type) { this.name = name; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string Name</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Name { get { return name; } set { Dirty = true; name = value; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public Uri Uri</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public AtomUri Uri { get { if (uri == null) { uri = new AtomUri(""); } return uri; } set { Dirty = true; uri = value; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public Uri Email</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Email { get { return email; } set { Dirty = true; email = value; } } ///////////////////////////////////////////////////////////////////////////// #region Persistence overloads ////////////////////////////////////////////////////////////////////// /// <summary>Just returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public override string XmlName { get { return type == AtomPersonType.Author ? AtomParserNameTable.XmlAuthorElement : AtomParserNameTable.XmlContributorElement; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>saves the inner state of the element</summary> /// <param name="writer">the xmlWriter to save into </param> ////////////////////////////////////////////////////////////////////// protected override void SaveInnerXml(XmlWriter writer) { base.SaveInnerXml(writer); // now save our state... WriteEncodedElementString(writer, BaseNameTable.XmlName, Name); WriteEncodedElementString(writer, AtomParserNameTable.XmlEmailElement, Email); WriteEncodedElementString(writer, AtomParserNameTable.XmlUriElement, Uri); } ////////////////////////////////////////////////////////////////////// /// <summary>figures out if this object should be persisted</summary> /// <returns> true, if it's worth saving</returns> ////////////////////////////////////////////////////////////////////// public override bool ShouldBePersisted() { if (!base.ShouldBePersisted()) { if (Utilities.IsPersistable(name)) { return true; } if (Utilities.IsPersistable(email)) { return true; } if (Utilities.IsPersistable(uri)) { return true; } return false; } return true; } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// #endregion } ///////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.ComponentModel; using System.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [Export(typeof(VisualStudioDiagnosticListTable))] internal class VisualStudioDiagnosticListTable : VisualStudioBaseDiagnosticListTable { internal const string IdentifierString = nameof(VisualStudioDiagnosticListTable); private readonly IErrorList _errorList; private readonly LiveTableDataSource _liveTableSource; private readonly BuildTableDataSource _buildTableSource; [ImportingConstructor] public VisualStudioDiagnosticListTable( SVsServiceProvider serviceProvider, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, ExternalErrorDiagnosticUpdateSource errorSource, ITableManagerProvider provider) : this(serviceProvider, (Workspace)workspace, diagnosticService, errorSource, provider) { ConnectWorkspaceEvents(); _errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList; if (_errorList == null) { AddInitialTableSource(workspace.CurrentSolution, _liveTableSource); return; } _errorList.PropertyChanged += OnErrorListPropertyChanged; AddInitialTableSource(workspace.CurrentSolution, GetCurrentDataSource()); } private ITableDataSource GetCurrentDataSource() { if (_errorList == null) { return _liveTableSource; } return _errorList.AreOtherErrorSourceEntriesShown ? (ITableDataSource)_liveTableSource : _buildTableSource; } /// this is for test only internal VisualStudioDiagnosticListTable(Workspace workspace, IDiagnosticService diagnosticService, ITableManagerProvider provider) : this(null, workspace, diagnosticService, null, provider) { AddInitialTableSource(workspace.CurrentSolution, _liveTableSource); } private VisualStudioDiagnosticListTable( SVsServiceProvider serviceProvider, Workspace workspace, IDiagnosticService diagnosticService, ExternalErrorDiagnosticUpdateSource errorSource, ITableManagerProvider provider) : base(serviceProvider, workspace, diagnosticService, provider) { _liveTableSource = new LiveTableDataSource(serviceProvider, workspace, diagnosticService, IdentifierString); _buildTableSource = new BuildTableDataSource(workspace, errorSource); } protected override void AddTableSourceIfNecessary(Solution solution) { if (solution.ProjectIds.Count == 0) { return; } RemoveTableSourcesIfNecessary(); AddTableSource(GetCurrentDataSource()); } protected override void RemoveTableSourceIfNecessary(Solution solution) { if (solution.ProjectIds.Count > 0) { return; } RemoveTableSourcesIfNecessary(); } private void RemoveTableSourcesIfNecessary() { RemoveTableSourceIfNecessary(_buildTableSource); RemoveTableSourceIfNecessary(_liveTableSource); } private void RemoveTableSourceIfNecessary(ITableDataSource source) { if (!this.TableManager.Sources.Any(s => s == source)) { return; } this.TableManager.RemoveSource(source); } protected override void ShutdownSource() { _liveTableSource.Shutdown(); _buildTableSource.Shutdown(); } private void OnErrorListPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(IErrorList.AreOtherErrorSourceEntriesShown)) { AddTableSourceIfNecessary(this.Workspace.CurrentSolution); } } private class BuildTableDataSource : AbstractTableDataSource<DiagnosticData> { private readonly Workspace _workspace; private readonly ExternalErrorDiagnosticUpdateSource _buildErrorSource; public BuildTableDataSource(Workspace workspace, ExternalErrorDiagnosticUpdateSource errorSource) { _workspace = workspace; _buildErrorSource = errorSource; ConnectToBuildUpdateSource(errorSource); } private void ConnectToBuildUpdateSource(ExternalErrorDiagnosticUpdateSource errorSource) { if (errorSource == null) { return; } SetStableState(errorSource.IsInProgress); errorSource.BuildStarted += OnBuildStarted; } private void OnBuildStarted(object sender, bool started) { SetStableState(started); if (!started) { OnDataAddedOrChanged(this, _buildErrorSource.GetBuildErrors().Length); } } private void SetStableState(bool started) { IsStable = !started; ChangeStableState(IsStable); } public override string DisplayName => ServicesVSResources.BuildTableSourceName; public override string SourceTypeIdentifier => StandardTableDataSources.ErrorTableDataSource; public override string Identifier => IdentifierString; protected void OnDataAddedOrChanged(object key, int itemCount) { // reuse factory. it is okay to re-use factory since we make sure we remove the factory before // adding it back bool newFactory = false; ImmutableArray<SubscriptionWithoutLock> snapshot; AbstractTableEntriesFactory<DiagnosticData> factory; lock (Gate) { snapshot = Subscriptions; if (!Map.TryGetValue(key, out factory)) { factory = new TableEntriesFactory(this, _workspace); Map.Add(key, factory); newFactory = true; } } factory.OnUpdated(itemCount); for (var i = 0; i < snapshot.Length; i++) { snapshot[i].AddOrUpdate(factory, newFactory); } } private class TableEntriesFactory : AbstractTableEntriesFactory<DiagnosticData> { private readonly BuildTableDataSource _source; private readonly Workspace _workspace; public TableEntriesFactory(BuildTableDataSource source, Workspace workspace) : base(source) { _source = source; _workspace = workspace; } protected override ImmutableArray<DiagnosticData> GetItems() { return _source._buildErrorSource.GetBuildErrors(); } protected override ImmutableArray<ITrackingPoint> GetTrackingPoints(ImmutableArray<DiagnosticData> items) { return ImmutableArray<ITrackingPoint>.Empty; } protected override AbstractTableEntriesSnapshot<DiagnosticData> CreateSnapshot( int version, ImmutableArray<DiagnosticData> items, ImmutableArray<ITrackingPoint> trackingPoints) { return new TableEntriesSnapshot(this, version, items); } private class TableEntriesSnapshot : AbstractTableEntriesSnapshot<DiagnosticData> { private readonly TableEntriesFactory _factory; public TableEntriesSnapshot( TableEntriesFactory factory, int version, ImmutableArray<DiagnosticData> items) : base(version, Guid.Empty, items, ImmutableArray<ITrackingPoint>.Empty) { _factory = factory; } public override bool TryGetValue(int index, string columnName, out object content) { // REVIEW: this method is too-chatty to make async, but otherwise, how one can implement it async? // also, what is cancellation mechanism? var item = GetItem(index); if (item == null) { content = null; return false; } switch (columnName) { case StandardTableKeyNames.ErrorRank: content = WellKnownDiagnosticTags.Build; return true; case StandardTableKeyNames.ErrorSeverity: content = GetErrorCategory(item.Severity); return true; case StandardTableKeyNames.ErrorCode: content = item.Id; return true; case StandardTableKeyNames.ErrorCodeToolTip: content = GetHelpLinkToolTipText(item); return content != null; case StandardTableKeyNames.HelpLink: content = GetHelpLink(item); return content != null; case StandardTableKeyNames.ErrorCategory: content = item.Category; return true; case StandardTableKeyNames.ErrorSource: content = ErrorSource.Build; return true; case StandardTableKeyNames.BuildTool: content = PredefinedBuildTools.Build; return true; case StandardTableKeyNames.Text: content = item.Message; return true; case StandardTableKeyNames.DocumentName: content = GetFileName(item.DataLocation?.OriginalFilePath, item.DataLocation?.MappedFilePath); return true; case StandardTableKeyNames.Line: content = item.DataLocation?.MappedStartLine ?? 0; return true; case StandardTableKeyNames.Column: content = item.DataLocation?.MappedStartColumn ?? 0; return true; case StandardTableKeyNames.ProjectName: content = GetProjectName(_factory._workspace, item.ProjectId); return content != null; case StandardTableKeyNames.ProjectGuid: var guid = GetProjectGuid(_factory._workspace, item.ProjectId); content = guid; return guid != Guid.Empty; default: content = null; return false; } } public override bool TryNavigateTo(int index, bool previewTab) { var item = GetItem(index); if (item == null) { return false; } // this item is not navigatable if (item.DocumentId == null) { return false; } return TryNavigateTo(_factory._workspace, item.DocumentId, item.DataLocation?.OriginalStartLine ?? 0, item.DataLocation?.OriginalStartColumn ?? 0, previewTab); } protected override bool IsEquivalent(DiagnosticData item1, DiagnosticData item2) { // everything same except location return item1.Id == item2.Id && item1.ProjectId == item2.ProjectId && item1.DocumentId == item2.DocumentId && item1.Category == item2.Category && item1.Severity == item2.Severity && item1.WarningLevel == item2.WarningLevel && item1.Message == item2.Message; } } } } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using Jace; using System.Threading; using System.Runtime.InteropServices; using System.Windows.Interop; using SpatialAnalysis.Visualization; using SpatialAnalysis.Data; using SpatialAnalysis.Data.Visualization; using SpatialAnalysis.Miscellaneous; namespace SpatialAnalysis.Data.CostFormulaSet { /// <summary> /// Interaction logic for TextFormulaSet.xaml /// </summary> public partial class TextFormulaSet : Window { #region Hiding the close button private const int GWL_STYLE = -16; private const int WS_SYSMENU = 0x80000; [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); //Hiding the close button private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e) { var hwnd = new WindowInteropHelper(this).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); } #endregion /// <summary> /// Gets or sets the cost function. /// </summary> /// <value>The cost function.</value> public CalculateCost CostFunction { get; set; } private double _min, _max; OSMDocument _host; SpatialDataField _spatialDataField; /// <summary> /// Gets or sets the linked parameters to the cost function. /// </summary> /// <value>The linked parameters.</value> public HashSet<Parameter> LinkedParameters { get; set; } /// <summary> /// Initializes a new instance of the <see cref="TextFormulaSet"/> class. /// </summary> /// <param name="host">The main document to which this class belongs.</param> /// <param name="spatialDataField">The spatial data field.</param> public TextFormulaSet(OSMDocument host, SpatialDataField spatialDataField) { InitializeComponent(); this._host = host; this._min = spatialDataField.Min; this._max = spatialDataField.Max; this._test.Click += _test_Click; this.main.TextChanged += main_TextChanged; this.Loaded += Window_Loaded; this._insetParameter.Click += new RoutedEventHandler(_insetParameter_Click); this.main.Text = spatialDataField.TextFormula; this._spatialDataField = spatialDataField; this.LinkedParameters = new HashSet<Parameter>(); } void _insetParameter_Click(object sender, RoutedEventArgs e) { ParameterSetting parameterSetting = new ParameterSetting(this._host, true); parameterSetting.Owner = this._host; parameterSetting.ShowDialog(); if (string.IsNullOrEmpty(parameterSetting.ParameterName)) { return; } if (this.main.SelectedText == null) { this.main.Text = this.main.Text.Insert(this.main.CaretIndex, parameterSetting.ParameterName); } else { this.main.SelectedText = parameterSetting.ParameterName; this.main.CaretIndex += this.main.SelectedText.Length; this.main.SelectionLength = 0; } } void _test_Click(object sender, RoutedEventArgs e) { this._graphs._graphsHost.Clear(); this.LinkedParameters.Clear(); string textFormula = (string)this.main.Text.Clone(); foreach (var item in this._host.Parameters) { if (textFormula.Contains(item.Key)) { textFormula = textFormula.Replace(item.Key, item.Value.Value.ToString()); this.LinkedParameters.Add(item.Value); } } try { CalculationEngine engine = new CalculationEngine(); Func<double, double> func = (Func<double, double>)engine.Formula(textFormula) .Parameter("X", Jace.DataType.FloatingPoint) .Result(Jace.DataType.FloatingPoint) .Build(); this.CostFunction = new CalculateCost(func); } catch (Exception error) { this.CostFunction = null; MessageBox.Show("Failed to parse the formula!\n\t" + error.Report()); return; } PointCollection points = new PointCollection(); int num = 50; try { double yMax = double.NegativeInfinity; double yMin = double.PositiveInfinity; double d = (this._max - this._min) / num; double t = this._min; for (int i = 0; i <= num; i++) { double yVal = this.CostFunction(t); if (yVal == double.MaxValue || yVal == double.MinValue || double.IsNaN(yVal) || double.IsInfinity(yVal) || double.IsNegativeInfinity(yVal) || double.IsPositiveInfinity(yVal)) { throw new ArgumentException(yVal.ToString() + " is not a valid output for the cost function"); } Point pnt = new Point(t, yVal); t += d; points.Add(pnt); yMax = (yMax < yVal) ? yVal : yMax; yMin = (yMin > yVal) ? yVal : yMin; } this._graphs._yMax.Text = yMax.ToString(); this._graphs._yMin.Text = yMin.ToString(); this._graphs._xMin.Text = this._min.ToString(); this._graphs._xMax.Text = this._max.ToString(); if (yMax - yMin < .01) { throw new ArgumentException(string.Format("f(x) = {0}\n\tWPF Charts does not support drawing it!", ((yMax + yMin) / 2).ToString())); } this._graphs._graphsHost.AddTrendLine(points); } catch (Exception error) { MessageBox.Show(error.Report()); return; } this._ok.IsEnabled = true; } private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { System.Diagnostics.Process.Start("https://github.com/pieterderycke/Jace/wiki"); } private void TextBlock_MouseEnter(object sender, MouseEventArgs e) { this.Cursor = Cursors.Hand; } private void TextBlock_MouseLeave(object sender, MouseEventArgs e) { this.Cursor = Cursors.Arrow; } private void _ok_Click(object sender, RoutedEventArgs e) { this.Close(); } private void main_TextChanged(object sender, TextChangedEventArgs e) { this._ok.IsEnabled = false; } private void MenuItem_Click(object sender, RoutedEventArgs e) { double dpi = 96; GetNumber getNumber0 = new GetNumber("Set Image Resolution", "The graph will be exported in PGN format. Setting a heigh resolution value may crash this app.", dpi); getNumber0.ShowDialog(); dpi = getNumber0.NumberValue; getNumber0 = null; Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Title = "Save the Scene to PNG Image format"; dlg.DefaultExt = ".png"; dlg.Filter = "PNG documents (.png)|*.png"; Nullable<bool> result = dlg.ShowDialog(this); string fileAddress = ""; if (result == true) { fileAddress = dlg.FileName; } else { return; } Rect bounds = VisualTreeHelper.GetDescendantBounds(this._graphs); RenderTargetBitmap main_rtb = new RenderTargetBitmap((int)(bounds.Width * dpi / 96), (int)(bounds.Height * dpi / 96), dpi, dpi, System.Windows.Media.PixelFormats.Default); DrawingVisual dvFloorScene = new DrawingVisual(); using (DrawingContext dc = dvFloorScene.RenderOpen()) { VisualBrush vb = new VisualBrush(this._graphs); dc.DrawRectangle(vb, null, bounds); } main_rtb.Render(dvFloorScene); BitmapEncoder pngEncoder = new PngBitmapEncoder(); pngEncoder.Frames.Add(BitmapFrame.Create(main_rtb)); try { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { pngEncoder.Save(ms); ms.Close(); System.IO.File.WriteAllBytes(fileAddress, ms.ToArray()); } } catch (Exception err) { MessageBox.Show(err.Report(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } } }
using System; using System.Collections; using System.Collections.Generic; using Server; using Server.Guilds; using Server.Items; using Server.Misc; using Server.Regions; using Server.Spells; namespace Server.Multis { public enum HousePlacementResult { Valid, BadRegion, BadLand, BadStatic, BadItem, NoSurface, BadRegionHidden, BadRegionTemp, InvalidCastleKeep, BadRegionRaffle } public class HousePlacement { private const int YardSize = 5; // Any land tile which matches one of these ID numbers is considered a road and cannot be placed over. private static int[] m_RoadIDs = new int[] { 0x0071, 0x0078, 0x00E8, 0x00EB, 0x07AE, 0x07B1, 0x3FF4, 0x3FF4, 0x3FF8, 0x3FFB, 0x0442, 0x0479, // Sand stones 0x0501, 0x0510, // Sand stones 0x0009, 0x0015, // Furrows 0x0150, 0x015C // Furrows }; public static HousePlacementResult Check( Mobile from, int multiID, Point3D center, out ArrayList toMove ) { // If this spot is considered valid, every item and mobile in this list will be moved under the house sign toMove = new ArrayList(); Map map = from.Map; if ( map == null || map == Map.Internal ) return HousePlacementResult.BadLand; // A house cannot go here if ( from.AccessLevel >= AccessLevel.GameMaster ) return HousePlacementResult.Valid; // Staff can place anywhere if ( map == Map.Ilshenar || SpellHelper.IsFeluccaT2A( map, center ) ) return HousePlacementResult.BadRegion; // No houses in Ilshenar/T2A if ( map == Map.Malas && ( multiID == 0x007C || multiID == 0x007E ) ) return HousePlacementResult.InvalidCastleKeep; NoHousingRegion noHousingRegion = (NoHousingRegion) Region.Find( center, map ).GetRegion( typeof( NoHousingRegion ) ); if ( noHousingRegion != null ) return HousePlacementResult.BadRegion; // This holds data describing the internal structure of the house MultiComponentList mcl = MultiData.GetComponents( multiID ); if ( multiID >= 0x13EC && multiID < 0x1D00 ) HouseFoundation.AddStairsTo( ref mcl ); // this is a AOS house, add the stairs // Location of the nortwest-most corner of the house Point3D start = new Point3D( center.X + mcl.Min.X, center.Y + mcl.Min.Y, center.Z ); // These are storage lists. They hold items and mobiles found in the map for further processing List<Item> items = new List<Item>(); List<Mobile> mobiles = new List<Mobile>(); // These are also storage lists. They hold location values indicating the yard and border locations. List<Point2D> yard = new List<Point2D>(), borders = new List<Point2D>(); /* RULES: * * 1) All tiles which are around the -outside- of the foundation must not have anything impassable. * 2) No impassable object or land tile may come in direct contact with any part of the house. * 3) Five tiles from the front and back of the house must be completely clear of all house tiles. * 4) The foundation must rest flatly on a surface. Any bumps around the foundation are not allowed. * 5) No foundation tile may reside over terrain which is viewed as a road. */ for ( int x = 0; x < mcl.Width; ++x ) { for ( int y = 0; y < mcl.Height; ++y ) { int tileX = start.X + x; int tileY = start.Y + y; StaticTile[] addTiles = mcl.Tiles[x][y]; if ( addTiles.Length == 0 ) continue; // There are no tiles here, continue checking somewhere else Point3D testPoint = new Point3D( tileX, tileY, center.Z ); Region reg = Region.Find( testPoint, map ); if ( !reg.AllowHousing( from, testPoint ) ) // Cannot place houses in dungeons, towns, treasure map areas etc { if ( reg.IsPartOf( typeof( TempNoHousingRegion ) ) ) return HousePlacementResult.BadRegionTemp; if (reg.IsPartOf(typeof(TreasureRegion)) || reg.IsPartOf(typeof(HouseRegion))) return HousePlacementResult.BadRegionHidden; if (reg.IsPartOf(typeof(HouseRaffleRegion))) return HousePlacementResult.BadRegionRaffle; return HousePlacementResult.BadRegion; } LandTile landTile = map.Tiles.GetLandTile( tileX, tileY ); int landID = landTile.ID & TileData.MaxLandValue; StaticTile[] oldTiles = map.Tiles.GetStaticTiles( tileX, tileY, true ); Sector sector = map.GetSector( tileX, tileY ); items.Clear(); for ( int i = 0; i < sector.Items.Count; ++i ) { Item item = sector.Items[i]; if ( item.Visible && item.X == tileX && item.Y == tileY ) items.Add( item ); } mobiles.Clear(); for ( int i = 0; i < sector.Mobiles.Count; ++i ) { Mobile m = sector.Mobiles[i]; if ( m.X == tileX && m.Y == tileY ) mobiles.Add( m ); } int landStartZ = 0, landAvgZ = 0, landTopZ = 0; map.GetAverageZ( tileX, tileY, ref landStartZ, ref landAvgZ, ref landTopZ ); bool hasFoundation = false; for ( int i = 0; i < addTiles.Length; ++i ) { StaticTile addTile = addTiles[i]; if ( addTile.ID == 0x1 ) // Nodraw continue; TileFlag addTileFlags = TileData.ItemTable[addTile.ID & TileData.MaxItemValue].Flags; bool isFoundation = ( addTile.Z == 0 && (addTileFlags & TileFlag.Wall) != 0 ); bool hasSurface = false; if ( isFoundation ) hasFoundation = true; int addTileZ = center.Z + addTile.Z; int addTileTop = addTileZ + addTile.Height; if ( (addTileFlags & TileFlag.Surface) != 0 ) addTileTop += 16; if ( addTileTop > landStartZ && landAvgZ > addTileZ ) return HousePlacementResult.BadLand; // Broke rule #2 if ( isFoundation && ((TileData.LandTable[landTile.ID & TileData.MaxLandValue].Flags & TileFlag.Impassable) == 0) && landAvgZ == center.Z ) hasSurface = true; for ( int j = 0; j < oldTiles.Length; ++j ) { StaticTile oldTile = oldTiles[j]; ItemData id = TileData.ItemTable[oldTile.ID & TileData.MaxItemValue]; if ( (id.Impassable || (id.Surface && (id.Flags & TileFlag.Background) == 0)) && addTileTop > oldTile.Z && (oldTile.Z + id.CalcHeight) > addTileZ ) return HousePlacementResult.BadStatic; // Broke rule #2 /*else if ( isFoundation && !hasSurface && (id.Flags & TileFlag.Surface) != 0 && (oldTile.Z + id.CalcHeight) == center.Z ) hasSurface = true;*/ } for ( int j = 0; j < items.Count; ++j ) { Item item = items[j]; ItemData id = item.ItemData; if ( addTileTop > item.Z && (item.Z + id.CalcHeight) > addTileZ ) { if ( item.Movable ) toMove.Add( item ); else if ( (id.Impassable || (id.Surface && (id.Flags & TileFlag.Background) == 0)) ) return HousePlacementResult.BadItem; // Broke rule #2 } /*else if ( isFoundation && !hasSurface && (id.Flags & TileFlag.Surface) != 0 && (item.Z + id.CalcHeight) == center.Z ) { hasSurface = true; }*/ } if ( isFoundation && !hasSurface ) return HousePlacementResult.NoSurface; // Broke rule #4 for ( int j = 0; j < mobiles.Count; ++j ) { Mobile m = mobiles[j]; if ( addTileTop > m.Z && (m.Z + 16) > addTileZ ) toMove.Add( m ); } } for ( int i = 0; i < m_RoadIDs.Length; i += 2 ) { if ( landID >= m_RoadIDs[i] && landID <= m_RoadIDs[i + 1] ) return HousePlacementResult.BadLand; // Broke rule #5 } if ( hasFoundation ) { for ( int xOffset = -1; xOffset <= 1; ++xOffset ) { for ( int yOffset = -YardSize; yOffset <= YardSize; ++yOffset ) { Point2D yardPoint = new Point2D( tileX + xOffset, tileY + yOffset ); if ( !yard.Contains( yardPoint ) ) yard.Add( yardPoint ); } } for ( int xOffset = -1; xOffset <= 1; ++xOffset ) { for ( int yOffset = -1; yOffset <= 1; ++yOffset ) { if ( xOffset == 0 && yOffset == 0 ) continue; // To ease this rule, we will not add to the border list if the tile here is under a base floor (z<=8) int vx = x + xOffset; int vy = y + yOffset; if ( vx >= 0 && vx < mcl.Width && vy >= 0 && vy < mcl.Height ) { StaticTile[] breakTiles = mcl.Tiles[vx][vy]; bool shouldBreak = false; for ( int i = 0; !shouldBreak && i < breakTiles.Length; ++i ) { StaticTile breakTile = breakTiles[i]; if ( breakTile.Height == 0 && breakTile.Z <= 8 && TileData.ItemTable[breakTile.ID & TileData.MaxItemValue].Surface ) shouldBreak = true; } if ( shouldBreak ) continue; } Point2D borderPoint = new Point2D( tileX + xOffset, tileY + yOffset ); if ( !borders.Contains( borderPoint ) ) borders.Add( borderPoint ); } } } } } for ( int i = 0; i < borders.Count; ++i ) { Point2D borderPoint = borders[i]; LandTile landTile = map.Tiles.GetLandTile( borderPoint.X, borderPoint.Y ); int landID = landTile.ID & TileData.MaxLandValue; if ( (TileData.LandTable[landID].Flags & TileFlag.Impassable) != 0 ) return HousePlacementResult.BadLand; for ( int j = 0; j < m_RoadIDs.Length; j += 2 ) { if ( landID >= m_RoadIDs[j] && landID <= m_RoadIDs[j + 1] ) return HousePlacementResult.BadLand; // Broke rule #5 } StaticTile[] tiles = map.Tiles.GetStaticTiles( borderPoint.X, borderPoint.Y, true ); for ( int j = 0; j < tiles.Length; ++j ) { StaticTile tile = tiles[j]; ItemData id = TileData.ItemTable[tile.ID & TileData.MaxItemValue]; if ( id.Impassable || (id.Surface && (id.Flags & TileFlag.Background) == 0 && (tile.Z + id.CalcHeight) > (center.Z + 2)) ) return HousePlacementResult.BadStatic; // Broke rule #1 } Sector sector = map.GetSector( borderPoint.X, borderPoint.Y ); List<Item> sectorItems = sector.Items; for ( int j = 0; j < sectorItems.Count; ++j ) { Item item = sectorItems[j]; if ( item.X != borderPoint.X || item.Y != borderPoint.Y || item.Movable ) continue; ItemData id = item.ItemData; if ( id.Impassable || (id.Surface && (id.Flags & TileFlag.Background) == 0 && (item.Z + id.CalcHeight) > (center.Z + 2)) ) return HousePlacementResult.BadItem; // Broke rule #1 } } List<Sector> _sectors = new List<Sector>(); List<BaseHouse> _houses = new List<BaseHouse>(); for ( int i = 0; i < yard.Count; i++ ) { Sector sector = map.GetSector( yard[i] ); if ( !_sectors.Contains( sector ) ) { _sectors.Add( sector ); if ( sector.Multis != null ) { for ( int j = 0; j < sector.Multis.Count; j++ ) { if ( sector.Multis[j] is BaseHouse ) { BaseHouse _house = (BaseHouse)sector.Multis[j]; if ( !_houses.Contains( _house ) ) { _houses.Add( _house ); } } } } } } for ( int i = 0; i < yard.Count; ++i ) { foreach ( BaseHouse b in _houses ) { if ( b.Contains( yard[i] ) ) return HousePlacementResult.BadStatic; // Broke rule #3 } /*Point2D yardPoint = yard[i]; IPooledEnumerable eable = map.GetMultiTilesAt( yardPoint.X, yardPoint.Y ); foreach ( StaticTile[] tile in eable ) { for ( int j = 0; j < tile.Length; ++j ) { if ( (TileData.ItemTable[tile[j].ID & TileData.MaxItemValue].Flags & (TileFlag.Impassable | TileFlag.Surface)) != 0 ) { eable.Free(); return HousePlacementResult.BadStatic; // Broke rule #3 } } } eable.Free();*/ } return HousePlacementResult.Valid; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// CallSummaryResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Insights.V1.Call { public class CallSummaryResource : Resource { public sealed class CallTypeEnum : StringEnum { private CallTypeEnum(string value) : base(value) {} public CallTypeEnum() {} public static implicit operator CallTypeEnum(string value) { return new CallTypeEnum(value); } public static readonly CallTypeEnum Carrier = new CallTypeEnum("carrier"); public static readonly CallTypeEnum Sip = new CallTypeEnum("sip"); public static readonly CallTypeEnum Trunking = new CallTypeEnum("trunking"); public static readonly CallTypeEnum Client = new CallTypeEnum("client"); } public sealed class CallStateEnum : StringEnum { private CallStateEnum(string value) : base(value) {} public CallStateEnum() {} public static implicit operator CallStateEnum(string value) { return new CallStateEnum(value); } public static readonly CallStateEnum Ringing = new CallStateEnum("ringing"); public static readonly CallStateEnum Completed = new CallStateEnum("completed"); public static readonly CallStateEnum Busy = new CallStateEnum("busy"); public static readonly CallStateEnum Fail = new CallStateEnum("fail"); public static readonly CallStateEnum Noanswer = new CallStateEnum("noanswer"); public static readonly CallStateEnum Canceled = new CallStateEnum("canceled"); public static readonly CallStateEnum Answered = new CallStateEnum("answered"); public static readonly CallStateEnum Undialed = new CallStateEnum("undialed"); } public sealed class ProcessingStateEnum : StringEnum { private ProcessingStateEnum(string value) : base(value) {} public ProcessingStateEnum() {} public static implicit operator ProcessingStateEnum(string value) { return new ProcessingStateEnum(value); } public static readonly ProcessingStateEnum Complete = new ProcessingStateEnum("complete"); public static readonly ProcessingStateEnum Partial = new ProcessingStateEnum("partial"); } private static Request BuildFetchRequest(FetchCallSummaryOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Insights, "/v1/Voice/" + options.PathCallSid + "/Summary", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch CallSummary parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of CallSummary </returns> public static CallSummaryResource Fetch(FetchCallSummaryOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch CallSummary parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of CallSummary </returns> public static async System.Threading.Tasks.Task<CallSummaryResource> FetchAsync(FetchCallSummaryOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathCallSid"> The call_sid </param> /// <param name="processingState"> The processing_state </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of CallSummary </returns> public static CallSummaryResource Fetch(string pathCallSid, CallSummaryResource.ProcessingStateEnum processingState = null, ITwilioRestClient client = null) { var options = new FetchCallSummaryOptions(pathCallSid){ProcessingState = processingState}; return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathCallSid"> The call_sid </param> /// <param name="processingState"> The processing_state </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of CallSummary </returns> public static async System.Threading.Tasks.Task<CallSummaryResource> FetchAsync(string pathCallSid, CallSummaryResource.ProcessingStateEnum processingState = null, ITwilioRestClient client = null) { var options = new FetchCallSummaryOptions(pathCallSid){ProcessingState = processingState}; return await FetchAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a CallSummaryResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> CallSummaryResource object represented by the provided JSON </returns> public static CallSummaryResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<CallSummaryResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The account_sid /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The call_sid /// </summary> [JsonProperty("call_sid")] public string CallSid { get; private set; } /// <summary> /// The call_type /// </summary> [JsonProperty("call_type")] [JsonConverter(typeof(StringEnumConverter))] public CallSummaryResource.CallTypeEnum CallType { get; private set; } /// <summary> /// The call_state /// </summary> [JsonProperty("call_state")] [JsonConverter(typeof(StringEnumConverter))] public CallSummaryResource.CallStateEnum CallState { get; private set; } /// <summary> /// The processing_state /// </summary> [JsonProperty("processing_state")] [JsonConverter(typeof(StringEnumConverter))] public CallSummaryResource.ProcessingStateEnum ProcessingState { get; private set; } /// <summary> /// The created_time /// </summary> [JsonProperty("created_time")] public DateTime? CreatedTime { get; private set; } /// <summary> /// The start_time /// </summary> [JsonProperty("start_time")] public DateTime? StartTime { get; private set; } /// <summary> /// The end_time /// </summary> [JsonProperty("end_time")] public DateTime? EndTime { get; private set; } /// <summary> /// The duration /// </summary> [JsonProperty("duration")] public int? Duration { get; private set; } /// <summary> /// The connect_duration /// </summary> [JsonProperty("connect_duration")] public int? ConnectDuration { get; private set; } /// <summary> /// The from /// </summary> [JsonProperty("from")] public object From { get; private set; } /// <summary> /// The to /// </summary> [JsonProperty("to")] public object To { get; private set; } /// <summary> /// The carrier_edge /// </summary> [JsonProperty("carrier_edge")] public object CarrierEdge { get; private set; } /// <summary> /// The client_edge /// </summary> [JsonProperty("client_edge")] public object ClientEdge { get; private set; } /// <summary> /// The sdk_edge /// </summary> [JsonProperty("sdk_edge")] public object SdkEdge { get; private set; } /// <summary> /// The sip_edge /// </summary> [JsonProperty("sip_edge")] public object SipEdge { get; private set; } /// <summary> /// The tags /// </summary> [JsonProperty("tags")] public List<string> Tags { get; private set; } /// <summary> /// The url /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The attributes /// </summary> [JsonProperty("attributes")] public object Attributes { get; private set; } /// <summary> /// The properties /// </summary> [JsonProperty("properties")] public object Properties { get; private set; } /// <summary> /// The trust /// </summary> [JsonProperty("trust")] public object Trust { get; private set; } private CallSummaryResource() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; using Xunit.Sdk; namespace System { public static class AssertExtensions { private static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework"); public static void Throws<T>(Action action, string message) where T : Exception { Assert.Equal(Assert.Throws<T>(action).Message, message); } public static void Throws<T>(string netCoreParamName, string netFxParamName, Action action) where T : ArgumentException { T exception = Assert.Throws<T>(action); if (netFxParamName == null && IsFullFramework) { // Param name varies between NETFX versions -- skip checking it return; } string expectedParamName = IsFullFramework ? netFxParamName : netCoreParamName; if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) Assert.Equal(expectedParamName, exception.ParamName); } public static T Throws<T>(string paramName, Action action) where T : ArgumentException { T exception = Assert.Throws<T>(action); if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) Assert.Equal(paramName, exception.ParamName); return exception; } public static T Throws<T>(string paramName, Func<object> testCode) where T : ArgumentException { T exception = Assert.Throws<T>(testCode); if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) Assert.Equal(paramName, exception.ParamName); return exception; } public static async Task<T> ThrowsAsync<T>(string paramName, Func<Task> testCode) where T : ArgumentException { T exception = await Assert.ThrowsAsync<T>(testCode); if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) Assert.Equal(paramName, exception.ParamName); return exception; } public static void Throws<TNetCoreExceptionType, TNetFxExceptionType>(string paramName, Action action) where TNetCoreExceptionType : ArgumentException where TNetFxExceptionType : ArgumentException { Throws<TNetCoreExceptionType, TNetFxExceptionType>(paramName, paramName, action); } public static void Throws<TNetCoreExceptionType, TNetFxExceptionType>(string netCoreParamName, string netFxParamName, Action action) where TNetCoreExceptionType : ArgumentException where TNetFxExceptionType : ArgumentException { if (IsFullFramework) { Throws<TNetFxExceptionType>(netFxParamName, action); } else { Throws<TNetCoreExceptionType>(netCoreParamName, action); } } public static void ThrowsAny(Type firstExceptionType, Type secondExceptionType, Action action) { try { action(); } catch (Exception e) { if (e.GetType().Equals(firstExceptionType) || e.GetType().Equals(secondExceptionType)) { return; } throw new XunitException($"Expected: ({firstExceptionType}) or ({secondExceptionType}) -> Actual: ({e.GetType()})"); } throw new XunitException("AssertExtensions.ThrowsAny<firstExceptionType, secondExceptionType> didn't throw any exception"); } public static void ThrowsAny<TFirstExceptionType, TSecondExceptionType>(Action action) where TFirstExceptionType : Exception where TSecondExceptionType : Exception { ThrowsAny(typeof(TFirstExceptionType), typeof(TSecondExceptionType), action); } public static void ThrowsIf<T>(bool condition, Action action) where T : Exception { if (condition) { Assert.Throws<T>(action); } else { action(); } } private static string AddOptionalUserMessage(string message, string userMessage) { if (userMessage == null) return message; else return $"{message} {userMessage}"; } /// <summary> /// Validate that a given value is greater than another value. /// </summary> /// <param name="actual">The value that should be greater than <paramref name="greaterThan"/>.</param> /// <param name="greaterThan">The value that <paramref name="actual"/> should be greater than.</param> public static void GreaterThan<T>(T actual, T greaterThan, string userMessage = null) where T : IComparable { if (actual == null) throw new XunitException( greaterThan == null ? AddOptionalUserMessage($"Expected: <null> to be greater than <null>.", userMessage) : AddOptionalUserMessage($"Expected: <null> to be greater than {greaterThan}.", userMessage)); if (actual.CompareTo(greaterThan) <= 0) throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be greater than {greaterThan}", userMessage)); } /// <summary> /// Validate that a given value is less than another value. /// </summary> /// <param name="actual">The value that should be less than <paramref name="lessThan"/>.</param> /// <param name="lessThan">The value that <paramref name="actual"/> should be less than.</param> public static void LessThan<T>(T actual, T lessThan, string userMessage = null) where T : IComparable { if (actual == null) { if (lessThan == null) { throw new XunitException(AddOptionalUserMessage($"Expected: <null> to be less than <null>.", userMessage)); } else { // Null is always less than non-null return; } } if (actual.CompareTo(lessThan) >= 0) throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be less than {lessThan}", userMessage)); } /// <summary> /// Validate that a given value is less than or equal to another value. /// </summary> /// <param name="actual">The value that should be less than or equal to <paramref name="lessThanOrEqualTo"/></param> /// <param name="lessThanOrEqualTo">The value that <paramref name="actual"/> should be less than or equal to.</param> public static void LessThanOrEqualTo<T>(T actual, T lessThanOrEqualTo, string userMessage = null) where T : IComparable { // null, by definition is always less than or equal to if (actual == null) return; if (actual.CompareTo(lessThanOrEqualTo) > 0) throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be less than or equal to {lessThanOrEqualTo}", userMessage)); } /// <summary> /// Validate that a given value is greater than or equal to another value. /// </summary> /// <param name="actual">The value that should be greater than or equal to <paramref name="greaterThanOrEqualTo"/></param> /// <param name="greaterThanOrEqualTo">The value that <paramref name="actual"/> should be greater than or equal to.</param> public static void GreaterThanOrEqualTo<T>(T actual, T greaterThanOrEqualTo, string userMessage = null) where T : IComparable { // null, by definition is always less than or equal to if (actual == null) { if (greaterThanOrEqualTo == null) { // We're equal return; } else { // Null is always less than non-null throw new XunitException(AddOptionalUserMessage($"Expected: <null> to be greater than or equal to <null>.", userMessage)); } } if (actual.CompareTo(greaterThanOrEqualTo) < 0) throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be greater than or equal to {greaterThanOrEqualTo}", userMessage)); } } }
// FileSystemScanner.cs // // Copyright 2005 John Reilly // // 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. using System; namespace ICSharpCode.SharpZipLib.Core { #region EventArgs /// <summary> /// Event arguments for scanning. /// </summary> internal class ScanEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name.</param> public ScanEventArgs(string name) { name_ = name; } #endregion /// <summary> /// The file or directory name for this event. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating if scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments during processing of a single file or directory. /// </summary> internal class ProgressEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name if known.</param> /// <param name="processed">The number of bytes processed so far</param> /// <param name="target">The total number of bytes to process, 0 if not known</param> public ProgressEventArgs(string name, long processed, long target) { name_ = name; processed_ = processed; target_ = target; } #endregion /// <summary> /// The name for this event if known. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating wether scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } /// <summary> /// Get a percentage representing how much of the <see cref="Target"></see> has been processed /// </summary> /// <value>0.0 to 100.0 percent; 0 if target is not known.</value> public float PercentComplete { get { float result; if (target_ <= 0) { result = 0; } else { result = ((float)processed_ / (float)target_) * 100.0f; } return result; } } /// <summary> /// The number of bytes processed so far /// </summary> public long Processed { get { return processed_; } } /// <summary> /// The number of bytes to process. /// </summary> /// <remarks>Target may be 0 or negative if the value isnt known.</remarks> public long Target { get { return target_; } } #region Instance Fields string name_; long processed_; long target_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments for directories. /// </summary> internal class DirectoryEventArgs : ScanEventArgs { #region Constructors /// <summary> /// Initialize an instance of <see cref="DirectoryEventArgs"></see>. /// </summary> /// <param name="name">The name for this directory.</param> /// <param name="hasMatchingFiles">Flag value indicating if any matching files are contained in this directory.</param> public DirectoryEventArgs(string name, bool hasMatchingFiles) : base (name) { hasMatchingFiles_ = hasMatchingFiles; } #endregion /// <summary> /// Get a value indicating if the directory contains any matching files or not. /// </summary> public bool HasMatchingFiles { get { return hasMatchingFiles_; } } #region Instance Fields bool hasMatchingFiles_; #endregion } /// <summary> /// Arguments passed when scan failures are detected. /// </summary> internal class ScanFailureEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanFailureEventArgs"></see> /// </summary> /// <param name="name">The name to apply.</param> /// <param name="e">The exception to use.</param> public ScanFailureEventArgs(string name, Exception e) { name_ = name; exception_ = e; continueRunning_ = true; } #endregion /// <summary> /// The applicable name. /// </summary> public string Name { get { return name_; } } /// <summary> /// The applicable exception. /// </summary> public Exception Exception { get { return exception_; } } /// <summary> /// Get / set a value indicating wether scanning should continue. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; Exception exception_; bool continueRunning_; #endregion } #endregion #region Delegates /// <summary> /// Delegate invoked before starting to process a directory. /// </summary> internal delegate void ProcessDirectoryHandler(object sender, DirectoryEventArgs e); /// <summary> /// Delegate invoked before starting to process a file. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void ProcessFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked during processing of a file or directory /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void ProgressHandler(object sender, ProgressEventArgs e); /// <summary> /// Delegate invoked when a file has been completely processed. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void CompletedFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked when a directory failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void DirectoryFailureHandler(object sender, ScanFailureEventArgs e); /// <summary> /// Delegate invoked when a file failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void FileFailureHandler(object sender, ScanFailureEventArgs e); #endregion /// <summary> /// FileSystemScanner provides facilities scanning of files and directories. /// </summary> internal class FileSystemScanner { #region Constructors /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="filter">The <see cref="PathFilter">file filter</see> to apply when scanning.</param> public FileSystemScanner(string filter) { fileFilter_ = new PathFilter(filter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter"> directory filter</see> to apply.</param> public FileSystemScanner(string fileFilter, string directoryFilter) { fileFilter_ = new PathFilter(fileFilter); directoryFilter_ = new PathFilter(directoryFilter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter) { fileFilter_ = fileFilter; } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> /// <param name="directoryFilter">The directory <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter, IScanFilter directoryFilter) { fileFilter_ = fileFilter; directoryFilter_ = directoryFilter; } #endregion #region Delegates /// <summary> /// Delegate to invoke when a directory is processed. /// </summary> public ProcessDirectoryHandler ProcessDirectory; /// <summary> /// Delegate to invoke when a file is processed. /// </summary> public ProcessFileHandler ProcessFile; /// <summary> /// Delegate to invoke when processing for a file has finished. /// </summary> public CompletedFileHandler CompletedFile; /// <summary> /// Delegate to invoke when a directory failure is detected. /// </summary> public DirectoryFailureHandler DirectoryFailure; /// <summary> /// Delegate to invoke when a file failure is detected. /// </summary> public FileFailureHandler FileFailure; #endregion /// <summary> /// Raise the DirectoryFailure event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="e">The exception detected.</param> bool OnDirectoryFailure(string directory, Exception e) { DirectoryFailureHandler handler = DirectoryFailure; bool result = (handler != null); if ( result ) { ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); handler(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the FileFailure event. /// </summary> /// <param name="file">The file name.</param> /// <param name="e">The exception detected.</param> bool OnFileFailure(string file, Exception e) { FileFailureHandler handler = FileFailure; bool result = (handler != null); if ( result ){ ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); FileFailure(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the ProcessFile event. /// </summary> /// <param name="file">The file name.</param> void OnProcessFile(string file) { ProcessFileHandler handler = ProcessFile; if ( handler!= null ) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the complete file event /// </summary> /// <param name="file">The file name</param> void OnCompleteFile(string file) { CompletedFileHandler handler = CompletedFile; if (handler != null) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the ProcessDirectory event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="hasMatchingFiles">Flag indicating if the directory has matching files.</param> void OnProcessDirectory(string directory, bool hasMatchingFiles) { ProcessDirectoryHandler handler = ProcessDirectory; if ( handler != null ) { DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Scan a directory. /// </summary> /// <param name="directory">The base directory to scan.</param> /// <param name="recurse">True to recurse subdirectories, false to scan a single directory.</param> public void Scan(string directory, bool recurse) { alive_ = true; ScanDir(directory, recurse); } void ScanDir(string directory, bool recurse) { try { string[] names = System.IO.Directory.GetFiles(directory); bool hasMatch = false; for (int fileIndex = 0; fileIndex < names.Length; ++fileIndex) { if ( !fileFilter_.IsMatch(names[fileIndex]) ) { names[fileIndex] = null; } else { hasMatch = true; } } OnProcessDirectory(directory, hasMatch); if ( alive_ && hasMatch ) { foreach (string fileName in names) { try { if ( fileName != null ) { OnProcessFile(fileName); if ( !alive_ ) { break; } } } catch (Exception e) { if (!OnFileFailure(fileName, e)) { throw; } } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } if ( alive_ && recurse ) { try { string[] names = System.IO.Directory.GetDirectories(directory); foreach (string fulldir in names) { if ((directoryFilter_ == null) || (directoryFilter_.IsMatch(fulldir))) { ScanDir(fulldir, true); if ( !alive_ ) { break; } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } } } #region Instance Fields /// <summary> /// The file filter currently in use. /// </summary> IScanFilter fileFilter_; /// <summary> /// The directory filter currently in use. /// </summary> IScanFilter directoryFilter_; /// <summary> /// Flag indicating if scanning should continue running. /// </summary> bool alive_; #endregion } }
/************************************************************************* Copyright (c) 1992-2007 The University of Tennessee. All rights reserved. Contributors: * Sergey Bochkanov (ALGLIB project). Translation from FORTRAN to pseudocode. See subroutines comments for additional copyrights. >>> SOURCE LICENSE >>> 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 (www.fsf.org); 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. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ using System; namespace FuncLib.Mathematics.LinearAlgebra.AlgLib { internal class reflections { /************************************************************************* Generation of an elementary reflection transformation The subroutine generates elementary reflection H of order N, so that, for a given X, the following equality holds true: ( X(1) ) ( Beta ) H * ( .. ) = ( 0 ) ( X(n) ) ( 0 ) where ( V(1) ) H = 1 - Tau * ( .. ) * ( V(1), ..., V(n) ) ( V(n) ) where the first component of vector V equals 1. Input parameters: X - vector. Array whose index ranges within [1..N]. N - reflection order. Output parameters: X - components from 2 to N are replaced with vector V. The first component is replaced with parameter Beta. Tau - scalar value Tau. If X is a null vector, Tau equals 0, otherwise 1 <= Tau <= 2. This subroutine is the modification of the DLARFG subroutines from the LAPACK library. MODIFICATIONS: 24.12.2005 sign(Alpha) was replaced with an analogous to the Fortran SIGN code. -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 *************************************************************************/ public static void generatereflection(ref double[] x, int n, ref double tau) { int j = 0; double alpha = 0; double xnorm = 0; double v = 0; double beta = 0; double mx = 0; double s = 0; int i_ = 0; if (n <= 1) { tau = 0; return; } // // Scale if needed (to avoid overflow/underflow during intermediate // calculations). // mx = 0; for (j = 1; j <= n; j++) { mx = Math.Max(Math.Abs(x[j]), mx); } s = 1; if ((double)(mx) != (double)(0)) { if ((double)(mx) <= (double)(AP.Math.MinRealNumber / AP.Math.MachineEpsilon)) { s = AP.Math.MinRealNumber / AP.Math.MachineEpsilon; v = 1 / s; for (i_ = 1; i_ <= n; i_++) { x[i_] = v * x[i_]; } mx = mx * v; } else { if ((double)(mx) >= (double)(AP.Math.MaxRealNumber * AP.Math.MachineEpsilon)) { s = AP.Math.MaxRealNumber * AP.Math.MachineEpsilon; v = 1 / s; for (i_ = 1; i_ <= n; i_++) { x[i_] = v * x[i_]; } mx = mx * v; } } } // // XNORM = DNRM2( N-1, X, INCX ) // alpha = x[1]; xnorm = 0; if ((double)(mx) != (double)(0)) { for (j = 2; j <= n; j++) { xnorm = xnorm + AP.Math.Sqr(x[j] / mx); } xnorm = Math.Sqrt(xnorm) * mx; } if ((double)(xnorm) == (double)(0)) { // // H = I // tau = 0; x[1] = x[1] * s; return; } // // general case // mx = Math.Max(Math.Abs(alpha), Math.Abs(xnorm)); beta = -(mx * Math.Sqrt(AP.Math.Sqr(alpha / mx) + AP.Math.Sqr(xnorm / mx))); if ((double)(alpha) < (double)(0)) { beta = -beta; } tau = (beta - alpha) / beta; v = 1 / (alpha - beta); for (i_ = 2; i_ <= n; i_++) { x[i_] = v * x[i_]; } x[1] = beta; // // Scale back outputs // x[1] = x[1] * s; } /************************************************************************* Application of an elementary reflection to a rectangular matrix of size MxN The algorithm pre-multiplies the matrix by an elementary reflection transformation which is given by column V and scalar Tau (see the description of the GenerateReflection procedure). Not the whole matrix but only a part of it is transformed (rows from M1 to M2, columns from N1 to N2). Only the elements of this submatrix are changed. Input parameters: C - matrix to be transformed. Tau - scalar defining the transformation. V - column defining the transformation. Array whose index ranges within [1..M2-M1+1]. M1, M2 - range of rows to be transformed. N1, N2 - range of columns to be transformed. WORK - working array whose indexes goes from N1 to N2. Output parameters: C - the result of multiplying the input matrix C by the transformation matrix which is given by Tau and V. If N1>N2 or M1>M2, C is not modified. -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 *************************************************************************/ public static void applyreflectionfromtheleft(ref double[,] c, double tau, ref double[] v, int m1, int m2, int n1, int n2, ref double[] work) { double t = 0; int i = 0; int vm = 0; int i_ = 0; if ((double)(tau) == (double)(0) | n1 > n2 | m1 > m2) { return; } // // w := C' * v // vm = m2 - m1 + 1; for (i = n1; i <= n2; i++) { work[i] = 0; } for (i = m1; i <= m2; i++) { t = v[i + 1 - m1]; for (i_ = n1; i_ <= n2; i_++) { work[i_] = work[i_] + t * c[i, i_]; } } // // C := C - tau * v * w' // for (i = m1; i <= m2; i++) { t = v[i - m1 + 1] * tau; for (i_ = n1; i_ <= n2; i_++) { c[i, i_] = c[i, i_] - t * work[i_]; } } } /************************************************************************* Application of an elementary reflection to a rectangular matrix of size MxN The algorithm post-multiplies the matrix by an elementary reflection transformation which is given by column V and scalar Tau (see the description of the GenerateReflection procedure). Not the whole matrix but only a part of it is transformed (rows from M1 to M2, columns from N1 to N2). Only the elements of this submatrix are changed. Input parameters: C - matrix to be transformed. Tau - scalar defining the transformation. V - column defining the transformation. Array whose index ranges within [1..N2-N1+1]. M1, M2 - range of rows to be transformed. N1, N2 - range of columns to be transformed. WORK - working array whose indexes goes from M1 to M2. Output parameters: C - the result of multiplying the input matrix C by the transformation matrix which is given by Tau and V. If N1>N2 or M1>M2, C is not modified. -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 *************************************************************************/ public static void applyreflectionfromtheright(ref double[,] c, double tau, ref double[] v, int m1, int m2, int n1, int n2, ref double[] work) { double t = 0; int i = 0; int vm = 0; int i_ = 0; int i1_ = 0; if ((double)(tau) == (double)(0) | n1 > n2 | m1 > m2) { return; } vm = n2 - n1 + 1; for (i = m1; i <= m2; i++) { i1_ = (1) - (n1); t = 0.0; for (i_ = n1; i_ <= n2; i_++) { t += c[i, i_] * v[i_ + i1_]; } t = t * tau; i1_ = (1) - (n1); for (i_ = n1; i_ <= n2; i_++) { c[i, i_] = c[i, i_] - t * v[i_ + i1_]; } } } } }
namespace Microsoft.Protocols.TestSuites.MS_ASEMAIL { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net.Mail; using System.Threading; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.Common.DataStructures; using Microsoft.Protocols.TestTools; using Request = Microsoft.Protocols.TestSuites.Common.Request; /// <summary> /// The base class of scenario class. /// </summary> public class TestSuiteBase : TestClassBase { #region Properties /// <summary> /// Gets protocol Interface of MS-ASEMAIL /// </summary> protected IMS_ASEMAILAdapter EMAILAdapter { get; private set; } /// <summary> /// Gets or sets the information of User1. /// </summary> protected UserInformation User1Information { get; set; } /// <summary> /// Gets or sets the information of User2. /// </summary> protected UserInformation User2Information { get; set; } /// <summary> /// Gets or sets the information of User3. /// </summary> protected UserInformation User3Information { get; set; } /// <summary> /// Gets or sets the information of User4. /// </summary> protected UserInformation User4Information { get; set; } /// <summary> /// Gets or sets the information of User5. /// </summary> protected UserInformation User5Information { get; set; } #endregion #region Create sync delete operation request /// <summary> /// Create a Sync delete operation request which would be used to delete items permanently. /// </summary> /// <param name="syncKey">The synchronization state of a collection.</param> /// <param name="collectionId">The server ID of the folder.</param> /// <param name="serverId">The server ID of the item which will be deleted.</param> /// <returns>The Sync delete operation request.</returns> protected static SyncRequest CreateSyncPermanentDeleteRequest(string syncKey, string collectionId, string serverId) { Request.SyncCollection syncCollection = new Request.SyncCollection { SyncKey = syncKey, CollectionId = collectionId, WindowSize = "100", DeletesAsMoves = false, DeletesAsMovesSpecified = true }; Request.SyncCollectionDelete deleteData = new Request.SyncCollectionDelete { ServerId = serverId }; syncCollection.Commands = new object[] { deleteData }; return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection }); } #endregion #region Test case initialize and cleanup /// <summary> /// Override the base TestInitialize function /// </summary> protected override void TestInitialize() { base.TestInitialize(); if (this.EMAILAdapter == null) { this.EMAILAdapter = Site.GetAdapter<IMS_ASEMAILAdapter>(); } string domain = Common.GetConfigurationPropertyValue("Domain", this.Site); this.User1Information = new UserInformation { UserName = Common.GetConfigurationPropertyValue("User1Name", this.Site), UserPassword = Common.GetConfigurationPropertyValue("User1Password", this.Site), UserDomain = domain }; this.User2Information = new UserInformation { UserName = Common.GetConfigurationPropertyValue("User2Name", this.Site), UserPassword = Common.GetConfigurationPropertyValue("User2Password", this.Site), UserDomain = domain }; this.User3Information = new UserInformation { UserName = Common.GetConfigurationPropertyValue("User3Name", this.Site), UserPassword = Common.GetConfigurationPropertyValue("User3Password", this.Site), UserDomain = domain }; this.User4Information = new UserInformation { UserName = Common.GetConfigurationPropertyValue("User4Name", this.Site), UserPassword = Common.GetConfigurationPropertyValue("User4Password", this.Site), UserDomain = domain }; this.User5Information = new UserInformation { UserName = Common.GetConfigurationPropertyValue("User5Name", this.Site), UserPassword = Common.GetConfigurationPropertyValue("User5Password", this.Site), UserDomain = domain }; if (Common.GetSutVersion(this.Site) != SutVersion.ExchangeServer2007 || string.Equals(Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "12.1")) { this.SwitchUser(this.User1Information, true); } } /// <summary> /// Override the base TestCleanup function /// </summary> protected override void TestCleanup() { if (this.User1Information.UserCreatedItems.Count != 0) { this.SwitchUser(this.User1Information, false); this.DeleteItemsInFolder(this.User1Information); } if (this.User2Information.UserCreatedItems.Count != 0) { this.SwitchUser(this.User2Information, false); this.DeleteItemsInFolder(this.User2Information); } if (this.User3Information.UserCreatedItems.Count != 0) { this.SwitchUser(this.User3Information, false); this.DeleteItemsInFolder(this.User3Information); } if (this.User4Information.UserCreatedItems.Count != 0) { this.SwitchUser(this.User4Information, false); this.DeleteItemsInFolder(this.User4Information); } if (this.User5Information.UserCreatedItems.Count != 0) { this.SwitchUser(this.User5Information, false); this.DeleteItemsInFolder(this.User5Information); } base.TestCleanup(); } #endregion #region Initialize sync with server /// <summary> /// Sync changes between client and server /// </summary> /// <param name="syncKey">The synchronization key returned by last request.</param> /// <param name="collectionId">Identify the folder as the collection being synchronized.</param> /// <param name="bodyPreference">Sets preference information related to the type and size of information for body</param> /// <returns>Return change result</returns> protected SyncStore SyncChanges(string syncKey, string collectionId, Request.BodyPreference bodyPreference) { // Get changes from server use initial syncKey SyncRequest syncRequest = TestSuiteHelper.CreateSyncRequest(syncKey, collectionId, bodyPreference); SyncStore syncResult = this.EMAILAdapter.Sync(syncRequest); return syncResult; } /// <summary> /// Initialize the sync with server /// </summary> /// <param name="collectionId">Specify the folder collection Id which needs to be synced.</param> /// <returns>Return change result</returns> protected SyncStore InitializeSync(string collectionId) { // Obtains the key by sending an initial Sync request with a SyncKey element value of zero and the CollectionId element SyncRequest syncRequest = Common.CreateInitialSyncRequest(collectionId); SyncStore syncResult = this.EMAILAdapter.Sync(syncRequest); // Verify sync change result Site.Assert.AreEqual<byte>( 1, syncResult.CollectionStatus, "If the Sync command executes successfully, the Status in response should be 1."); return syncResult; } #endregion #region SwitchUser /// <summary> /// Change user to call ActiveSync operations and resynchronize the collection hierarchy. /// </summary> /// <param name="userInformation">The information of the user.</param> /// <param name="isFolderSyncNeeded">A Boolean value that indicates whether needs to synchronize the folder hierarchy.</param> protected void SwitchUser(UserInformation userInformation, bool isFolderSyncNeeded) { this.EMAILAdapter.SwitchUser(userInformation.UserName, userInformation.UserPassword, userInformation.UserDomain); if (isFolderSyncNeeded) { // Call FolderSync command to synchronize the collection hierarchy. FolderSyncRequest folderSyncRequest = Common.CreateFolderSyncRequest("0"); FolderSyncResponse folderSyncResponse = this.EMAILAdapter.FolderSync(folderSyncRequest); // Verify FolderSync command response. Site.Assert.AreEqual<int>( 1, int.Parse(folderSyncResponse.ResponseData.Status), "If the FolderSync command executes successfully, the Status in response should be 1."); if (string.IsNullOrEmpty(userInformation.InboxCollectionId)) { userInformation.InboxCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Inbox, this.Site); } if (string.IsNullOrEmpty(userInformation.DeletedItemsCollectionId)) { userInformation.DeletedItemsCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.DeletedItems, this.Site); } if (string.IsNullOrEmpty(userInformation.CalendarCollectionId)) { userInformation.CalendarCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Calendar, this.Site); } } } #endregion #region Send email /// <summary> /// Send a plain text email. /// </summary> /// <param name="subject">The subject of email</param> /// <param name="cc">The cc address of the mail</param> /// <param name="bcc">The bcc address of the mail</param> /// <param name="to">The to address of the mail</param> /// <param name="sender">The sender address of the mail</param> /// <param name="replyTo">The replyTo address of the mail</param> /// <param name="from">The from address of the mail</param> protected void SendPlaintextEmail( string subject, string cc, string bcc, string to, string sender, string replyTo, string from) { string emailBody = Common.GenerateResourceName(Site, "content"); string emailMime = TestSuiteHelper.CreatePlainTextMime( string.IsNullOrEmpty(from) ? Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain) : from, string.IsNullOrEmpty(to) ? Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain) : to, cc, bcc, subject, emailBody, sender, replyTo); string clientId = TestSuiteHelper.GetClientId(); SendMailRequest sendMailRequest = TestSuiteHelper.CreateSendMailRequest(clientId, false, emailMime); this.SwitchUser(this.User1Information, false); SendMailResponse response = this.EMAILAdapter.SendMail(sendMailRequest); Site.Assert.AreEqual<string>( string.Empty, response.ResponseDataXML, "The server should return an empty xml response data to indicate SendMail command was executed successfully."); } /// <summary> /// Send a plain text email. /// </summary> /// <param name="subject">The subject of email</param> /// <param name="cc">The cc address of the mail</param> /// <param name="bcc">The bcc address of the mail</param> protected void SendPlaintextEmail(string subject, string cc, string bcc) { string emailBody = Common.GenerateResourceName(Site, "content"); string emailMime = TestSuiteHelper.CreatePlainTextMime( Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain), cc, bcc, subject, emailBody); string clientId = TestSuiteHelper.GetClientId(); SendMailRequest sendMailRequest = TestSuiteHelper.CreateSendMailRequest(clientId, false, emailMime); this.SwitchUser(this.User1Information, false); SendMailResponse response = this.EMAILAdapter.SendMail(sendMailRequest); Site.Assert.AreEqual<string>( string.Empty, response.ResponseDataXML, "The server should return an empty xml response data to indicate SendMail command executes successfully."); this.SwitchUser(this.User2Information, true); this.RecordCaseRelativeItems(this.User2Information.UserName, this.User2Information.InboxCollectionId, subject); } /// <summary> /// Send a meeting request email. /// </summary> /// <param name="subject">The subject of email</param> /// <param name="calendar">The meeting calendar</param> protected void SendMeetingRequest(string subject, Calendar calendar) { string emailBody = Common.GenerateResourceName(Site, "content"); string icalendarFormatContent = TestSuiteHelper.CreateiCalendarFormatContent(calendar); string meetingEmailMime = TestSuiteHelper.CreateMeetingRequestMime( calendar.OrganizerEmail, calendar.Attendees.Attendee[0].Email, subject, emailBody, icalendarFormatContent); string clientId = TestSuiteHelper.GetClientId(); SendMailRequest sendMailRequest = TestSuiteHelper.CreateSendMailRequest(clientId, false, meetingEmailMime); this.SwitchUser(this.User1Information, false); SendMailResponse response = this.EMAILAdapter.SendMail(sendMailRequest); Site.Assert.AreEqual<string>( string.Empty, response.ResponseDataXML, "The server should return an empty xml response data to indicate SendMail command success."); } /// <summary> /// Create a default calendar object in the current login user calendar folder /// </summary> /// <param name="subject">The calendar subject</param> /// <param name="organizerEmailAddress">The organizer email address</param> /// <param name="attendeeEmailAddress">The attendee email address</param> /// <param name="calendarUID">The uid of calendar</param> /// <param name="timestamp">The DtStamp of calendar</param> /// <param name="startTime">The StartTime of calendar</param> /// <param name="endTime">The EndTime of calendar</param> /// <returns>Returns the Calendar instance</returns> protected Calendar CreateDefaultCalendar( string subject, string organizerEmailAddress, string attendeeEmailAddress, string calendarUID, DateTime? timestamp, DateTime? startTime, DateTime? endTime) { #region Configure the default calendar application data Request.SyncCollectionAdd syncAddCollection = new Request.SyncCollectionAdd(); string clientId = TestSuiteHelper.GetClientId(); syncAddCollection.ClientId = clientId; syncAddCollection.ApplicationData = new Request.SyncCollectionAddApplicationData(); List<object> items = new List<object>(); List<Request.ItemsChoiceType8> itemsElementName = new List<Request.ItemsChoiceType8>(); if (!Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("12.1")) { items.Add(true); itemsElementName.Add(Request.ItemsChoiceType8.ResponseRequested); } #region TIME/Subject/Location/UID items.Add(string.Format("{0:yyyyMMddTHHmmss}Z", null == startTime ? DateTime.UtcNow.AddDays(5) : startTime.Value)); itemsElementName.Add(Request.ItemsChoiceType8.StartTime); items.Add(string.Format("{0:yyyyMMddTHHmmss}Z", null == endTime ? DateTime.UtcNow.AddDays(5).AddMinutes(30) : endTime.Value)); itemsElementName.Add(Request.ItemsChoiceType8.EndTime); if (!Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("16.0")&&!Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("16.1")) { items.Add(string.Format("{0:yyyyMMddTHHmmss}Z", null == timestamp ? DateTime.UtcNow.AddDays(5) : timestamp.Value)); itemsElementName.Add(Request.ItemsChoiceType8.DtStamp); } items.Add(subject); itemsElementName.Add(Request.ItemsChoiceType8.Subject); items.Add(calendarUID ?? Guid.NewGuid().ToString()); if (Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("16.0") || Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("16.1")) { itemsElementName.Add(Request.ItemsChoiceType8.ClientUid); } else { itemsElementName.Add(Request.ItemsChoiceType8.UID); } if (Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("16.0")|| Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("16.1")) { Request.Location location = new Request.Location(); location.DisplayName = "OFFICE"; items.Add(location); itemsElementName.Add(Request.ItemsChoiceType8.Location); } else { items.Add("OFFICE"); itemsElementName.Add(Request.ItemsChoiceType8.Location1); } #endregion #region Attendee/Organizer Request.AttendeesAttendee attendee = new Request.AttendeesAttendee { Email = attendeeEmailAddress, Name = new MailAddress(attendeeEmailAddress).User, AttendeeStatus = 0x0, AttendeeTypeSpecified = true, AttendeeType = 0x1 }; // 0x0 = Response unknown // 0x1 = Required items.Add(new Request.Attendees() { Attendee = new Request.AttendeesAttendee[] { attendee } }); itemsElementName.Add(Request.ItemsChoiceType8.Attendees); if (!Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("16.0")&& !Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("16.1")) { items.Add(organizerEmailAddress); itemsElementName.Add(Request.ItemsChoiceType8.OrganizerEmail); items.Add(new MailAddress(organizerEmailAddress).DisplayName); itemsElementName.Add(Request.ItemsChoiceType8.OrganizerName); } #endregion #region Sensitivity/BusyStatus/AllDayEvent // 0x0 == Normal items.Add((byte)0x0); itemsElementName.Add(Request.ItemsChoiceType8.Sensitivity); // 0x1 == Tentative items.Add((byte)0x1); itemsElementName.Add(Request.ItemsChoiceType8.BusyStatus); // 0x0 not an all-day event items.Add((byte)0x0); itemsElementName.Add(Request.ItemsChoiceType8.AllDayEvent); #endregion syncAddCollection.ApplicationData.Items = items.ToArray(); syncAddCollection.ApplicationData.ItemsElementName = itemsElementName.ToArray(); #endregion #region Execute the Sync command to upload the calendar SyncStore initSyncResponse = this.InitializeSync(this.User1Information.CalendarCollectionId); SyncRequest uploadCalendarRequest = TestSuiteHelper.CreateSyncAddRequest(initSyncResponse.SyncKey, this.User1Information.CalendarCollectionId, syncAddCollection); this.EMAILAdapter.Sync(uploadCalendarRequest); #endregion #region Get the new added calendar item SyncStore getItemResponse = this.GetSyncResult(subject, this.User1Information.CalendarCollectionId, null); Sync calendarItem = TestSuiteHelper.GetSyncAddItem(getItemResponse, subject); Site.Assert.IsNotNull(calendarItem, "The item with subject {0} should be found in the folder {1}.", subject, FolderType.Calendar.ToString()); #endregion return calendarItem.Calendar; } /// <summary> /// Send a meeting response email /// </summary> /// <param name="calendar">The meeting calendar</param> protected void SendMeetingResponse(Calendar calendar) { // Create reply mail to organizer string emailBody = Common.GenerateResourceName(Site, "content"); string icalendarResponseContent = TestSuiteHelper.CreateMeetingResponseiCalendarFormatContent( (DateTime)calendar.DtStamp, (DateTime)calendar.EndTime, calendar.UID, calendar.Subject, calendar.Location, calendar.OrganizerEmail, calendar.Attendees.Attendee[0].Email); // Create reply mail mime content string meetingResponseEmailMime = TestSuiteHelper.CreateMeetingRequestMime( calendar.Attendees.Attendee[0].Email, calendar.OrganizerEmail, calendar.Subject, emailBody, icalendarResponseContent); string clientId = TestSuiteHelper.GetClientId(); SendMailRequest sendMailRequest = TestSuiteHelper.CreateSendMailRequest(clientId, false, meetingResponseEmailMime); this.SwitchUser(this.User2Information, true); SendMailResponse response = this.EMAILAdapter.SendMail(sendMailRequest); Site.Assert.AreEqual<string>( string.Empty, response.ResponseDataXML, "The server should return an empty xml response data to indicate SendMail command success."); } #endregion #region Get Sync add result /// <summary> /// Get the specified email item. /// </summary> /// <param name="emailSubject">The subject of the email item.</param> /// <param name="folderCollectionId">The serverId of the default folder.</param> /// <param name="bodyPreference">The preference information related to the type and size of information that is returned from fetching.</param> /// <returns>The result of getting the specified email item.</returns> protected SyncStore GetSyncResult(string emailSubject, string folderCollectionId, Request.BodyPreference bodyPreference) { SyncStore syncItemResult; Sync item = null; int counter = 0; int waitTime = int.Parse(Common.GetConfigurationPropertyValue("WaitTime", this.Site)); int retryCount = int.Parse(Common.GetConfigurationPropertyValue("RetryCount", this.Site)); do { Thread.Sleep(waitTime); // Get the new added email item SyncStore initSyncResult = this.InitializeSync(folderCollectionId); syncItemResult = this.SyncChanges(initSyncResult.SyncKey, folderCollectionId, bodyPreference); if (syncItemResult != null && syncItemResult.CollectionStatus == 1) { item = TestSuiteHelper.GetSyncAddItem(syncItemResult, emailSubject); } counter++; } while ((syncItemResult == null || item == null) && counter < retryCount); Site.Assert.IsNotNull(item, "The email item with subject {0} should be found. Retry count: {1}", emailSubject, counter); // Verify sync result Site.Assert.AreEqual<byte>( 1, syncItemResult.CollectionStatus, "If the Sync command executes successfully, the status in response should be 1."); return syncItemResult; } #endregion #region Update email /// <summary> /// Update email /// </summary> /// <param name="collectionId">The collectionId of the folder which contains the item to be updated.</param> /// <param name="syncKey">The syncKey which is returned from server</param> /// <param name="read">The value is TRUE indicates the email has been read; a value of FALSE indicates the email has not been read</param> /// <param name="serverId">The server id of the email</param> /// <param name="flag">The flag instance</param> /// <param name="categories">The array of categories</param> /// <returns>Return update email result</returns> protected SyncStore UpdateEmail(string collectionId, string syncKey, bool? read, string serverId, Request.Flag flag, Collection<string> categories) { Request.SyncCollectionChange changeData = new Request.SyncCollectionChange { ServerId = serverId, ApplicationData = new Request.SyncCollectionChangeApplicationData() }; List<object> items = new List<object>(); List<Request.ItemsChoiceType7> itemsElementName = new List<Request.ItemsChoiceType7>(); if (null != read) { items.Add(read); itemsElementName.Add(Request.ItemsChoiceType7.Read); } if (null != flag) { items.Add(flag); itemsElementName.Add(Request.ItemsChoiceType7.Flag); } if (null != categories) { Request.Categories2 mailCategories = new Request.Categories2 { Category = new string[categories.Count] }; categories.CopyTo(mailCategories.Category, 0); items.Add(mailCategories); itemsElementName.Add(Request.ItemsChoiceType7.Categories2); } changeData.ApplicationData.Items = items.ToArray(); changeData.ApplicationData.ItemsElementName = itemsElementName.ToArray(); SyncRequest syncRequest = TestSuiteHelper.CreateSyncChangeRequest(syncKey, collectionId, changeData); SyncStore result = this.EMAILAdapter.Sync(syncRequest); Site.Assert.AreEqual<byte>( 1, result.CollectionStatus, "The server returns a Status 1 in the Sync command response indicate sync command success."); return result; } /// <summary> /// Update email with more data /// </summary> /// <param name="collectionId">The collectionId of the folder which contains the item to be updated.</param> /// <param name="syncKey">The syncKey which is returned from server</param> /// <param name="read">The value is TRUE indicates the email has been read; a value of FALSE indicates the email has not been read</param> /// <param name="serverId">The server id of the email</param> /// <param name="flag">The flag instance</param> /// <param name="categories">The list of categories</param> /// <param name="additionalElement">Additional flag element</param> /// <param name="insertTag">Additional element will insert before this tag</param> /// <returns>Return update email result</returns> protected SendStringResponse UpdateEmailWithMoreData(string collectionId, string syncKey, bool read, string serverId, Request.Flag flag, Collection<object> categories, string additionalElement, string insertTag) { // Create normal sync request Request.SyncCollectionChange changeData = TestSuiteHelper.CreateSyncChangeData(read, serverId, flag, categories); SyncRequest syncRequest = TestSuiteHelper.CreateSyncChangeRequest(syncKey, collectionId, changeData); // Calls Sync command to update email with invalid sync request SendStringResponse result = this.EMAILAdapter.InvalidSync(syncRequest, additionalElement, insertTag); return result; } #endregion #region Add a meeting to the server /// <summary> /// Add a meeting to the server. /// </summary> /// <param name="calendarCollectionId">The collectionId of the folder which the item should be added.</param> /// <param name="elementsToValueMap">The key and value pairs of common meeting properties.</param> protected void SyncAddMeeting(string calendarCollectionId, Dictionary<Request.ItemsChoiceType8, object> elementsToValueMap) { Request.SyncCollectionAddApplicationData applicationData = new Request.SyncCollectionAddApplicationData { Items = new object[elementsToValueMap.Count], ItemsElementName = new Request.ItemsChoiceType8[elementsToValueMap.Count] }; if (elementsToValueMap.Count > 0) { elementsToValueMap.Values.CopyTo(applicationData.Items, 0); elementsToValueMap.Keys.CopyTo(applicationData.ItemsElementName, 0); } SyncStore iniSync = this.InitializeSync(calendarCollectionId); SyncRequest syncAddRequest = TestSuiteHelper.CreateSyncAddRequest(iniSync.SyncKey, calendarCollectionId, applicationData); SyncStore syncAddResponse = this.EMAILAdapter.Sync(syncAddRequest); Site.Assert.AreEqual<int>( 1, int.Parse(syncAddResponse.AddResponses[0].Status), "The sync add operation should be successful."); } #endregion #region Record the userName, folder collectionId and item subject /// <summary> /// Record the user name, folder collectionId and subjects the current test case impacts. /// </summary> /// <param name="userName">The user that current test case used.</param> /// <param name="folderCollectionId">The collectionId of folders that the current test case impact.</param> /// <param name="itemSubjects">The subject of items that the current test case impact.</param> protected void RecordCaseRelativeItems(string userName, string folderCollectionId, params string[] itemSubjects) { // Record the item in the specified folder. CreatedItems createdItems = new CreatedItems { CollectionId = folderCollectionId }; foreach (string subject in itemSubjects) { createdItems.ItemSubject.Add(subject); } // Record the created items of User1. if (userName == this.User1Information.UserName) { this.User1Information.UserCreatedItems.Add(createdItems); } else if (userName == this.User2Information.UserName) { this.User2Information.UserCreatedItems.Add(createdItems); } else if (userName == this.User3Information.UserName) { this.User3Information.UserCreatedItems.Add(createdItems); } else if (userName == this.User4Information.UserName) { this.User4Information.UserCreatedItems.Add(createdItems); } else if (userName == this.User5Information.UserName) { this.User5Information.UserCreatedItems.Add(createdItems); } } #endregion #region Private method /// <summary> /// Delete all the items in a folder. /// </summary> /// <param name="userInformation">The user information which contains user created items</param> private void DeleteItemsInFolder(UserInformation userInformation) { foreach (CreatedItems createdItems in userInformation.UserCreatedItems) { SyncStore syncStore = this.InitializeSync(createdItems.CollectionId); SyncStore result = this.SyncChanges(syncStore.SyncKey, createdItems.CollectionId, null); string syncKey = result.SyncKey; int retryCount = int.Parse(Common.GetConfigurationPropertyValue("RetryCount", this.Site)); int waitTime = int.Parse(Common.GetConfigurationPropertyValue("WaitTime", this.Site)); int counter = 0; do { Thread.Sleep(waitTime); if (result != null) { if (result.CollectionStatus == 1) { break; } } counter++; } while (counter < retryCount / 10); if (result.AddElements != null) { SyncRequest deleteRequest; foreach (Sync syncItem in result.AddElements) { if (createdItems.CollectionId == userInformation.CalendarCollectionId) { foreach (string subject in createdItems.ItemSubject) { if (syncItem.Calendar != null && syncItem.Calendar.Subject != null) { if (syncItem.Calendar.Subject.Equals(subject, StringComparison.CurrentCultureIgnoreCase)) { deleteRequest = CreateSyncPermanentDeleteRequest(syncKey, createdItems.CollectionId, syncItem.ServerId); SyncStore deleteSyncResult = this.EMAILAdapter.Sync(deleteRequest); syncKey = deleteSyncResult.SyncKey; Site.Assert.AreEqual<byte>(1, deleteSyncResult.CollectionStatus, "Item should be deleted."); } } } } else { List<Request.SyncCollectionDelete> deleteData = new List<Request.SyncCollectionDelete>(); foreach (string subject in createdItems.ItemSubject) { string serverId = null; if (result != null) { foreach (Sync item in result.AddElements) { if (item.Email.Subject != null && item.Email.Subject.Contains(subject)) { serverId = item.ServerId; break; } if (item.Calendar.Subject != null && item.Calendar.Subject.Contains(subject)) { serverId = item.ServerId; break; } } } if (serverId != null) { deleteData.Add(new Request.SyncCollectionDelete() { ServerId = serverId }); } } if (deleteData.Count > 0) { Request.SyncCollection syncCollection = TestSuiteHelper.CreateSyncCollection(syncKey, createdItems.CollectionId); syncCollection.Commands = deleteData.ToArray(); syncCollection.DeletesAsMoves = false; syncCollection.DeletesAsMovesSpecified = true; SyncRequest syncRequest = Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection }); SyncStore deleteResult = this.EMAILAdapter.Sync(syncRequest); syncKey = deleteResult.SyncKey; Site.Assert.AreEqual<byte>( 1, deleteResult.CollectionStatus, "The value of Status should be 1 to indicate the Sync command executes successfully."); } } } } } } #endregion } }
namespace StripeTests { using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Stripe; using Xunit; public class PaymentIntentServiceTest : BaseStripeTest { private const string PaymentIntentId = "pi_123"; private readonly PaymentIntentService service; private readonly PaymentIntentCancelOptions cancelOptions; private readonly PaymentIntentCaptureOptions captureOptions; private readonly PaymentIntentConfirmOptions confirmOptions; private readonly PaymentIntentCreateOptions createOptions; private readonly PaymentIntentListOptions listOptions; private readonly PaymentIntentUpdateOptions updateOptions; public PaymentIntentServiceTest( StripeMockFixture stripeMockFixture, MockHttpClientFixture mockHttpClientFixture) : base(stripeMockFixture, mockHttpClientFixture) { this.service = new PaymentIntentService(this.StripeClient); this.cancelOptions = new PaymentIntentCancelOptions { }; this.captureOptions = new PaymentIntentCaptureOptions { AmountToCapture = 123, }; this.confirmOptions = new PaymentIntentConfirmOptions { ReceiptEmail = "stripe@stripe.com", }; this.createOptions = new PaymentIntentCreateOptions { Amount = 1000, Currency = "usd", PaymentMethodTypes = new List<string> { "card", }, TransferData = new PaymentIntentTransferDataOptions { Amount = 100, Destination = "acct_123", } }; this.listOptions = new PaymentIntentListOptions { Limit = 1, }; this.updateOptions = new PaymentIntentUpdateOptions { Metadata = new Dictionary<string, string> { { "key", "value" }, }, }; } [Fact] public void Cancel() { var intent = this.service.Cancel(PaymentIntentId, this.cancelOptions); this.AssertRequest(HttpMethod.Post, "/v1/payment_intents/pi_123/cancel"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public async Task CancelAsync() { var intent = await this.service.CancelAsync(PaymentIntentId, this.cancelOptions); this.AssertRequest(HttpMethod.Post, "/v1/payment_intents/pi_123/cancel"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public void Capture() { var intent = this.service.Capture(PaymentIntentId, this.captureOptions); this.AssertRequest(HttpMethod.Post, "/v1/payment_intents/pi_123/capture"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public async Task CaptureAsync() { var intent = await this.service.CaptureAsync(PaymentIntentId, this.captureOptions); this.AssertRequest(HttpMethod.Post, "/v1/payment_intents/pi_123/capture"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public void Confirm() { var intent = this.service.Confirm(PaymentIntentId, this.confirmOptions); this.AssertRequest(HttpMethod.Post, "/v1/payment_intents/pi_123/confirm"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public async Task ConfirmAsync() { var intent = await this.service.ConfirmAsync(PaymentIntentId, this.confirmOptions); this.AssertRequest(HttpMethod.Post, "/v1/payment_intents/pi_123/confirm"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public void Create() { var intent = this.service.Create(this.createOptions); this.AssertRequest(HttpMethod.Post, "/v1/payment_intents"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public async Task CreateAsync() { var intent = await this.service.CreateAsync(this.createOptions); this.AssertRequest(HttpMethod.Post, "/v1/payment_intents"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public void Get() { var intent = this.service.Get(PaymentIntentId); this.AssertRequest(HttpMethod.Get, "/v1/payment_intents/pi_123"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public async Task GetAsync() { var intent = await this.service.GetAsync(PaymentIntentId); this.AssertRequest(HttpMethod.Get, "/v1/payment_intents/pi_123"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public void GetWithClientSecret() { var options = new PaymentIntentGetOptions { ClientSecret = "pi_client_secret_123", }; var intent = this.service.Get(PaymentIntentId, options); this.AssertRequest(HttpMethod.Get, "/v1/payment_intents/pi_123"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public void List() { var intents = this.service.List(this.listOptions); this.AssertRequest(HttpMethod.Get, "/v1/payment_intents"); Assert.NotNull(intents); Assert.Equal("list", intents.Object); Assert.Single(intents.Data); Assert.Equal("payment_intent", intents.Data[0].Object); } [Fact] public async Task ListAsync() { var intents = await this.service.ListAsync(this.listOptions); this.AssertRequest(HttpMethod.Get, "/v1/payment_intents"); Assert.NotNull(intents); Assert.Equal("list", intents.Object); Assert.Single(intents.Data); Assert.Equal("payment_intent", intents.Data[0].Object); } [Fact] public void ListAutoPaging() { var intents = this.service.ListAutoPaging(this.listOptions).ToList(); Assert.NotNull(intents); Assert.Equal("payment_intent", intents[0].Object); } [Fact] public void Update() { var intent = this.service.Update(PaymentIntentId, this.updateOptions); this.AssertRequest(HttpMethod.Post, "/v1/payment_intents/pi_123"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } [Fact] public async Task UpdateAsync() { var intent = await this.service.UpdateAsync(PaymentIntentId, this.updateOptions); this.AssertRequest(HttpMethod.Post, "/v1/payment_intents/pi_123"); Assert.NotNull(intent); Assert.Equal("payment_intent", intent.Object); } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; /* * AvaTax API Client Library * * (c) 2004-2019 Avalara, Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Genevieve Conty * @author Greg Hester * Swagger name: AvaTaxClient */ namespace Avalara.AvaTax.RestClient { /// <summary> /// An individual tax detail element. Represents the amount of tax calculated for a particular jurisdiction, for a particular line in an invoice. /// </summary> public class TransactionLineDetailModel { /// <summary> /// The unique ID number of this tax detail. /// </summary> public Int64? id { get; set; } /// <summary> /// The unique ID number of the line within this transaction. /// </summary> public Int64? transactionLineId { get; set; } /// <summary> /// The unique ID number of this transaction. /// </summary> public Int64? transactionId { get; set; } /// <summary> /// The unique ID number of the address used for this tax detail. /// </summary> public Int64? addressId { get; set; } /// <summary> /// The two character ISO 3166 country code of the country where this tax detail is assigned. /// </summary> public String country { get; set; } /// <summary> /// The two-or-three character ISO region code for the region where this tax detail is assigned. /// </summary> public String region { get; set; } /// <summary> /// For U.S. transactions, the Federal Information Processing Standard (FIPS) code for the county where this tax detail is assigned. /// </summary> public String countyFIPS { get; set; } /// <summary> /// For U.S. transactions, the Federal Information Processing Standard (FIPS) code for the state where this tax detail is assigned. /// </summary> public String stateFIPS { get; set; } /// <summary> /// The amount of this line that was considered exempt in this tax detail. /// </summary> public Decimal? exemptAmount { get; set; } /// <summary> /// The unique ID number of the exemption reason for this tax detail. /// </summary> public Int32? exemptReasonId { get; set; } /// <summary> /// True if this detail element represented an in-state transaction. /// </summary> public Boolean? inState { get; set; } /// <summary> /// The code of the jurisdiction to which this tax detail applies. /// </summary> public String jurisCode { get; set; } /// <summary> /// The name of the jurisdiction to which this tax detail applies. /// </summary> public String jurisName { get; set; } /// <summary> /// The unique ID number of the jurisdiction to which this tax detail applies. /// </summary> public Int32? jurisdictionId { get; set; } /// <summary> /// The Avalara-specified signature code of the jurisdiction to which this tax detail applies. /// </summary> public String signatureCode { get; set; } /// <summary> /// The state assigned number of the jurisdiction to which this tax detail applies. /// </summary> public String stateAssignedNo { get; set; } /// <summary> /// DEPRECATED - Date: 12/20/2017, Version: 18.1, Message: Use jurisdictionTypeId instead. /// The type of the jurisdiction to which this tax detail applies. /// </summary> public JurisTypeId? jurisType { get; set; } /// <summary> /// The type of the jurisdiction in which this tax detail applies. /// </summary> public JurisdictionType? jurisdictionType { get; set; } /// <summary> /// The amount of this line item that was considered nontaxable in this tax detail. /// </summary> public Decimal? nonTaxableAmount { get; set; } /// <summary> /// The rule according to which portion of this detail was considered nontaxable. /// </summary> public Int32? nonTaxableRuleId { get; set; } /// <summary> /// The type of nontaxability that was applied to this tax detail. /// </summary> public TaxRuleTypeId? nonTaxableType { get; set; } /// <summary> /// The rate at which this tax detail was calculated. /// </summary> public Decimal? rate { get; set; } /// <summary> /// The unique ID number of the rule according to which this tax detail was calculated. /// </summary> public Int32? rateRuleId { get; set; } /// <summary> /// The unique ID number of the source of the rate according to which this tax detail was calculated. /// </summary> public Int32? rateSourceId { get; set; } /// <summary> /// For Streamlined Sales Tax customers, the SST Electronic Return code under which this tax detail should be applied. /// </summary> public String serCode { get; set; } /// <summary> /// Indicates whether this tax detail applies to the origin or destination of the transaction. /// </summary> public Sourcing? sourcing { get; set; } /// <summary> /// The amount of tax for this tax detail. /// </summary> public Decimal? tax { get; set; } /// <summary> /// The taxable amount of this tax detail. /// </summary> public Decimal? taxableAmount { get; set; } /// <summary> /// The type of tax that was calculated. Depends on the company's nexus settings as well as the jurisdiction's tax laws. /// </summary> public String taxType { get; set; } /// <summary> /// The id of the tax subtype. /// </summary> public String taxSubTypeId { get; set; } /// <summary> /// The id of the tax type group. /// </summary> public String taxTypeGroupId { get; set; } /// <summary> /// The name of the tax against which this tax amount was calculated. /// </summary> public String taxName { get; set; } /// <summary> /// The type of the tax authority to which this tax will be remitted. /// </summary> public Int32? taxAuthorityTypeId { get; set; } /// <summary> /// The unique ID number of the tax region. /// </summary> public Int32? taxRegionId { get; set; } /// <summary> /// The amount of tax that AvaTax calculated. /// If an override for tax amount is used, there may be a difference between the tax /// field which applies your override, and the this amount that is calculated without override. /// </summary> public Decimal? taxCalculated { get; set; } /// <summary> /// The amount of tax override that was specified for this tax line. /// </summary> public Decimal? taxOverride { get; set; } /// <summary> /// DEPRECATED - Date: 12/20/2017, Version: 18.1, Message: Please use rateTypeCode instead. /// The rate type for this tax detail. /// </summary> public RateType? rateType { get; set; } /// <summary> /// Indicates the code of the rate type that was used to calculate this tax detail. Use [ListRateTypesByCountry](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListRateTypesByCountry/) API for a full list of rate type codes. /// </summary> public String rateTypeCode { get; set; } /// <summary> /// Number of units in this line item that were calculated to be taxable according to this rate detail. /// </summary> public Decimal? taxableUnits { get; set; } /// <summary> /// Number of units in this line item that were calculated to be nontaxable according to this rate detail. /// </summary> public Decimal? nonTaxableUnits { get; set; } /// <summary> /// Number of units in this line item that were calculated to be exempt according to this rate detail. /// </summary> public Decimal? exemptUnits { get; set; } /// <summary> /// When calculating units, what basis of measurement did we use for calculating the units? /// </summary> public String unitOfBasis { get; set; } /// <summary> /// True if this value is a non-passthrough tax. /// /// A non-passthrough tax is a tax that may not be charged to a customer; it must be paid directly by the company. /// </summary> public Boolean? isNonPassThru { get; set; } /// <summary> /// The Taxes/Fee component. True if the fee is applied. /// </summary> public Boolean? isFee { get; set; } /// <summary> /// Number of units in this line item that were calculated to be taxable according to this rate detail in the reporting currency. /// </summary> public Decimal? reportingTaxableUnits { get; set; } /// <summary> /// Number of units in this line item that were calculated to be nontaxable according to this rate detail in the reporting currency. /// </summary> public Decimal? reportingNonTaxableUnits { get; set; } /// <summary> /// Number of units in this line item that were calculated to be exempt according to this rate detail in the reporting currency. /// </summary> public Decimal? reportingExemptUnits { get; set; } /// <summary> /// The amount of tax for this tax detail in the reporting currency. /// </summary> public Decimal? reportingTax { get; set; } /// <summary> /// The amount of tax that AvaTax calculated in the reporting currency. /// If an override for tax amount is used, there may be a difference between the tax /// field which applies your override, and the this amount that is calculated without override. /// </summary> public Decimal? reportingTaxCalculated { get; set; } /// <summary> /// LiabilityType identifies the party liable to file the tax. This field is used to filter taxes from reports and tax filings as appropriate. /// </summary> public LiabilityType? liabilityType { get; set; } /// <summary> /// Convert this object to a JSON string of itself /// </summary> /// <returns>A JSON string of this object</returns> public override string ToString() { return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented }); } } }